]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/sql_create.c
bef5a43b433c0283762269626983dd2f268dc176
[bacula/bacula] / bacula / src / cats / sql_create.c
1 /*
2  * Bacula Catalog Database Create record interface routines
3  *
4  *    Kern Sibbald, March 2000
5  *
6  *    Version $Id$
7  */
8
9 /*
10    Copyright (C) 2000-2005 Kern Sibbald
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 /* The following is necessary so that we do not include
30  * the dummy external definition of DB.
31  */
32 #define __SQL_C                       /* indicate that this is sql.c */
33
34 #include "bacula.h"
35 #include "cats.h"
36
37 #if    HAVE_SQLITE3 || HAVE_MYSQL || HAVE_SQLITE || HAVE_POSTGRESQL
38
39 /* -----------------------------------------------------------------------
40  *
41  *   Generic Routines (or almost generic)
42  *
43  * -----------------------------------------------------------------------
44  */
45
46 /* Forward referenced subroutines */
47 static int db_create_file_record(JCR *jcr, B_DB *mdb, ATTR_DBR *ar);
48 static int db_create_filename_record(JCR *jcr, B_DB *mdb, ATTR_DBR *ar);
49 static int db_create_path_record(JCR *jcr, B_DB *mdb, ATTR_DBR *ar);
50
51
52 /* Imported subroutines */
53 extern void print_dashes(B_DB *mdb);
54 extern void print_result(B_DB *mdb);
55 extern int QueryDB(const char *file, int line, JCR *jcr, B_DB *db, char *select_cmd);
56 extern int InsertDB(const char *file, int line, JCR *jcr, B_DB *db, char *select_cmd);
57 extern int UpdateDB(const char *file, int line, JCR *jcr, B_DB *db, char *update_cmd);
58 extern void split_path_and_file(JCR *jcr, B_DB *mdb, const char *fname);
59
60
61 /* Create a new record for the Job
62  * Returns: 0 on failure
63  *          1 on success
64  */
65 int
66 db_create_job_record(JCR *jcr, B_DB *mdb, JOB_DBR *jr)
67 {
68    char dt[MAX_TIME_LENGTH];
69    time_t stime;
70    struct tm tm;
71    int stat;
72    utime_t JobTDate;
73    char ed1[30];
74
75    db_lock(mdb);
76
77    stime = jr->SchedTime;
78    ASSERT(stime != 0);
79
80    localtime_r(&stime, &tm);
81    strftime(dt, sizeof(dt), "%Y-%m-%d %T", &tm);
82    JobTDate = (utime_t)stime;
83
84    /* Must create it */
85    Mmsg(mdb->cmd,
86 "INSERT INTO Job (Job,Name,Type,Level,JobStatus,SchedTime,JobTDate) VALUES "
87 "('%s','%s','%c','%c','%c','%s',%s)",
88            jr->Job, jr->Name, (char)(jr->JobType), (char)(jr->JobLevel),
89            (char)(jr->JobStatus), dt, edit_uint64(JobTDate, ed1));
90
91    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
92       Mmsg2(&mdb->errmsg, _("Create DB Job record %s failed. ERR=%s\n"),
93             mdb->cmd, sql_strerror(mdb));
94       jr->JobId = 0;
95       stat = 0;
96    } else {
97       jr->JobId = sql_insert_id(mdb, _("Job"));
98       stat = 1;
99    }
100    db_unlock(mdb);
101    return stat;
102 }
103
104 /* Create a JobMedia record for medium used this job
105  * Returns: false on failure
106  *          true  on success
107  */
108 bool
109 db_create_jobmedia_record(JCR *jcr, B_DB *mdb, JOBMEDIA_DBR *jm)
110 {
111    bool ok = true;;
112    int count;
113    char ed1[50], ed2[50];
114
115    db_lock(mdb);
116
117    /* Now get count for VolIndex */
118    Mmsg(mdb->cmd, "SELECT count(*) from JobMedia");
119    count = get_sql_record_max(jcr, mdb);
120    if (count < 0) {
121       count = 0;
122    }
123    count++;
124
125    Mmsg(mdb->cmd,
126         "INSERT INTO JobMedia (JobId,MediaId,FirstIndex,LastIndex,"
127         "StartFile,EndFile,StartBlock,EndBlock,VolIndex,Copy,Stripe) "
128         "VALUES (%s,%s,%u,%u,%u,%u,%u,%u,%u,%u,%u)",
129         edit_int64(jm->JobId, ed1),
130         edit_int64(jm->MediaId, ed2),
131         jm->FirstIndex, jm->LastIndex,
132         jm->StartFile, jm->EndFile, jm->StartBlock, jm->EndBlock,count,
133         jm->Copy, jm->Stripe);
134
135    Dmsg0(300, mdb->cmd);
136    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
137       Mmsg2(&mdb->errmsg, _("Create JobMedia record %s failed: ERR=%s\n"), mdb->cmd,
138          sql_strerror(mdb));
139       ok = false;
140    } else {
141       /* Worked, now update the Media record with the EndFile and EndBlock */
142       Mmsg(mdb->cmd,
143            "UPDATE Media SET EndFile=%u, EndBlock=%u WHERE MediaId=%u",
144            jm->EndFile, jm->EndBlock, jm->MediaId);
145       if (!UPDATE_DB(jcr, mdb, mdb->cmd)) {
146          Mmsg2(&mdb->errmsg, _("Update Media record %s failed: ERR=%s\n"), mdb->cmd,
147               sql_strerror(mdb));
148          ok = false;
149       }
150    }
151    db_unlock(mdb);
152    Dmsg0(300, "Return from JobMedia\n");
153    return ok;
154 }
155
156
157
158 /* Create Unique Pool record
159  * Returns: false on failure
160  *          true  on success
161  */
162 bool
163 db_create_pool_record(JCR *jcr, B_DB *mdb, POOL_DBR *pr)
164 {
165    bool stat;        
166    char ed1[30], ed2[30], ed3[50];
167
168    Dmsg0(200, "In create pool\n");
169    db_lock(mdb);
170    Mmsg(mdb->cmd, "SELECT PoolId,Name FROM Pool WHERE Name='%s'", pr->Name);
171    Dmsg1(200, "selectpool: %s\n", mdb->cmd);
172
173    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
174       mdb->num_rows = sql_num_rows(mdb);
175       if (mdb->num_rows > 0) {
176          Mmsg1(&mdb->errmsg, _("pool record %s already exists\n"), pr->Name);
177          sql_free_result(mdb);
178          db_unlock(mdb);
179          return false;
180       }
181       sql_free_result(mdb);
182    }
183
184    /* Must create it */
185    Mmsg(mdb->cmd,
186 "INSERT INTO Pool (Name,NumVols,MaxVols,UseOnce,UseCatalog,"
187 "AcceptAnyVolume,AutoPrune,Recycle,VolRetention,VolUseDuration,"
188 "MaxVolJobs,MaxVolFiles,MaxVolBytes,PoolType,LabelType,LabelFormat) "
189 "VALUES ('%s',%u,%u,%d,%d,%d,%d,%d,%s,%s,%u,%u,%s,'%s',%d,'%s')",
190                   pr->Name,
191                   pr->NumVols, pr->MaxVols,
192                   pr->UseOnce, pr->UseCatalog,
193                   pr->AcceptAnyVolume,
194                   pr->AutoPrune, pr->Recycle,
195                   edit_uint64(pr->VolRetention, ed1),
196                   edit_uint64(pr->VolUseDuration, ed2),
197                   pr->MaxVolJobs, pr->MaxVolFiles,
198                   edit_uint64(pr->MaxVolBytes, ed3),
199                   pr->PoolType, pr->LabelType, pr->LabelFormat);
200    Dmsg1(200, "Create Pool: %s\n", mdb->cmd);
201    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
202       Mmsg2(&mdb->errmsg, _("Create db Pool record %s failed: ERR=%s\n"),
203             mdb->cmd, sql_strerror(mdb));
204       pr->PoolId = 0;
205       stat = false;
206    } else {
207       pr->PoolId = sql_insert_id(mdb, _("Pool"));
208       stat = true;
209    }
210    db_unlock(mdb);
211    return stat;
212 }
213
214 /*
215  * Create Unique Device record
216  * Returns: false on failure
217  *          true  on success
218  */
219 bool
220 db_create_device_record(JCR *jcr, B_DB *mdb, DEVICE_DBR *dr)
221 {
222    bool ok;
223    char ed1[30], ed2[30];
224
225    Dmsg0(200, "In create Device\n");
226    db_lock(mdb);
227    Mmsg(mdb->cmd, "SELECT DeviceId,Name FROM Device WHERE Name='%s'", dr->Name);
228    Dmsg1(200, "selectdevice: %s\n", mdb->cmd);
229
230    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
231       mdb->num_rows = sql_num_rows(mdb);
232       if (mdb->num_rows > 0) {
233          Mmsg1(&mdb->errmsg, _("Device record %s already exists\n"), dr->Name);
234          sql_free_result(mdb);
235          db_unlock(mdb);
236          return false;
237       }
238       sql_free_result(mdb);
239    }
240
241    /* Must create it */
242    Mmsg(mdb->cmd,
243 "INSERT INTO Device (Name,MediaTypeId,StorageId) VALUES ('%s',%s,%s)",
244                   dr->Name,
245                   edit_uint64(dr->MediaTypeId, ed1),
246                   edit_int64(dr->StorageId, ed2));
247    Dmsg1(200, "Create Device: %s\n", mdb->cmd);
248    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
249       Mmsg2(&mdb->errmsg, _("Create db Device record %s failed: ERR=%s\n"),
250             mdb->cmd, sql_strerror(mdb));
251       dr->DeviceId = 0;
252       ok = false;
253    } else {
254       dr->DeviceId = sql_insert_id(mdb, _("Device"));
255       ok = true;
256    }
257    db_unlock(mdb);
258    return ok;
259 }
260
261
262
263 /*
264  * Create a Unique record for Storage -- no duplicates
265  * Returns: false on failure
266  *          true  on success with id in sr->StorageId
267  */
268 bool db_create_storage_record(JCR *jcr, B_DB *mdb, STORAGE_DBR *sr)
269 {
270    SQL_ROW row;
271    bool ok;
272
273    db_lock(mdb);
274    Mmsg(mdb->cmd, "SELECT StorageId,AutoChanger FROM Storage WHERE Name='%s'", sr->Name);
275
276    sr->StorageId = 0;
277    sr->created = false;
278    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
279       mdb->num_rows = sql_num_rows(mdb);
280       /* If more than one, report error, but return first row */
281       if (mdb->num_rows > 1) {
282          Mmsg1(&mdb->errmsg, _("More than one Storage record!: %d\n"), (int)(mdb->num_rows));
283          Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
284       }
285       if (mdb->num_rows >= 1) {
286          if ((row = sql_fetch_row(mdb)) == NULL) {
287             Mmsg1(&mdb->errmsg, _("error fetching Storage row: %s\n"), sql_strerror(mdb));
288             Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
289             sql_free_result(mdb);
290             db_unlock(mdb);
291             return false;
292          }
293          sr->StorageId = str_to_int64(row[0]);
294          sr->AutoChanger = atoi(row[1]);   /* bool */
295          sql_free_result(mdb);
296          db_unlock(mdb);
297          return true;
298       }
299       sql_free_result(mdb);
300    }
301
302    /* Must create it */
303    Mmsg(mdb->cmd, "INSERT INTO Storage (Name,AutoChanger)"
304         " VALUES ('%s',%d)", sr->Name, sr->AutoChanger);
305
306    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
307       Mmsg2(&mdb->errmsg, _("Create DB Storage record %s failed. ERR=%s\n"),
308             mdb->cmd, sql_strerror(mdb));
309       Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
310       ok = false;
311    } else {
312       sr->StorageId = sql_insert_id(mdb, _("Storage"));
313       sr->created = true;
314       ok = true;
315    }
316    db_unlock(mdb);
317    return ok;
318 }
319
320
321 /*
322  * Create Unique MediaType record
323  * Returns: false on failure
324  *          true  on success
325  */
326 bool
327 db_create_mediatype_record(JCR *jcr, B_DB *mdb, MEDIATYPE_DBR *mr)
328 {
329    bool stat;        
330
331    Dmsg0(200, "In create mediatype\n");
332    db_lock(mdb);
333    Mmsg(mdb->cmd, "SELECT MediaTypeId,MediaType FROM MediaType WHERE MediaType='%s'", mr->MediaType);
334    Dmsg1(200, "selectmediatype: %s\n", mdb->cmd);
335
336    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
337       mdb->num_rows = sql_num_rows(mdb);
338       if (mdb->num_rows > 0) {
339          Mmsg1(&mdb->errmsg, _("mediatype record %s already exists\n"), mr->MediaType);
340          sql_free_result(mdb);
341          db_unlock(mdb);
342          return false;
343       }
344       sql_free_result(mdb);
345    }
346
347    /* Must create it */
348    Mmsg(mdb->cmd,
349 "INSERT INTO MediaType (MediaType,ReadOnly) "
350 "VALUES ('%s',%d)",
351                   mr->MediaType,
352                   mr->ReadOnly);
353    Dmsg1(200, "Create mediatype: %s\n", mdb->cmd);
354    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
355       Mmsg2(&mdb->errmsg, _("Create db mediatype record %s failed: ERR=%s\n"),
356             mdb->cmd, sql_strerror(mdb));
357       mr->MediaTypeId = 0;
358       stat = false;
359    } else {
360       mr->MediaTypeId = sql_insert_id(mdb, _("MediaType"));
361       stat = true;
362    }
363    db_unlock(mdb);
364    return stat;
365 }
366
367
368 /*
369  * Create Media record. VolumeName and non-zero Slot must be unique
370  *
371  * Returns: 0 on failure
372  *          1 on success
373  */
374 int
375 db_create_media_record(JCR *jcr, B_DB *mdb, MEDIA_DBR *mr)
376 {
377    int stat;
378    char ed1[50], ed2[50], ed3[50], ed4[50], ed5[50], ed6[50], ed7[50], ed8[50];
379    struct tm tm;
380
381    db_lock(mdb);
382    Mmsg(mdb->cmd, "SELECT MediaId FROM Media WHERE VolumeName='%s'",
383            mr->VolumeName);
384    Dmsg1(300, "selectpool: %s\n", mdb->cmd);
385
386    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
387       mdb->num_rows = sql_num_rows(mdb);
388       if (mdb->num_rows > 0) {
389          Mmsg1(&mdb->errmsg, _("Volume \"%s\" already exists.\n"), mr->VolumeName);
390          sql_free_result(mdb);
391          db_unlock(mdb);
392          return 0;
393       }
394       sql_free_result(mdb);
395    }
396
397    /* Must create it */
398    Mmsg(mdb->cmd,
399 "INSERT INTO Media (VolumeName,MediaType,PoolId,MaxVolBytes,VolCapacityBytes,"
400 "Recycle,VolRetention,VolUseDuration,MaxVolJobs,MaxVolFiles,"
401 "VolStatus,Slot,VolBytes,InChanger,VolReadTime,VolWriteTime,VolParts,"
402 "EndFile,EndBlock,LabelType,StorageId) "
403 "VALUES ('%s','%s',%u,%s,%s,%d,%s,%s,%u,%u,'%s',%d,%s,%d,%s,%s,%d,0,0,%d,%s)",
404                   mr->VolumeName,
405                   mr->MediaType, mr->PoolId,
406                   edit_uint64(mr->MaxVolBytes,ed1),
407                   edit_uint64(mr->VolCapacityBytes, ed2),
408                   mr->Recycle,
409                   edit_uint64(mr->VolRetention, ed3),
410                   edit_uint64(mr->VolUseDuration, ed4),
411                   mr->MaxVolJobs,
412                   mr->MaxVolFiles,
413                   mr->VolStatus,
414                   mr->Slot,
415                   edit_uint64(mr->VolBytes, ed5),
416                   mr->InChanger,
417                   edit_uint64(mr->VolReadTime, ed6),
418                   edit_uint64(mr->VolWriteTime, ed7),
419                   mr->VolParts,
420                   mr->LabelType,
421                   edit_int64(mr->StorageId, ed8) 
422                   );
423
424
425    Dmsg1(500, "Create Volume: %s\n", mdb->cmd);
426    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
427       Mmsg2(&mdb->errmsg, _("Create DB Media record %s failed. ERR=%s\n"),
428             mdb->cmd, sql_strerror(mdb));
429       stat = 0;
430    } else {
431       mr->MediaId = sql_insert_id(mdb, _("Media"));
432       stat = 1;
433       if (mr->set_label_date) {
434          char dt[MAX_TIME_LENGTH];
435          if (mr->LabelDate == 0) {
436             mr->LabelDate = time(NULL);
437          }
438          localtime_r(&mr->LabelDate, &tm);
439          strftime(dt, sizeof(dt), "%Y-%m-%d %T", &tm);
440          Mmsg(mdb->cmd, "UPDATE Media SET LabelDate='%s' "
441               "WHERE MediaId=%d", dt, mr->MediaId);
442          stat = UPDATE_DB(jcr, mdb, mdb->cmd);
443       }
444    }
445
446    /*
447     * Make sure that if InChanger is non-zero any other identical slot
448     *   has InChanger zero.
449     */
450    db_make_inchanger_unique(jcr, mdb, mr);
451
452    db_unlock(mdb);
453    return stat;
454 }
455
456 /*
457  * Create a Unique record for the client -- no duplicates
458  * Returns: 0 on failure
459  *          1 on success with id in cr->ClientId
460  */
461 int db_create_client_record(JCR *jcr, B_DB *mdb, CLIENT_DBR *cr)
462 {
463    SQL_ROW row;
464    int stat;
465    char ed1[50], ed2[50];
466
467    db_lock(mdb);
468    Mmsg(mdb->cmd, "SELECT ClientId,Uname FROM Client WHERE Name='%s'", cr->Name);
469
470    cr->ClientId = 0;
471    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
472       mdb->num_rows = sql_num_rows(mdb);
473       /* If more than one, report error, but return first row */
474       if (mdb->num_rows > 1) {
475          Mmsg1(&mdb->errmsg, _("More than one Client!: %d\n"), (int)(mdb->num_rows));
476          Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
477       }
478       if (mdb->num_rows >= 1) {
479          if ((row = sql_fetch_row(mdb)) == NULL) {
480             Mmsg1(&mdb->errmsg, _("error fetching Client row: %s\n"), sql_strerror(mdb));
481             Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
482             sql_free_result(mdb);
483             db_unlock(mdb);
484             return 0;
485          }
486          cr->ClientId = str_to_int64(row[0]);
487          if (row[1]) {
488             bstrncpy(cr->Uname, row[1], sizeof(cr->Uname));
489          } else {
490             cr->Uname[0] = 0;         /* no name */
491          }
492          sql_free_result(mdb);
493          db_unlock(mdb);
494          return 1;
495       }
496       sql_free_result(mdb);
497    }
498
499    /* Must create it */
500    Mmsg(mdb->cmd, "INSERT INTO Client (Name,Uname,AutoPrune,"
501 "FileRetention,JobRetention) VALUES "
502 "('%s','%s',%d,%s,%s)", cr->Name, cr->Uname, cr->AutoPrune,
503       edit_uint64(cr->FileRetention, ed1),
504       edit_uint64(cr->JobRetention, ed2));
505
506    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
507       Mmsg2(&mdb->errmsg, _("Create DB Client record %s failed. ERR=%s\n"),
508             mdb->cmd, sql_strerror(mdb));
509       Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
510       cr->ClientId = 0;
511       stat = 0;
512    } else {
513       cr->ClientId = sql_insert_id(mdb, _("Client"));
514       stat = 1;
515    }
516    db_unlock(mdb);
517    return stat;
518 }
519
520
521
522
523
524 /*
525  * Create a Unique record for the counter -- no duplicates
526  * Returns: 0 on failure
527  *          1 on success with counter filled in
528  */
529 int db_create_counter_record(JCR *jcr, B_DB *mdb, COUNTER_DBR *cr)
530 {
531    COUNTER_DBR mcr;
532    int stat;
533
534    db_lock(mdb);
535    memset(&mcr, 0, sizeof(mcr));
536    bstrncpy(mcr.Counter, cr->Counter, sizeof(mcr.Counter));
537    if (db_get_counter_record(jcr, mdb, &mcr)) {
538       memcpy(cr, &mcr, sizeof(COUNTER_DBR));
539       db_unlock(mdb);
540       return 1;
541    }
542
543    /* Must create it */
544    Mmsg(mdb->cmd, "INSERT INTO Counters (Counter,MinValue,MaxValue,CurrentValue,"
545       "WrapCounter) VALUES ('%s','%d','%d','%d','%s')",
546       cr->Counter, cr->MinValue, cr->MaxValue, cr->CurrentValue,
547       cr->WrapCounter);
548
549    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
550       Mmsg2(&mdb->errmsg, _("Create DB Counters record %s failed. ERR=%s\n"),
551             mdb->cmd, sql_strerror(mdb));
552       Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
553       stat = 0;
554    } else {
555       stat = 1;
556    }
557    db_unlock(mdb);
558    return stat;
559 }
560
561
562 /*
563  * Create a FileSet record. This record is unique in the
564  *  name and the MD5 signature of the include/exclude sets.
565  *  Returns: 0 on failure
566  *           1 on success with FileSetId in record
567  */
568 bool db_create_fileset_record(JCR *jcr, B_DB *mdb, FILESET_DBR *fsr)
569 {
570    SQL_ROW row;
571    bool stat;
572    struct tm tm;
573
574    db_lock(mdb);
575    fsr->created = false;
576    Mmsg(mdb->cmd, "SELECT FileSetId,CreateTime FROM FileSet WHERE "
577 "FileSet='%s' AND MD5='%s'", fsr->FileSet, fsr->MD5);
578
579    fsr->FileSetId = 0;
580    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
581       mdb->num_rows = sql_num_rows(mdb);
582       if (mdb->num_rows > 1) {
583          Mmsg1(&mdb->errmsg, _("More than one FileSet!: %d\n"), (int)(mdb->num_rows));
584          Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
585       }
586       if (mdb->num_rows >= 1) {
587          if ((row = sql_fetch_row(mdb)) == NULL) {
588             Mmsg1(&mdb->errmsg, _("error fetching FileSet row: ERR=%s\n"), sql_strerror(mdb));
589             Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
590             sql_free_result(mdb);
591             db_unlock(mdb);
592             return false;
593          }
594          fsr->FileSetId = str_to_int64(row[0]);
595          if (row[1] == NULL) {
596             fsr->cCreateTime[0] = 0;
597          } else {
598             bstrncpy(fsr->cCreateTime, row[1], sizeof(fsr->cCreateTime));
599          }
600          sql_free_result(mdb);
601          db_unlock(mdb);
602          return true;
603       }
604       sql_free_result(mdb);
605    }
606
607    if (fsr->CreateTime == 0 && fsr->cCreateTime[0] == 0) {
608       fsr->CreateTime = time(NULL);
609    }
610    localtime_r(&fsr->CreateTime, &tm);
611    strftime(fsr->cCreateTime, sizeof(fsr->cCreateTime), "%Y-%m-%d %T", &tm);
612
613    /* Must create it */
614       Mmsg(mdb->cmd, "INSERT INTO FileSet (FileSet,MD5,CreateTime) "
615 "VALUES ('%s','%s','%s')", fsr->FileSet, fsr->MD5, fsr->cCreateTime);
616
617    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
618       Mmsg2(&mdb->errmsg, _("Create DB FileSet record %s failed. ERR=%s\n"),
619             mdb->cmd, sql_strerror(mdb));
620       Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
621       fsr->FileSetId = 0;
622       stat = false;
623    } else {
624       fsr->FileSetId = sql_insert_id(mdb, _("FileSet"));
625       fsr->created = true;
626       stat = true;
627    }
628
629    db_unlock(mdb);
630    return stat;
631 }
632
633
634 /*
635  *  struct stat
636  *  {
637  *      dev_t         st_dev;       * device *
638  *      ino_t         st_ino;       * inode *
639  *      mode_t        st_mode;      * protection *
640  *      nlink_t       st_nlink;     * number of hard links *
641  *      uid_t         st_uid;       * user ID of owner *
642  *      gid_t         st_gid;       * group ID of owner *
643  *      dev_t         st_rdev;      * device type (if inode device) *
644  *      off_t         st_size;      * total size, in bytes *
645  *      unsigned long st_blksize;   * blocksize for filesystem I/O *
646  *      unsigned long st_blocks;    * number of blocks allocated *
647  *      time_t        st_atime;     * time of last access *
648  *      time_t        st_mtime;     * time of last modification *
649  *      time_t        st_ctime;     * time of last inode change *
650  *  };
651  */
652
653
654
655 /*
656  * Create File record in B_DB
657  *
658  *  In order to reduce database size, we store the File attributes,
659  *  the FileName, and the Path separately.  In principle, there
660  *  is a single FileName record and a single Path record, no matter
661  *  how many times it occurs.  This is this subroutine, we separate
662  *  the file and the path and create three database records.
663  */
664 int db_create_file_attributes_record(JCR *jcr, B_DB *mdb, ATTR_DBR *ar)
665 {
666
667    db_lock(mdb);
668    Dmsg1(300, "Fname=%s\n", ar->fname);
669    Dmsg0(500, "put_file_into_catalog\n");
670    /*
671     * Make sure we have an acceptable attributes record.
672     */
673    if (!(ar->Stream == STREAM_UNIX_ATTRIBUTES ||
674          ar->Stream == STREAM_UNIX_ATTRIBUTES_EX)) {
675       Mmsg0(&mdb->errmsg, _("Attempt to put non-attributes into catalog\n"));
676       Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
677       goto bail_out;
678    }
679
680
681    split_path_and_file(jcr, mdb, ar->fname);
682
683    if (!db_create_filename_record(jcr, mdb, ar)) {
684       goto bail_out;
685    }
686    Dmsg1(500, "db_create_filename_record: %s\n", mdb->esc_name);
687
688
689    if (!db_create_path_record(jcr, mdb, ar)) {
690       goto bail_out;
691    }
692    Dmsg1(500, "db_create_path_record: %s\n", mdb->esc_name);
693
694    /* Now create master File record */
695    if (!db_create_file_record(jcr, mdb, ar)) {
696       goto bail_out;
697    }
698    Dmsg0(500, "db_create_file_record OK\n");
699
700    Dmsg3(300, "CreateAttributes Path=%s File=%s FilenameId=%d\n", mdb->path, mdb->fname, ar->FilenameId);
701    db_unlock(mdb);
702    return 1;
703
704 bail_out:
705    db_unlock(mdb);
706    return 0;
707 }
708
709 /*
710  * This is the master File entry containing the attributes.
711  *  The filename and path records have already been created.
712  */
713 static int db_create_file_record(JCR *jcr, B_DB *mdb, ATTR_DBR *ar)
714 {
715    int stat;
716    static char *no_sig = "0";
717    char *sig;
718
719    ASSERT(ar->JobId);
720    ASSERT(ar->PathId);
721    ASSERT(ar->FilenameId);
722
723    if (ar->Sig == NULL) {
724       sig = no_sig;
725    } else {
726       sig = ar->Sig;
727    }
728
729    /* Must create it */
730    Mmsg(mdb->cmd,
731         "INSERT INTO File (FileIndex,JobId,PathId,FilenameId,"
732         "LStat,MD5) VALUES (%u,%u,%u,%u,'%s','%s')",
733         ar->FileIndex, ar->JobId, ar->PathId, ar->FilenameId,
734         ar->attr, sig);
735
736    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
737       Mmsg2(&mdb->errmsg, _("Create db File record %s failed. ERR=%s"),
738          mdb->cmd, sql_strerror(mdb));
739       Jmsg(jcr, M_FATAL, 0, "%s", mdb->errmsg);
740       ar->FileId = 0;
741       stat = 0;
742    } else {
743       ar->FileId = sql_insert_id(mdb, _("File"));
744       stat = 1;
745    }
746    return stat;
747 }
748
749 /* Create a Unique record for the Path -- no duplicates */
750 static int db_create_path_record(JCR *jcr, B_DB *mdb, ATTR_DBR *ar)
751 {
752    SQL_ROW row;
753    int stat;
754
755    mdb->esc_name = check_pool_memory_size(mdb->esc_name, 2*mdb->pnl+2);
756    db_escape_string(mdb->esc_name, mdb->path, mdb->pnl);
757
758    if (mdb->cached_path_id != 0 && mdb->cached_path_len == mdb->pnl &&
759        strcmp(mdb->cached_path, mdb->path) == 0) {
760       ar->PathId = mdb->cached_path_id;
761       return 1;
762    }
763
764    Mmsg(mdb->cmd, "SELECT PathId FROM Path WHERE Path='%s'", mdb->esc_name);
765
766    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
767       mdb->num_rows = sql_num_rows(mdb);
768       if (mdb->num_rows > 1) {
769          char ed1[30];
770          Mmsg2(&mdb->errmsg, _("More than one Path!: %s for path: %s\n"),
771             edit_uint64(mdb->num_rows, ed1), mdb->path);
772          Jmsg(jcr, M_WARNING, 0, "%s", mdb->errmsg);
773       }
774       /* Even if there are multiple paths, take the first one */
775       if (mdb->num_rows >= 1) {
776          if ((row = sql_fetch_row(mdb)) == NULL) {
777             Mmsg1(&mdb->errmsg, _("error fetching row: %s\n"), sql_strerror(mdb));
778             Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
779             sql_free_result(mdb);
780             ar->PathId = 0;
781             ASSERT(ar->PathId);
782             return 0;
783          }
784          ar->PathId = str_to_int64(row[0]);
785          sql_free_result(mdb);
786          /* Cache path */
787          if (ar->PathId != mdb->cached_path_id) {
788             mdb->cached_path_id = ar->PathId;
789             mdb->cached_path_len = mdb->pnl;
790             pm_strcpy(mdb->cached_path, mdb->path);
791          }
792          ASSERT(ar->PathId);
793          return 1;
794       }
795       sql_free_result(mdb);
796    }
797
798    Mmsg(mdb->cmd, "INSERT INTO Path (Path) VALUES ('%s')", mdb->esc_name);
799
800    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
801       Mmsg2(&mdb->errmsg, _("Create db Path record %s failed. ERR=%s\n"),
802          mdb->cmd, sql_strerror(mdb));
803       Jmsg(jcr, M_FATAL, 0, "%s", mdb->errmsg);
804       ar->PathId = 0;
805       stat = 0;
806    } else {
807       ar->PathId = sql_insert_id(mdb, _("Path"));
808       stat = 1;
809    }
810
811    /* Cache path */
812    if (stat && ar->PathId != mdb->cached_path_id) {
813       mdb->cached_path_id = ar->PathId;
814       mdb->cached_path_len = mdb->pnl;
815       pm_strcpy(mdb->cached_path, mdb->path);
816    }
817    return stat;
818 }
819
820 /* Create a Unique record for the filename -- no duplicates */
821 static int db_create_filename_record(JCR *jcr, B_DB *mdb, ATTR_DBR *ar)
822 {
823    SQL_ROW row;
824
825    mdb->esc_name = check_pool_memory_size(mdb->esc_name, 2*mdb->fnl+2);
826    db_escape_string(mdb->esc_name, mdb->fname, mdb->fnl);
827
828    Mmsg(mdb->cmd, "SELECT FilenameId FROM Filename WHERE Name='%s'", mdb->esc_name);
829
830    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
831       mdb->num_rows = sql_num_rows(mdb);
832       if (mdb->num_rows > 1) {
833          char ed1[30];
834          Mmsg2(&mdb->errmsg, _("More than one Filename! %s for file: %s\n"),
835             edit_uint64(mdb->num_rows, ed1), mdb->fname);
836          Jmsg(jcr, M_WARNING, 0, "%s", mdb->errmsg);
837       }
838       if (mdb->num_rows >= 1) {
839          if ((row = sql_fetch_row(mdb)) == NULL) {
840             Mmsg2(&mdb->errmsg, _("Error fetching row for file=%s: ERR=%s\n"),
841                 mdb->fname, sql_strerror(mdb));
842             Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
843             ar->FilenameId = 0;
844          } else {
845             ar->FilenameId = str_to_int64(row[0]);
846          }
847          sql_free_result(mdb);
848          return ar->FilenameId > 0;
849       }
850       sql_free_result(mdb);
851    }
852
853    Mmsg(mdb->cmd, "INSERT INTO Filename (Name) VALUES ('%s')", mdb->esc_name);
854
855    if (!INSERT_DB(jcr, mdb, mdb->cmd)) {
856       Mmsg2(&mdb->errmsg, _("Create db Filename record %s failed. ERR=%s\n"),
857             mdb->cmd, sql_strerror(mdb));
858       Jmsg(jcr, M_FATAL, 0, "%s", mdb->errmsg);
859       ar->FilenameId = 0;
860    } else {
861       ar->FilenameId = sql_insert_id(mdb, _("Filename"));
862    }
863    return ar->FilenameId > 0;
864 }
865
866 #endif /* HAVE_SQLITE3 || HAVE_MYSQL || HAVE_SQLITE || HAVE_POSTGRESQL */