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