]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/sql.c
Final changes
[bacula/bacula] / bacula / src / cats / sql.c
1 /*
2  * Bacula Catalog Database interface routines
3  *
4  *     Almost generic set of SQL database interface routines
5  *      (with a little more work)
6  *
7  *    Kern Sibbald, March 2000
8  *
9  *    Version $Id$
10  */
11
12 /*
13    Copyright (C) 2000-2005 Kern Sibbald
14
15    This program is free software; you can redistribute it and/or
16    modify it under the terms of the GNU General Public License as
17    published by the Free Software Foundation; either version 2 of
18    the License, or (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23    General Public License for more details.
24
25    You should have received a copy of the GNU General Public
26    License along with this program; if not, write to the Free
27    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28    MA 02111-1307, USA.
29
30  */
31
32 /* The following is necessary so that we do not include
33  * the dummy external definition of B_DB.
34  */
35 #define __SQL_C                       /* indicate that this is sql.c */
36
37 #include "bacula.h"
38 #include "cats.h"
39
40 #if    HAVE_SQLITE3 || HAVE_MYSQL || HAVE_SQLITE || HAVE_POSTGRESQL
41
42 uint32_t bacula_db_version = 0;
43
44 /* Forward referenced subroutines */
45 void print_dashes(B_DB *mdb);
46 void print_result(B_DB *mdb);
47
48 /*
49  * Called here to retrieve an integer from the database
50  */
51 static int int_handler(void *ctx, int num_fields, char **row)
52 {
53    uint32_t *val = (uint32_t *)ctx;
54
55    Dmsg1(800, "int_handler starts with row pointing at %x\n", row);
56
57    if (row[0]) {
58       Dmsg1(800, "int_handler finds '%s'\n", row[0]);
59       *val = str_to_int64(row[0]);
60    } else {
61       Dmsg0(800, "int_handler finds zero\n");
62       *val = 0;
63    }
64    Dmsg0(800, "int_handler finishes\n");
65    return 0;
66 }
67
68
69
70 /* NOTE!!! The following routines expect that the
71  *  calling subroutine sets and clears the mutex
72  */
73
74 /* Check that the tables correspond to the version we want */
75 int check_tables_version(JCR *jcr, B_DB *mdb)
76 {
77    const char *query = "SELECT VersionId FROM Version";
78
79    bacula_db_version = 0;
80    db_sql_query(mdb, query, int_handler, (void *)&bacula_db_version);
81    if (bacula_db_version != BDB_VERSION) {
82       Mmsg(mdb->errmsg, "Version error for database \"%s\". Wanted %d, got %d\n",
83           mdb->db_name, BDB_VERSION, bacula_db_version);
84       Jmsg(jcr, M_FATAL, 0, "%s", mdb->errmsg);
85       return 0;
86    }
87    return 1;
88 }
89
90 /* Utility routine for queries. The database MUST be locked before calling here. */
91 int
92 QueryDB(const char *file, int line, JCR *jcr, B_DB *mdb, char *cmd)
93 {
94    int status;
95    if ((status=sql_query(mdb, cmd)) != 0) {
96       m_msg(file, line, &mdb->errmsg, _("query %s failed:\n%s\n"), cmd, sql_strerror(mdb));
97       j_msg(file, line, jcr, M_FATAL, 0, "%s", mdb->errmsg);
98       if (verbose) {
99          j_msg(file, line, jcr, M_INFO, 0, "%s\n", cmd);
100       }
101       return 0;
102    }
103
104    mdb->result = sql_store_result(mdb);
105
106    return mdb->result != NULL;
107 }
108
109 /*
110  * Utility routine to do inserts
111  * Returns: 0 on failure
112  *          1 on success
113  */
114 int
115 InsertDB(const char *file, int line, JCR *jcr, B_DB *mdb, char *cmd)
116 {
117    if (sql_query(mdb, cmd)) {
118       m_msg(file, line, &mdb->errmsg,  _("insert %s failed:\n%s\n"), cmd, sql_strerror(mdb));
119       j_msg(file, line, jcr, M_FATAL, 0, "%s", mdb->errmsg);
120       if (verbose) {
121          j_msg(file, line, jcr, M_INFO, 0, "%s\n", cmd);
122       }
123       return 0;
124    }
125    if (mdb->have_insert_id) {
126       mdb->num_rows = sql_affected_rows(mdb);
127    } else {
128       mdb->num_rows = 1;
129    }
130    if (mdb->num_rows != 1) {
131       char ed1[30];
132       m_msg(file, line, &mdb->errmsg, _("Insertion problem: affected_rows=%s\n"),
133          edit_uint64(mdb->num_rows, ed1));
134       if (verbose) {
135          j_msg(file, line, jcr, M_INFO, 0, "%s\n", cmd);
136       }
137       return 0;
138    }
139    mdb->changes++;
140    return 1;
141 }
142
143 /* Utility routine for updates.
144  *  Returns: 0 on failure
145  *           1 on success
146  */
147 int
148 UpdateDB(const char *file, int line, JCR *jcr, B_DB *mdb, char *cmd)
149 {
150
151    if (sql_query(mdb, cmd)) {
152       m_msg(file, line, &mdb->errmsg, _("update %s failed:\n%s\n"), cmd, sql_strerror(mdb));
153       j_msg(file, line, jcr, M_ERROR, 0, "%s", mdb->errmsg);
154       if (verbose) {
155          j_msg(file, line, jcr, M_INFO, 0, "%s\n", cmd);
156       }
157       return 0;
158    }
159    mdb->num_rows = sql_affected_rows(mdb);
160    if (mdb->num_rows < 1) {
161       char ed1[30];
162       m_msg(file, line, &mdb->errmsg, _("Update problem: affected_rows=%s\n"),
163          edit_uint64(mdb->num_rows, ed1));
164       if (verbose) {
165 //       j_msg(file, line, jcr, M_INFO, 0, "%s\n", cmd);
166       }
167       return 0;
168    }
169    mdb->changes++;
170    return 1;
171 }
172
173 /* Utility routine for deletes
174  *
175  * Returns: -1 on error
176  *           n number of rows affected
177  */
178 int
179 DeleteDB(const char *file, int line, JCR *jcr, B_DB *mdb, char *cmd)
180 {
181
182    if (sql_query(mdb, cmd)) {
183       m_msg(file, line, &mdb->errmsg, _("delete %s failed:\n%s\n"), cmd, sql_strerror(mdb));
184       j_msg(file, line, jcr, M_ERROR, 0, "%s", mdb->errmsg);
185       if (verbose) {
186          j_msg(file, line, jcr, M_INFO, 0, "%s\n", cmd);
187       }
188       return -1;
189    }
190    mdb->changes++;
191    return sql_affected_rows(mdb);
192 }
193
194
195 /*
196  * Get record max. Query is already in mdb->cmd
197  *  No locking done
198  *
199  * Returns: -1 on failure
200  *          count on success
201  */
202 int get_sql_record_max(JCR *jcr, B_DB *mdb)
203 {
204    SQL_ROW row;
205    int stat = 0;
206
207    if (QUERY_DB(jcr, mdb, mdb->cmd)) {
208       if ((row = sql_fetch_row(mdb)) == NULL) {
209          Mmsg1(&mdb->errmsg, _("error fetching row: %s\n"), sql_strerror(mdb));
210          stat = -1;
211       } else {
212          stat = str_to_int64(row[0]);
213       }
214       sql_free_result(mdb);
215    } else {
216       Mmsg1(&mdb->errmsg, _("error fetching row: %s\n"), sql_strerror(mdb));
217       stat = -1;
218    }
219    return stat;
220 }
221
222 /*
223  * Return pre-edited error message
224  */
225 char *db_strerror(B_DB *mdb)
226 {
227    return mdb->errmsg;
228 }
229
230 /*
231  * Lock database, this can be called multiple times by the same
232  *   thread without blocking, but must be unlocked the number of
233  *   times it was locked.
234  */
235 void _db_lock(const char *file, int line, B_DB *mdb)
236 {
237    int errstat;
238    if ((errstat=rwl_writelock(&mdb->lock)) != 0) {
239       berrno be;
240       e_msg(file, line, M_ABORT, 0, "rwl_writelock failure. ERR=%s\n",
241            be.strerror(errstat));
242    }
243 }
244
245 /*
246  * Unlock the database. This can be called multiple times by the
247  *   same thread up to the number of times that thread called
248  *   db_lock()/
249  */
250 void _db_unlock(const char *file, int line, B_DB *mdb)
251 {
252    int errstat;
253    if ((errstat=rwl_writeunlock(&mdb->lock)) != 0) {
254       berrno be;
255       e_msg(file, line, M_ABORT, 0, "rwl_writeunlock failure. ERR=%s\n",
256            be.strerror(errstat));
257    }
258 }
259
260 /*
261  * Start a transaction. This groups inserts and makes things
262  *  much more efficient. Usually started when inserting
263  *  file attributes.
264  */
265 void db_start_transaction(JCR *jcr, B_DB *mdb)
266 {
267    if (!jcr->attr) {
268       jcr->attr = get_pool_memory(PM_FNAME);
269    }
270 #ifdef HAVE_SQLITE
271    if (!mdb->allow_transactions) {
272       return;
273    }
274    db_lock(mdb);
275    /* Allow only 10,000 changes per transaction */
276    if (mdb->transaction && mdb->changes > 10000) {
277       db_end_transaction(jcr, mdb);
278    }
279    if (!mdb->transaction) {
280       my_sqlite_query(mdb, "BEGIN");  /* begin transaction */
281       Dmsg0(400, "Start SQLite transaction\n");
282       mdb->transaction = 1;
283    }
284    db_unlock(mdb);
285 #endif
286
287 /*
288  * This is turned off because transactions break
289  * if multiple simultaneous jobs are run.
290  */
291 #ifdef HAVE_POSTGRESQL
292    if (!mdb->allow_transactions) {
293       return;
294    }
295    db_lock(mdb);
296    /* Allow only 25,000 changes per transaction */
297    if (mdb->transaction && mdb->changes > 25000) {
298       db_end_transaction(jcr, mdb);
299    }
300    if (!mdb->transaction) {
301       db_sql_query(mdb, "BEGIN", NULL, NULL);  /* begin transaction */
302       Dmsg0(400, "Start PosgreSQL transaction\n");
303       mdb->transaction = 1;
304    }
305    db_unlock(mdb);
306 #endif
307 }
308
309 void db_end_transaction(JCR *jcr, B_DB *mdb)
310 {
311    /*
312     * This can be called during thread cleanup and
313     *   the db may already be closed.  So simply return.
314     */
315    if (!mdb) {
316       return;
317    }
318 #ifdef xxx
319    if (jcr && jcr->cached_attribute) {
320       if (!db_create_file_attributes_record(jcr, jcr->db, &jcr->ar)) {
321          Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"), db_strerror(jcr->db));
322       }
323       jcr->cached_attribute = false;
324    }
325 #endif
326 #ifdef HAVE_SQLITE
327    if (!mdb->allow_transactions) {
328       return;
329    }
330    db_lock(mdb);
331    if (mdb->transaction) {
332       my_sqlite_query(mdb, "COMMIT"); /* end transaction */
333       mdb->transaction = 0;
334       Dmsg1(400, "End SQLite transaction changes=%d\n", mdb->changes);
335    }
336    mdb->changes = 0;
337    db_unlock(mdb);
338 #endif
339
340 #ifdef HAVE_POSTGRESQL
341    if (!mdb->allow_transactions) {
342       return;
343    }
344    db_lock(mdb);
345    if (mdb->transaction) {
346       db_sql_query(mdb, "COMMIT", NULL, NULL); /* end transaction */
347       mdb->transaction = 0;
348       Dmsg1(400, "End PostgreSQL transaction changes=%d\n", mdb->changes);
349    }
350    mdb->changes = 0;
351    db_unlock(mdb);
352 #endif
353 }
354
355 /*
356  * Given a full filename, split it into its path
357  *  and filename parts. They are returned in pool memory
358  *  in the mdb structure.
359  */
360 void split_path_and_file(JCR *jcr, B_DB *mdb, const char *fname)
361 {
362    const char *p, *f;
363
364    /* Find path without the filename.
365     * I.e. everything after the last / is a "filename".
366     * OK, maybe it is a directory name, but we treat it like
367     * a filename. If we don't find a / then the whole name
368     * must be a path name (e.g. c:).
369     */
370    for (p=f=fname; *p; p++) {
371       if (*p == '/') {
372          f = p;                       /* set pos of last slash */
373       }
374    }
375    if (*f == '/') {                   /* did we find a slash? */
376       f++;                            /* yes, point to filename */
377    } else {                           /* no, whole thing must be path name */
378       f = p;
379    }
380
381    /* If filename doesn't exist (i.e. root directory), we
382     * simply create a blank name consisting of a single
383     * space. This makes handling zero length filenames
384     * easier.
385     */
386    mdb->fnl = p - f;
387    if (mdb->fnl > 0) {
388       mdb->fname = check_pool_memory_size(mdb->fname, mdb->fnl+1);
389       memcpy(mdb->fname, f, mdb->fnl);    /* copy filename */
390       mdb->fname[mdb->fnl] = 0;
391    } else {
392       mdb->fname[0] = 0;
393       mdb->fnl = 0;
394    }
395
396    mdb->pnl = f - fname;
397    if (mdb->pnl > 0) {
398       mdb->path = check_pool_memory_size(mdb->path, mdb->pnl+1);
399       memcpy(mdb->path, fname, mdb->pnl);
400       mdb->path[mdb->pnl] = 0;
401    } else {
402       Mmsg1(&mdb->errmsg, _("Path length is zero. File=%s\n"), fname);
403       Jmsg(jcr, M_ERROR, 0, "%s", mdb->errmsg);
404       mdb->path[0] = 0;
405       mdb->pnl = 0;
406    }
407
408    Dmsg2(500, "split path=%s file=%s\n", mdb->path, mdb->fname);
409 }
410
411 /*
412  * List dashes as part of header for listing SQL results in a table
413  */
414 void
415 list_dashes(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
416 {
417    SQL_FIELD  *field;
418    int i, j;
419
420    sql_field_seek(mdb, 0);
421    send(ctx, "+");
422    for (i = 0; i < sql_num_fields(mdb); i++) {
423       field = sql_fetch_field(mdb);
424       for (j = 0; j < (int)field->max_length + 2; j++) {
425          send(ctx, "-");
426       }
427       send(ctx, "+");
428    }
429    send(ctx, "\n");
430 }
431
432 /*
433  * If full_list is set, we list vertically, otherwise, we
434  * list on one line horizontally.
435  */
436 void
437 list_result(JCR *jcr, B_DB *mdb, DB_LIST_HANDLER *send, void *ctx, e_list_type type)
438 {
439    SQL_FIELD *field;
440    SQL_ROW row;
441    int i, col_len, max_len = 0;
442    char buf[2000], ewc[30];
443
444    Dmsg0(800, "list_result starts\n");
445    if (mdb->result == NULL || sql_num_rows(mdb) == 0) {
446       send(ctx, _("No results to list.\n"));
447       return;
448    }
449
450    Dmsg1(800, "list_result starts looking at %d fields\n", sql_num_fields(mdb));
451    /* determine column display widths */
452    sql_field_seek(mdb, 0);
453    for (i = 0; i < sql_num_fields(mdb); i++) {
454       Dmsg1(800, "list_result processing field %d\n", i);
455       field = sql_fetch_field(mdb);
456       col_len = cstrlen(field->name);
457       if (type == VERT_LIST) {
458          if (col_len > max_len) {
459             max_len = col_len;
460          }
461       } else {
462          if (IS_NUM(field->type) && (int)field->max_length > 0) { /* fixup for commas */
463             field->max_length += (field->max_length - 1) / 3;
464          }
465          if (col_len < (int)field->max_length) {
466             col_len = field->max_length;
467          }
468          if (col_len < 4 && !IS_NOT_NULL(field->flags)) {
469             col_len = 4;                 /* 4 = length of the word "NULL" */
470          }
471          field->max_length = col_len;    /* reset column info */
472       }
473    }
474
475    Dmsg0(800, "list_result finished first loop\n");
476    if (type == VERT_LIST) {
477       goto vertical_list;
478    }
479
480    Dmsg1(800, "list_result starts second loop looking at %d fields\n", sql_num_fields(mdb));
481    list_dashes(mdb, send, ctx);
482    send(ctx, "|");
483    sql_field_seek(mdb, 0);
484    for (i = 0; i < sql_num_fields(mdb); i++) {
485       Dmsg1(800, "list_result looking at field %d\n", i);
486       field = sql_fetch_field(mdb);
487       bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, field->name);
488       send(ctx, buf);
489    }
490    send(ctx, "\n");
491    list_dashes(mdb, send, ctx);
492
493    Dmsg1(800, "list_result starts third loop looking at %d fields\n", sql_num_fields(mdb));
494    while ((row = sql_fetch_row(mdb)) != NULL) {
495       sql_field_seek(mdb, 0);
496       send(ctx, "|");
497       for (i = 0; i < sql_num_fields(mdb); i++) {
498          field = sql_fetch_field(mdb);
499          if (row[i] == NULL) {
500             bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, "NULL");
501          } else if (IS_NUM(field->type) && !jcr->gui && is_an_integer(row[i])) {
502             bsnprintf(buf, sizeof(buf), " %*s |", (int)field->max_length,
503                       add_commas(row[i], ewc));
504          } else {
505             bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, row[i]);
506          }
507          send(ctx, buf);
508       }
509       send(ctx, "\n");
510    }
511    list_dashes(mdb, send, ctx);
512    return;
513
514 vertical_list:
515
516    Dmsg1(800, "list_result starts vertical list at %d fields\n", sql_num_fields(mdb));
517    while ((row = sql_fetch_row(mdb)) != NULL) {
518       sql_field_seek(mdb, 0);
519       for (i = 0; i < sql_num_fields(mdb); i++) {
520          field = sql_fetch_field(mdb);
521          if (row[i] == NULL) {
522             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, "NULL");
523          } else if (IS_NUM(field->type) && !jcr->gui && is_an_integer(row[i])) {
524             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name,
525                 add_commas(row[i], ewc));
526          } else {
527             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, row[i]);
528          }
529          send(ctx, buf);
530       }
531       send(ctx, "\n");
532    }
533    return;
534 }
535
536
537 #endif /* HAVE_SQLITE3 || HAVE_MYSQL || HAVE_SQLITE || HAVE_POSTGRESQL*/