]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/sqlite.c
Initial revision
[bacula/bacula] / bacula / src / cats / sqlite.c
1 /*
2  * Bacula Catalog Database routines specific to SQLite
3  *
4  *    Kern Sibbald, January 2002
5  */
6
7 /*
8    Copyright (C) 2002 Kern Sibbald and John Walker
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2 of
13    the License, or (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public
21    License along with this program; if not, write to the Free
22    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23    MA 02111-1307, USA.
24
25  */
26
27
28 /* The following is necessary so that we do not include
29  * the dummy external definition of DB.
30  */
31 #define __SQL_C                       /* indicate that this is sql.c */
32
33 #include "bacula.h"
34 #include "cats.h"
35
36 #ifdef HAVE_SQLITE
37
38 /* -----------------------------------------------------------------------
39  *
40  *    SQLite dependent defines and subroutines
41  *
42  * -----------------------------------------------------------------------
43  */
44
45 extern char *working_directory;
46
47 /* List of open databases */
48 static BQUEUE db_list = {&db_list, &db_list};
49
50 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
51
52 int QueryDB(char *file, int line, B_DB *db, char *select_cmd);
53
54
55 /*
56  * Initialize database data structure. In principal this should
57  * never have errors, or it is really fatal.
58  */
59 B_DB *
60 db_init_database(char *db_name, char *db_user, char *db_password)
61 {
62    B_DB *mdb;
63
64    P(mutex);                          /* lock DB queue */
65    /* Look to see if DB already open */
66    for (mdb=NULL; (mdb=(B_DB *)qnext(&db_list, &mdb->bq)); ) {
67       if (strcmp(mdb->db_name, db_name) == 0) {
68          Dmsg2(100, "DB REopen %d %s\n", mdb->ref_count, db_name);
69          mdb->ref_count++;
70          V(mutex);
71          return mdb;                  /* already open */
72       }
73    }
74    Dmsg0(100, "db_open first time\n");
75    mdb = (B_DB *) malloc(sizeof(B_DB));
76    memset(mdb, 0, sizeof(B_DB));
77    mdb->db_name = bstrdup(db_name);
78    mdb->have_insert_id = TRUE; 
79    mdb->errmsg = (char *) get_pool_memory(PM_EMSG); /* get error message buffer */
80    *mdb->errmsg = 0;
81    mdb->cmd = (char *) get_pool_memory(PM_EMSG);    /* get command buffer */
82    mdb->ref_count = 1;
83    qinsert(&db_list, &mdb->bq);            /* put db in list */
84    V(mutex);
85    return mdb;
86 }
87
88 /*
89  * Now actually open the database.  This can generate errors,
90  * which are returned in the errmsg
91  */
92 int
93 db_open_database(B_DB *mdb)
94 {
95    char *db_name;
96    int len;
97    struct stat statbuf;
98
99    P(mutex);
100    if (mdb->connected) {
101       V(mutex);
102       return 1;
103    }
104    mdb->connected = FALSE;
105    if (pthread_mutex_init(&mdb->mutex, NULL) != 0) {
106       Mmsg1(&mdb->errmsg, _("Unable to initialize DB mutex. ERR=%s\n"), strerror(errno));
107       V(mutex);
108       return 0;
109    }
110
111    /* open the database */
112    len = strlen(working_directory) + strlen(mdb->db_name) + 5; 
113    db_name = (char *)malloc(len);
114    strcpy(db_name, working_directory);
115    strcat(db_name, "/");
116    strcat(db_name, mdb->db_name);
117    strcat(db_name, ".db");
118    if (stat(db_name, &statbuf) != 0) {
119       Mmsg1(&mdb->errmsg, _("Database %s does not exist, please create it.\n"), 
120          db_name);
121       free(db_name);
122       V(mutex);
123       return 0;
124    }
125    mdb->db = sqlite_open(
126         db_name,                      /* database name */
127         644,                          /* mode */
128         &mdb->sqlite_errmsg);         /* error message */
129
130    Dmsg0(50, "sqlite_open\n");
131   
132    if (mdb->db == NULL) {
133       Mmsg2(&mdb->errmsg, _("Unable to open Database=%s. ERR=%s\n"),
134          db_name, mdb->sqlite_errmsg ? mdb->sqlite_errmsg : _("unknown"));
135       free(db_name);
136       V(mutex);
137       return 0;
138    }
139    free(db_name);
140    mdb->connected = TRUE;
141    V(mutex);
142    return 1;
143 }
144
145 void
146 db_close_database(B_DB *mdb)
147 {
148    P(mutex);
149    mdb->ref_count--;
150    if (mdb->ref_count == 0) {
151       qdchain(&mdb->bq);
152       if (mdb->connected && mdb->db) {
153          sqlite_close(mdb->db);
154       }
155       pthread_mutex_destroy(&mdb->mutex);
156       free_pool_memory(mdb->errmsg);
157       free_pool_memory(mdb->cmd);
158       if (mdb->db_name) {
159          free(mdb->db_name);
160       }
161       free(mdb);
162    }
163    V(mutex);
164 }
165
166 /*
167  * Return the next unique index (auto-increment) for
168  * the given table.  Return NULL on error.
169  */
170 char *db_next_index(B_DB *mdb, char *table)
171 {
172    SQL_ROW row;
173    static char id[20];
174
175    QUERY_DB(mdb, "BEGIN TRANSACTION");
176    sql_free_result(mdb);
177
178    Mmsg(&mdb->cmd,
179 "SELECT id FROM NextId WHERE TableName=\"%s\"", table);
180    if (!QUERY_DB(mdb, mdb->cmd)) {
181       Mmsg(&mdb->errmsg, _("next_index query error: ERR=%s\n"), sql_strerror(mdb));
182       QUERY_DB(mdb, "ROLLBACK");
183       return NULL;
184    }
185    if ((row = sql_fetch_row(mdb)) == NULL) {
186       Mmsg(&mdb->errmsg, _("Error fetching index: ERR=%s\n"), sql_strerror(mdb));
187       QUERY_DB(mdb, "ROLLBACK");
188       return NULL;
189    }
190    strncpy(id, row[0], sizeof(id));
191    id[sizeof(id)-1] = 0;
192    sql_free_result(mdb);
193
194    Mmsg(&mdb->cmd,
195 "UPDATE NextId SET id=id+1 WHERE TableName=\"%s\"", table);
196    if (!QUERY_DB(mdb, mdb->cmd)) {
197       Mmsg(&mdb->errmsg, _("next_index update error: ERR=%s\n"), sql_strerror(mdb));
198       QUERY_DB(mdb, "ROLLBACK");
199       return NULL;
200    }
201    sql_free_result(mdb);
202
203    QUERY_DB(mdb, "COMMIT");
204    sql_free_result(mdb);
205    return id;
206 }   
207
208
209
210 void
211 db_escape_string(char *snew, char *old, int len)
212 {
213    char *n, *o;
214
215    n = snew;
216    o = old;
217    while (len--) {
218       switch (*o) {
219       case '\'':
220          *n++ = '\\';
221          *n++ = '\'';
222          o++;
223          break;
224       case '"':
225          *n++ = '\\';
226          *n++ = '"';
227          o++;
228          break;
229       case 0:
230          *n++ = '\\';
231          *n++ = 0;
232          o++;
233          break;
234       default:
235          *n++ = *o++;
236          break;
237       }
238    }
239    *n = 0;
240 }
241
242 struct rh_data {
243    DB_RESULT_HANDLER *result_handler;
244    void *ctx;
245 };
246
247 /*  
248  * Convert SQLite's callback into Bacula DB callback  
249  */
250 static int sqlite_result(void *arh_data, int num_fields, char **rows, char **col_names)
251 {
252    struct rh_data *rh_data = (struct rh_data *)arh_data;   
253
254    if (rh_data->result_handler) {
255       (*(rh_data->result_handler))(rh_data->ctx, num_fields, rows);
256    }
257    return 0;
258 }
259
260 /*
261  * Submit a general SQL command (cmd), and for each row returned,
262  *  the sqlite_handler is called with the ctx.
263  */
264 int db_sql_query(B_DB *mdb, char *query, DB_RESULT_HANDLER *result_handler, void *ctx)
265 {
266    struct rh_data rh_data;
267    int stat;
268
269    P(mdb->mutex);
270    if (mdb->sqlite_errmsg) {
271       actuallyfree(mdb->sqlite_errmsg);
272       mdb->sqlite_errmsg = NULL;
273    }
274    rh_data.result_handler = result_handler;
275    rh_data.ctx = ctx;
276    stat = sqlite_exec(mdb->db, query, sqlite_result, (void *)&rh_data, &mdb->sqlite_errmsg);
277    if (stat != 0) {
278       Mmsg(&mdb->errmsg, _("Query failed: %s: ERR=%s\n"), query, sql_strerror(mdb));
279       V(mdb->mutex);
280       return 0;
281    }
282    V(mdb->mutex);
283    return 1;
284 }
285
286 /*
287  * Submit a sqlite query and retrieve all the data
288  */
289 int my_sqlite_query(B_DB *mdb, char *cmd) 
290 {
291    int stat;
292
293    if (mdb->sqlite_errmsg) {
294       actuallyfree(mdb->sqlite_errmsg);
295       mdb->sqlite_errmsg = NULL;
296    }
297    stat = sqlite_get_table(mdb->db, cmd, &mdb->result, &mdb->nrow, &mdb->ncolumn,
298             &mdb->sqlite_errmsg);
299    mdb->row = 0;                      /* row fetched */
300    return stat;
301 }
302
303 /* Fetch one row at a time */
304 SQL_ROW my_sqlite_fetch_row(B_DB *mdb)
305 {
306    if (mdb->row >= mdb->nrow) {
307       return NULL;
308    }
309    mdb->row++;
310    return &mdb->result[mdb->ncolumn * mdb->row];
311 }
312
313 void my_sqlite_free_table(B_DB *mdb)
314 {
315    unsigned int i;
316
317    if (mdb->fields_defined) {
318       for (i=0; i < sql_num_fields(mdb); i++) {
319          free(mdb->fields[i]);
320       }
321       free(mdb->fields);
322       mdb->fields_defined = FALSE;
323    }
324    sqlite_free_table(mdb->result);
325    mdb->nrow = mdb->ncolumn = 0; 
326 }
327
328 void my_sqlite_field_seek(B_DB *mdb, int field)
329 {
330    unsigned int i, j;
331    if (mdb->result == NULL) {
332       return;
333    }
334    /* On first call, set up the fields */
335    if (!mdb->fields_defined && sql_num_fields(mdb) > 0) {
336       mdb->fields = (SQL_FIELD **)malloc(sizeof(SQL_FIELD) * mdb->ncolumn);
337       for (i=0; i < sql_num_fields(mdb); i++) {
338          mdb->fields[i] = (SQL_FIELD *)malloc(sizeof(SQL_FIELD));
339          mdb->fields[i]->name = mdb->result[i];
340          mdb->fields[i]->length = strlen(mdb->fields[i]->name);
341          mdb->fields[i]->max_length = mdb->fields[i]->length;
342          for (j=1; j <= (unsigned)mdb->nrow; j++) {
343             uint32_t len;
344             if (mdb->result[i + mdb->ncolumn *j]) {
345                len = (uint32_t)strlen(mdb->result[i + mdb->ncolumn * j]);
346             } else {
347                len = 0;
348             }
349             if (len > mdb->fields[i]->max_length) {
350                mdb->fields[i]->max_length = len;
351             }
352          }
353          mdb->fields[i]->type = 0;
354          mdb->fields[i]->flags = 1;        /* not null */
355       }
356       mdb->fields_defined = TRUE;
357    }
358    if (field > (int)sql_num_fields(mdb)) {
359       field = (int)sql_num_fields(mdb);
360     }
361     mdb->field = field;
362
363 }
364
365 SQL_FIELD *my_sqlite_fetch_field(B_DB *mdb)
366 {
367    return mdb->fields[mdb->field++];
368 }
369
370 static void
371 list_dashes(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
372 {
373    SQL_FIELD *field;
374    unsigned int i, j;
375
376    sql_field_seek(mdb, 0);
377    send(ctx, "+");
378    for (i = 0; i < sql_num_fields(mdb); i++) {
379       field = sql_fetch_field(mdb);
380       for (j = 0; j < field->max_length + 2; j++)
381               send(ctx, "-");
382       send(ctx, "+");
383    }
384    send(ctx, "\n");
385 }
386
387 void
388 list_result(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
389 {
390    SQL_FIELD *field;
391    SQL_ROW row;
392    unsigned int i, col_len;
393    char buf[2000], ewc[30];
394
395    if (mdb->result == NULL || mdb->nrow == 0) {
396       return;
397    }
398    /* determine column display widths */
399    sql_field_seek(mdb, 0);
400    for (i = 0; i < sql_num_fields(mdb); i++) {
401       field = sql_fetch_field(mdb);
402       if (IS_NUM(field->type) && field->max_length > 0) { /* fixup for commas */
403          field->max_length += (field->max_length - 1) / 3;
404       }
405       col_len = strlen(field->name);
406       if (col_len < field->max_length)
407               col_len = field->max_length;
408       if (col_len < 4 && !IS_NOT_NULL(field->flags))
409               col_len = 4;    /* 4 = length of the word "NULL" */
410       field->max_length = col_len;    /* reset column info */
411    }
412
413    list_dashes(mdb, send, ctx);
414    send(ctx, "|");
415    sql_field_seek(mdb, 0);
416    for (i = 0; i < sql_num_fields(mdb); i++) {
417       field = sql_fetch_field(mdb);
418       sprintf(buf, " %-*s |", field->max_length, field->name);
419       send(ctx, buf);
420    }
421    send(ctx, "\n");
422    list_dashes(mdb, send, ctx);
423
424    while ((row = sql_fetch_row(mdb)) != NULL) {
425       sql_field_seek(mdb, 0);
426       send(ctx, "|");
427       for (i = 0; i < sql_num_fields(mdb); i++) {
428          field = sql_fetch_field(mdb);
429          if (row[i] == NULL) {
430             sprintf(buf, " %-*s |", field->max_length, "NULL");
431          } else if (IS_NUM(field->type)) {
432             sprintf(buf, " %*s |", field->max_length,       
433                add_commas(row[i], ewc));
434          } else {
435             sprintf(buf, " %-*s |", field->max_length, row[i]);
436          }
437          send(ctx, buf);
438       }
439       send(ctx, "\n");
440    }
441    list_dashes(mdb, send, ctx);
442 }
443
444
445 #endif /* HAVE_SQLITE */