]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/sqlite.c
fix warning
[bacula/bacula] / bacula / src / cats / sqlite.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version three of the GNU Affero General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU Affero General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of Kern Sibbald.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  * Bacula Catalog Database routines specific to SQLite
30  *
31  *    Kern Sibbald, January 2002
32  *
33  * Major rewrite by Marco van Wieringen, January 2010 for catalog refactoring.
34  */
35
36 #include "bacula.h"
37
38 #if HAVE_SQLITE3
39
40 #include "cats.h"
41 #include "bdb_priv.h"
42 #include <sqlite3.h>
43 #include "bdb_sqlite.h"
44
45 /* -----------------------------------------------------------------------
46  *
47  *    SQLite dependent defines and subroutines
48  *
49  * -----------------------------------------------------------------------
50  */
51
52 /*
53  * List of open databases
54  */
55 static dlist *db_list = NULL;
56
57 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
58
59 /*
60  * When using mult_db_connections = true, 
61  * sqlite can be BUSY. We just need sleep a little in this case.
62  */
63 static int sqlite_busy_handler(void *arg, int calls)
64 {
65    bmicrosleep(0, 500);
66    return 1;
67 }
68
69 B_DB_SQLITE::B_DB_SQLITE(JCR *jcr,
70                          const char *db_driver,
71                          const char *db_name,
72                          const char *db_user,
73                          const char *db_password,
74                          const char *db_address,
75                          int db_port,
76                          const char *db_socket,
77                          bool mult_db_connections,
78                          bool disable_batch_insert)
79 {
80    /*
81     * Initialize the parent class members.
82     */
83    m_db_interface_type = SQL_INTERFACE_TYPE_SQLITE3;
84    m_db_type = SQL_TYPE_SQLITE3;
85    m_db_driver = bstrdup("SQLite3");
86    m_db_name = bstrdup(db_name);
87    if (disable_batch_insert) {
88       m_disabled_batch_insert = true;
89       m_have_batch_insert = false;
90    } else {
91       m_disabled_batch_insert = false;
92 #if defined(USE_BATCH_FILE_INSERT)
93 #if defined(HAVE_SQLITE3_THREADSAFE)
94       m_have_batch_insert = sqlite3_threadsafe();
95 #else
96       m_have_batch_insert = false;
97 #endif /* HAVE_SQLITE3_THREADSAFE */
98 #else
99       m_have_batch_insert = false;
100 #endif /* USE_BATCH_FILE_INSERT */
101    }
102    errmsg = get_pool_memory(PM_EMSG); /* get error message buffer */
103    *errmsg = 0;
104    cmd = get_pool_memory(PM_EMSG);    /* get command buffer */
105    cached_path = get_pool_memory(PM_FNAME);
106    cached_path_id = 0;
107    m_ref_count = 1;
108    fname = get_pool_memory(PM_FNAME);
109    path = get_pool_memory(PM_FNAME);
110    esc_name = get_pool_memory(PM_FNAME);
111    esc_path = get_pool_memory(PM_FNAME);
112    esc_obj  = get_pool_memory(PM_FNAME);
113    m_allow_transactions = mult_db_connections;
114
115    /*
116     * Initialize the private members.
117     */
118    m_db_handle = NULL;
119    m_result = NULL;
120    m_sqlite_errmsg = NULL;
121
122    /*
123     * Put the db in the list.
124     */
125    if (db_list == NULL) {
126       db_list = New(dlist(this, &this->m_link));
127    }
128    db_list->append(this);
129 }
130
131 B_DB_SQLITE::~B_DB_SQLITE()
132 {
133 }
134
135 /*
136  * Now actually open the database.  This can generate errors,
137  * which are returned in the errmsg
138  *
139  * DO NOT close the database or delete mdb here !!!!
140  */
141 bool B_DB_SQLITE::db_open_database(JCR *jcr)
142 {
143    bool retval = false;
144    char *db_path;
145    int len;
146    struct stat statbuf;
147    int ret;
148    int errstat;
149    int retry = 0;
150
151    P(mutex);
152    if (m_connected) {
153       retval = true;
154       goto bail_out;
155    }
156
157    if ((errstat=rwl_init(&m_lock)) != 0) {
158       berrno be;
159       Mmsg1(&errmsg, _("Unable to initialize DB lock. ERR=%s\n"),
160             be.bstrerror(errstat));
161       goto bail_out;
162    }
163
164    /*
165     * Open the database
166     */
167    len = strlen(working_directory) + strlen(m_db_name) + 5;
168    db_path = (char *)malloc(len);
169    strcpy(db_path, working_directory);
170    strcat(db_path, "/");
171    strcat(db_path, m_db_name);
172    strcat(db_path, ".db");
173    if (stat(db_path, &statbuf) != 0) {
174       Mmsg1(&errmsg, _("Database %s does not exist, please create it.\n"),
175          db_path);
176       free(db_path);
177       goto bail_out;
178    }
179
180    for (m_db_handle = NULL; !m_db_handle && retry++ < 10; ) {
181       ret = sqlite3_open(db_path, &m_db_handle);
182       if (ret != SQLITE_OK) {
183          m_sqlite_errmsg = (char *)sqlite3_errmsg(m_db_handle); 
184          sqlite3_close(m_db_handle);
185          m_db_handle = NULL;
186       } else {
187          m_sqlite_errmsg = NULL;
188       }
189
190       Dmsg0(300, "sqlite_open\n");
191       if (!m_db_handle) {
192          bmicrosleep(1, 0);
193       }
194    }
195    if (m_db_handle == NULL) {
196       Mmsg2(&errmsg, _("Unable to open Database=%s. ERR=%s\n"),
197          db_path, m_sqlite_errmsg ? m_sqlite_errmsg : _("unknown"));
198       free(db_path);
199       goto bail_out;
200    }       
201    m_connected = true;
202    free(db_path);
203
204    /*
205     * Set busy handler to wait when we use mult_db_connections = true
206     */
207    sqlite3_busy_handler(m_db_handle, sqlite_busy_handler, NULL);
208
209 #if defined(SQLITE3_INIT_QUERY)
210    sql_query(SQLITE3_INIT_QUERY);
211 #endif
212
213    if (!check_tables_version(jcr, this)) {
214       goto bail_out;
215    }
216
217    retval = true;
218
219 bail_out:
220    V(mutex);
221    return retval;
222 }
223
224 void B_DB_SQLITE::db_close_database(JCR *jcr)
225 {
226    db_end_transaction(jcr);
227    P(mutex);
228    m_ref_count--;
229    if (m_ref_count == 0) {
230       sql_free_result();
231       db_list->remove(this);
232       if (m_connected && m_db_handle) {
233          sqlite3_close(m_db_handle);
234       }
235       rwl_destroy(&m_lock);
236       free_pool_memory(errmsg);
237       free_pool_memory(cmd);
238       free_pool_memory(cached_path);
239       free_pool_memory(fname);
240       free_pool_memory(path);
241       free_pool_memory(esc_name);
242       free_pool_memory(esc_path);
243       free_pool_memory(esc_obj);
244       if (m_db_driver) {
245          free(m_db_driver);
246       }
247       if (m_db_name) {
248          free(m_db_name);
249       }
250       delete this;
251       if (db_list->size() == 0) {
252          delete db_list;
253          db_list = NULL;
254       }
255    }
256    V(mutex);
257 }
258
259 void B_DB_SQLITE::db_thread_cleanup(void)
260 {
261    sqlite3_thread_cleanup();
262 }
263
264 /*
265  * Escape strings so that SQLite is happy
266  *
267  *   NOTE! len is the length of the old string. Your new
268  *         string must be long enough (max 2*old+1) to hold
269  *         the escaped output.
270  */
271 void B_DB_SQLITE::db_escape_string(JCR *jcr, char *snew, char *old, int len)
272 {
273    char *n, *o;
274
275    n = snew;
276    o = old;
277    while (len--) {
278       switch (*o) {
279       case '\'':
280          *n++ = '\'';
281          *n++ = '\'';
282          o++;
283          break;
284       case 0:
285          *n++ = '\\';
286          *n++ = 0;
287          o++;
288          break;
289       default:
290          *n++ = *o++;
291          break;
292       }
293    }
294    *n = 0;
295 }
296
297 /*
298  * Escape binary object so that SQLite is happy
299  * Memory is stored in B_DB struct, no need to free it
300  *
301  * TODO: this should be implemented  (escape \0)
302  */
303 char *B_DB_SQLITE::db_escape_object(JCR *jcr, char *old, int len)
304 {
305    int l;
306    int max = len*2;           /* TODO: too big, should be *4/3 */
307
308    esc_obj = check_pool_memory_size(esc_obj, max);
309    l = bin_to_base64(esc_obj, max, old, len, true);
310    esc_obj[l] = 0;
311    ASSERT(l < max);    /* TODO: add check for l */
312
313    return esc_obj;
314 }
315
316 /*
317  * Unescape binary object so that SQLIte is happy
318  *
319  * TODO: need to be implemented (escape \0)
320  */
321
322 void B_DB_SQLITE::db_unescape_object(JCR *jcr, char *from, int32_t expected_len,
323                                      POOLMEM **dest, int32_t *dest_len)
324 {
325    if (!from) {
326       *dest[0] = 0;
327       *dest_len = 0;
328       return;
329    }
330    *dest = check_pool_memory_size(*dest, expected_len+1);
331    base64_to_bin(*dest, expected_len+1, from, strlen(from));
332    *dest_len = expected_len;
333    (*dest)[expected_len]=0;
334 }
335
336 /*
337  * Start a transaction. This groups inserts and makes things
338  * much more efficient. Usually started when inserting
339  * file attributes.
340  */
341 void B_DB_SQLITE::db_start_transaction(JCR *jcr)
342 {
343    if (!jcr->attr) {
344       jcr->attr = get_pool_memory(PM_FNAME);
345    }
346    if (!jcr->ar) {
347       jcr->ar = (ATTR_DBR *)malloc(sizeof(ATTR_DBR));
348    }
349
350    if (!m_allow_transactions) {
351       return;
352    }
353
354    db_lock(this);
355    /*
356     * Allow only 10,000 changes per transaction
357     */
358    if (m_transaction && changes > 10000) {
359       db_end_transaction(jcr);
360    }
361    if (!m_transaction) {
362       sql_query("BEGIN");  /* begin transaction */
363       Dmsg0(400, "Start SQLite transaction\n");
364       m_transaction = true;
365    }
366    db_unlock(this);
367 }
368
369 void B_DB_SQLITE::db_end_transaction(JCR *jcr)
370 {
371    if (jcr && jcr->cached_attribute) {
372       Dmsg0(400, "Flush last cached attribute.\n");
373       if (!db_create_attributes_record(jcr, this, jcr->ar)) {
374          Jmsg1(jcr, M_FATAL, 0, _("Attribute create error. %s"), db_strerror(jcr->db));
375       }
376       jcr->cached_attribute = false;
377    }
378
379    if (!m_allow_transactions) {
380       return;
381    }
382
383    db_lock(this);
384    if (m_transaction) {
385       sql_query("COMMIT"); /* end transaction */
386       m_transaction = false;
387       Dmsg1(400, "End SQLite transaction changes=%d\n", changes);
388    }
389    changes = 0;
390    db_unlock(this);
391 }
392
393 struct rh_data {
394    B_DB_SQLITE *mdb;
395    DB_RESULT_HANDLER *result_handler;
396    void *ctx;
397    bool initialized;
398 };
399
400 /*
401  * Convert SQLite's callback into Bacula DB callback
402  */
403 static int sqlite_result_handler(void *arh_data, int num_fields, char **rows, char **col_names)
404 {
405    struct rh_data *rh_data = (struct rh_data *)arh_data;
406
407    /* The db_sql_query doesn't have access to m_results, so if we wan't to get
408     * fields information, we need to use col_names
409     */
410    if (!rh_data->initialized) {
411       rh_data->mdb->set_column_names(col_names, num_fields);
412       rh_data->initialized = true;
413    }
414    if (rh_data->result_handler) {
415       (*(rh_data->result_handler))(rh_data->ctx, num_fields, rows);
416    }
417    
418    return 0;
419 }
420
421 /*
422  * Submit a general SQL command (cmd), and for each row returned,
423  *  the result_handler is called with the ctx.
424  */
425 bool B_DB_SQLITE::db_sql_query(const char *query, DB_RESULT_HANDLER *result_handler, void *ctx)
426 {
427    bool retval = false;
428    int stat;
429    struct rh_data rh_data;
430
431    Dmsg1(500, "db_sql_query starts with '%s'\n", query);
432
433    db_lock(this);
434    if (m_sqlite_errmsg) {
435       sqlite3_free(m_sqlite_errmsg);
436       m_sqlite_errmsg = NULL;
437    }
438    sql_free_result();
439
440    rh_data.ctx = ctx;
441    rh_data.mdb = this;
442    rh_data.initialized = false;
443    rh_data.result_handler = result_handler;
444
445    stat = sqlite3_exec(m_db_handle, query, sqlite_result_handler,
446                        (void *)&rh_data, &m_sqlite_errmsg);
447    
448    if (stat != SQLITE_OK) {
449       Mmsg(errmsg, _("Query failed: %s: ERR=%s\n"), query, sql_strerror());
450       Dmsg0(500, "db_sql_query finished\n");
451       goto bail_out;
452    }
453    Dmsg0(500, "db_sql_query finished\n");
454    sql_free_result();
455    retval = true;
456
457 bail_out:
458    db_unlock(this);
459    return retval;
460 }
461
462 /*
463  * Submit a sqlite query and retrieve all the data
464  */
465 bool B_DB_SQLITE::sql_query(const char *query, int flags)
466 {
467    int stat;
468    bool retval = false;
469
470    Dmsg1(500, "sql_query starts with '%s'\n", query);
471
472    sql_free_result();
473    if (m_sqlite_errmsg) {
474       sqlite3_free(m_sqlite_errmsg);
475       m_sqlite_errmsg = NULL;
476    }
477
478    stat = sqlite3_get_table(m_db_handle, (char *)query, &m_result,
479                             &m_num_rows, &m_num_fields, &m_sqlite_errmsg);
480
481    m_row_number = 0;               /* no row fetched */
482    if (stat != 0) {                   /* something went wrong */
483       m_num_rows = m_num_fields = 0;
484       Dmsg0(500, "sql_query finished\n");
485    } else {
486       Dmsg0(500, "sql_query finished\n");
487       retval = true;
488    }
489    return retval;
490 }
491
492 void B_DB_SQLITE::sql_free_result(void)
493 {
494    db_lock(this);
495    if (m_fields) {
496       free(m_fields);
497       m_fields = NULL;
498    }
499    if (m_result) {
500       sqlite3_free_table(m_result);
501       m_result = NULL;
502    }
503    m_col_names = NULL;
504    m_num_rows = m_num_fields = 0;
505    db_unlock(this);
506 }
507
508 /*
509  * Fetch one row at a time
510  */
511 SQL_ROW B_DB_SQLITE::sql_fetch_row(void)
512 {
513    if (!m_result || (m_row_number >= m_num_rows)) {
514       return NULL;
515    }
516    m_row_number++;
517    return &m_result[m_num_fields * m_row_number];
518 }
519
520 const char *B_DB_SQLITE::sql_strerror(void)
521 {
522    return m_sqlite_errmsg ? m_sqlite_errmsg : "unknown";
523 }
524
525 void B_DB_SQLITE::sql_data_seek(int row)
526 {
527    /*
528     * Set the row number to be returned on the next call to sql_fetch_row
529     */
530    m_row_number = row;
531 }
532
533 int B_DB_SQLITE::sql_affected_rows(void)
534 {
535    return sqlite3_changes(m_db_handle);
536 }
537
538 uint64_t B_DB_SQLITE::sql_insert_autokey_record(const char *query, const char *table_name)
539 {
540    /*
541     * First execute the insert query and then retrieve the currval.
542     */
543    if (!sql_query(query)) {
544       return 0;
545    }
546
547    m_num_rows = sql_affected_rows();
548    if (m_num_rows != 1) {
549       return 0;
550    }
551
552    changes++;
553
554    return sqlite3_last_insert_rowid(m_db_handle);
555 }
556
557 SQL_FIELD *B_DB_SQLITE::sql_fetch_field(void)
558 {
559    int i, j, len;
560
561    /* We are in the middle of a db_sql_query and we want to get fields info */
562    if (m_col_names != NULL) {
563       if (m_num_fields > m_field_number) {
564          m_sql_field.name = m_col_names[m_field_number];
565          /* We don't have the maximum field length, so we can use 80 as
566           * estimation.
567           */
568          len = MAX(cstrlen(m_sql_field.name), 80/m_num_fields);
569          m_sql_field.max_length = len;
570
571          m_field_number++;
572          m_sql_field.type = 0;  /* not numeric */
573          m_sql_field.flags = 1; /* not null */
574          return &m_sql_field;
575       } else {                  /* too much fetch_field() */
576          return NULL;
577       }
578    }
579
580    /* We are after a sql_query() that stores the result in m_results */
581    if (!m_fields || m_fields_size < m_num_fields) {
582       if (m_fields) {
583          free(m_fields);
584          m_fields = NULL;
585       }
586       Dmsg1(500, "allocating space for %d fields\n", m_num_fields);
587       m_fields = (SQL_FIELD *)malloc(sizeof(SQL_FIELD) * m_num_fields);
588       m_fields_size = m_num_fields;
589
590       for (i = 0; i < m_num_fields; i++) {
591          Dmsg1(500, "filling field %d\n", i);
592          m_fields[i].name = m_result[i];
593          m_fields[i].max_length = cstrlen(m_fields[i].name);
594          for (j = 1; j <= m_num_rows; j++) {
595             if (m_result[i + m_num_fields * j]) {
596                len = (uint32_t)cstrlen(m_result[i + m_num_fields * j]);
597             } else {
598                len = 0;
599             }
600             if (len > m_fields[i].max_length) {
601                m_fields[i].max_length = len;
602             }
603          }
604          m_fields[i].type = 0;
605          m_fields[i].flags = 1;        /* not null */
606
607          Dmsg4(500, "sql_fetch_field finds field '%s' has length='%d' type='%d' and IsNull=%d\n",
608                m_fields[i].name, m_fields[i].max_length, m_fields[i].type, m_fields[i].flags);
609       }
610    }
611
612    /*
613     * Increment field number for the next time around
614     */
615    return &m_fields[m_field_number++];
616 }
617
618 bool B_DB_SQLITE::sql_field_is_not_null(int field_type)
619 {
620    switch (field_type) {
621    case 1:
622       return true;
623    default:
624       return false;
625    }
626 }
627
628 bool B_DB_SQLITE::sql_field_is_numeric(int field_type)
629 {
630    switch (field_type) {
631    case 1:
632       return true;
633    default:
634       return false;
635    }
636 }
637
638 /* 
639  * Returns true if OK
640  *         false if failed
641  */
642 bool B_DB_SQLITE::sql_batch_start(JCR *jcr)
643 {
644    bool retval;
645
646    db_lock(this);
647    retval = sql_query("CREATE TEMPORARY TABLE batch ("
648                               "FileIndex integer,"
649                               "JobId integer,"
650                               "Path blob,"
651                               "Name blob,"
652                               "LStat tinyblob,"
653                               "MD5 tinyblob,"
654                               "DeltaSeq integer)");
655    db_unlock(this);
656
657    return retval;
658 }
659
660 /* set error to something to abort operation */
661 /* 
662  * Returns true if OK
663  *         false if failed
664  */
665 bool B_DB_SQLITE::sql_batch_end(JCR *jcr, const char *error)
666 {
667    m_status = 0;
668
669    return true;
670 }
671
672 /* 
673  * Returns true if OK
674  *         false if failed
675  */
676 bool B_DB_SQLITE::sql_batch_insert(JCR *jcr, ATTR_DBR *ar)
677 {
678    const char *digest;
679    char ed1[50];
680
681    esc_name = check_pool_memory_size(esc_name, fnl*2+1);
682    db_escape_string(jcr, esc_name, fname, fnl);
683
684    esc_path = check_pool_memory_size(esc_path, pnl*2+1);
685    db_escape_string(jcr, esc_path, path, pnl);
686
687    if (ar->Digest == NULL || ar->Digest[0] == 0) {
688       digest = "0";
689    } else {
690       digest = ar->Digest;
691    }
692
693    Mmsg(cmd, "INSERT INTO batch VALUES "
694         "(%u,%s,'%s','%s','%s','%s',%u)",
695         ar->FileIndex, edit_int64(ar->JobId,ed1), esc_path,
696         esc_name, ar->attr, digest, ar->DeltaSeq);
697
698    return sql_query(cmd);
699 }
700
701 /*
702  * Initialize database data structure. In principal this should
703  * never have errors, or it is really fatal.
704  */
705 B_DB *db_init_database(JCR *jcr, const char *db_driver, const char *db_name,
706                        const char *db_user, const char *db_password, 
707                        const char *db_address, int db_port, 
708                        const char *db_socket, bool mult_db_connections, 
709                        bool disable_batch_insert)
710 {
711    B_DB *mdb = NULL;
712
713    P(mutex);                          /* lock DB queue */
714    /*
715     * Look to see if DB already open
716     */
717    if (db_list && !mult_db_connections) {
718       foreach_dlist(mdb, db_list) {
719          if (mdb->db_match_database(db_driver, db_name, db_address, db_port)) {
720             Dmsg1(300, "DB REopen %s\n", db_name);
721             mdb->increment_refcount();
722             goto bail_out;
723          }
724       }
725    }
726    Dmsg0(300, "db_init_database first time\n");
727    mdb = New(B_DB_SQLITE(jcr, db_driver, db_name, db_user, db_password,
728                          db_address, db_port, db_socket, mult_db_connections,
729                          disable_batch_insert));
730
731 bail_out:
732    V(mutex);
733    return mdb;
734 }
735
736 #endif /* HAVE_SQLITE3 */