]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/mysql.c
Misc -- see ChangeLog
[bacula/bacula] / bacula / src / cats / mysql.c
1 /*
2  * Bacula Catalog Database routines specific to MySQL
3  *   These are MySQL specific routines -- hopefully all
4  *    other files are generic.
5  *
6  *    Kern Sibbald, March 2000
7  *
8  *    Version $Id$
9  */
10
11 /*
12    Copyright (C) 2000-2003 Kern Sibbald and John Walker
13
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of
17    the License, or (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22    General Public License for more details.
23
24    You should have received a copy of the GNU General Public
25    License along with this program; if not, write to the Free
26    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27    MA 02111-1307, USA.
28
29  */
30
31
32 /* The following is necessary so that we do not include
33  * the dummy external definition of DB.
34  */
35 #define __SQL_C                       /* indicate that this is sql.c */
36
37 #include "bacula.h"
38 #include "cats.h"
39
40 #ifdef HAVE_MYSQL
41
42 /* -----------------------------------------------------------------------
43  *
44  *   MySQL dependent defines and subroutines
45  *
46  * -----------------------------------------------------------------------
47  */
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 /*
55  * Initialize database data structure. In principal this should
56  * never have errors, or it is really fatal.
57  */
58 B_DB *
59 db_init_database(JCR *jcr, char *db_name, char *db_user, char *db_password, 
60                  char *db_address, int db_port, char *db_socket) 
61 {
62    B_DB *mdb;
63
64    if (!db_user) {              
65       Jmsg(jcr, M_FATAL, 0, _("A user name for MySQL must be supplied.\n"));
66       return NULL;
67    }
68    P(mutex);                          /* lock DB queue */
69    /* Look to see if DB already open */
70    for (mdb=NULL; (mdb=(B_DB *)qnext(&db_list, &mdb->bq)); ) {
71       if (strcmp(mdb->db_name, db_name) == 0) {
72          Dmsg2(100, "DB REopen %d %s\n", mdb->ref_count, db_name);
73          mdb->ref_count++;
74          V(mutex);
75          return mdb;                  /* already open */
76       }
77    }
78    Dmsg0(100, "db_open first time\n");
79    mdb = (B_DB *) malloc(sizeof(B_DB));
80    memset(mdb, 0, sizeof(B_DB));
81    mdb->db_name = bstrdup(db_name);
82    mdb->db_user = bstrdup(db_user);
83    if (db_password) {
84       mdb->db_password = bstrdup(db_password);
85    }
86    if (db_address) {
87       mdb->db_address = bstrdup(db_address);
88    }
89    if (db_socket) {
90       mdb->db_socket = bstrdup(db_socket);
91    }
92    mdb->db_port = db_port;
93    mdb->have_insert_id = TRUE;
94    mdb->errmsg = get_pool_memory(PM_EMSG); /* get error message buffer */
95    *mdb->errmsg = 0;
96    mdb->cmd = get_pool_memory(PM_EMSG);    /* get command buffer */
97    mdb->cached_path = get_pool_memory(PM_FNAME);
98    mdb->cached_path_id = 0;
99    mdb->ref_count = 1;
100    mdb->fname = get_pool_memory(PM_FNAME);
101    mdb->path = get_pool_memory(PM_FNAME);
102    mdb->esc_name = get_pool_memory(PM_FNAME);
103    qinsert(&db_list, &mdb->bq);            /* put db in list */
104    V(mutex);
105    return mdb;
106 }
107
108 /*
109  * Now actually open the database.  This can generate errors,
110  * which are returned in the errmsg
111  */
112 int
113 db_open_database(JCR *jcr, B_DB *mdb)
114 {
115    int errstat;
116
117    P(mutex);
118    if (mdb->connected) {
119       V(mutex);
120       return 1;
121    }
122    mdb->connected = FALSE;
123
124    if ((errstat=rwl_init(&mdb->lock)) != 0) {
125       Mmsg1(&mdb->errmsg, _("Unable to initialize DB lock. ERR=%s\n"), 
126             strerror(errstat));
127       V(mutex);
128       return 0;
129    }
130
131    /* connect to the database */
132 #ifdef HAVE_EMBEDDED_MYSQL
133    mysql_server_init(0, NULL, NULL);
134 #endif
135    mysql_init(&(mdb->mysql));
136    Dmsg0(50, "mysql_init done\n");
137    mdb->db = mysql_real_connect(
138         &(mdb->mysql),                /* db */
139         mdb->db_address,              /* default = localhost */
140         mdb->db_user,                 /*  login name */
141         mdb->db_password,             /*  password */
142         mdb->db_name,                 /* database name */
143         mdb->db_port,                 /* default port */
144         mdb->db_socket,               /* default = socket */
145         CLIENT_FOUND_ROWS);           /* flags */
146
147    /* If no connect, try once more in case it is a timing problem */
148    if (mdb->db == NULL) {
149       mdb->db = mysql_real_connect(
150            &(mdb->mysql),                /* db */
151            mdb->db_address,              /* default = localhost */
152            mdb->db_user,                 /*  login name */
153            mdb->db_password,             /*  password */
154            mdb->db_name,                 /* database name */
155            mdb->db_port,                 /* default port */
156            mdb->db_socket,               /* default = socket */
157            CLIENT_FOUND_ROWS);           /* flags */
158    }
159     
160    Dmsg0(50, "mysql_real_connect done\n");
161    Dmsg3(50, "db_user=%s db_name=%s db_password=%s\n", mdb->db_user, mdb->db_name, 
162             mdb->db_password==NULL?"(NULL)":mdb->db_password);
163   
164    if (mdb->db == NULL) {
165       Mmsg2(&mdb->errmsg, _("Unable to connect to MySQL server. \n\
166 Database=%s User=%s\n\
167 It is probably not running or your password is incorrect.\n"), 
168          mdb->db_name, mdb->db_user);
169       V(mutex);
170       return 0;
171    }
172
173    if (!check_tables_version(jcr, mdb)) {
174       V(mutex);
175       db_close_database(jcr, mdb);
176       return 0;
177    }
178
179    my_thread_init();
180
181    mdb->connected = TRUE;
182    V(mutex);
183    return 1;
184 }
185
186 void
187 db_close_database(JCR *jcr, B_DB *mdb)
188 {
189    P(mutex);
190    mdb->ref_count--;
191    my_thread_end();
192    if (mdb->ref_count == 0) {
193       qdchain(&mdb->bq);
194       if (mdb->connected && mdb->db) {
195          sql_close(mdb);
196 #ifdef HAVE_EMBEDDED_MYSQL
197          mysql_server_end();
198 #endif
199       }
200       rwl_destroy(&mdb->lock);       
201       free_pool_memory(mdb->errmsg);
202       free_pool_memory(mdb->cmd);
203       free_pool_memory(mdb->cached_path);
204       free_pool_memory(mdb->fname);
205       free_pool_memory(mdb->path);
206       free_pool_memory(mdb->esc_name);
207       if (mdb->db_name) {
208          free(mdb->db_name);
209       }
210       if (mdb->db_user) {
211          free(mdb->db_user);
212       }
213       if (mdb->db_password) {
214          free(mdb->db_password);
215       }
216       if (mdb->db_address) {
217          free(mdb->db_address);
218       }
219       if (mdb->db_socket) {
220          free(mdb->db_socket);
221       }
222       free(mdb);
223    }
224    V(mutex);
225 }
226
227 /*
228  * Return the next unique index (auto-increment) for
229  * the given table.  Return NULL on error.
230  *  
231  * For MySQL, NULL causes the auto-increment value
232  *  to be updated.
233  */
234 int db_next_index(JCR *jcr, B_DB *mdb, char *table, char *index)
235 {
236    strcpy(index, "NULL");
237    return 1;
238 }   
239
240
241 /*
242  * Escape strings so that MySQL is happy
243  *
244  *   NOTE! len is the length of the old string. Your new
245  *         string must be long enough (max 2*old+1) to hold
246  *         the escaped output.
247  */
248 void
249 db_escape_string(char *snew, char *old, int len)
250 {
251    mysql_escape_string(snew, old, len);
252
253 #ifdef DO_IT_MYSELF
254
255 /* Should use mysql_real_escape_string ! */
256 unsigned long mysql_real_escape_string(MYSQL *mysql, char *to, const char *from, unsigned long length);
257
258    char *n, *o;
259
260    n = snew;
261    o = old;
262    while (len--) {
263       switch (*o) {
264       case 0:
265          *n++= '\\';
266          *n++= '0';
267          o++;
268          break;
269       case '\n':
270          *n++= '\\';
271          *n++= 'n';
272          o++;
273          break;
274       case '\r':
275          *n++= '\\';
276          *n++= 'r';
277          o++;
278          break;
279       case '\\':
280          *n++= '\\';
281          *n++= '\\';
282          o++;
283          break;
284       case '\'':
285          *n++= '\\';
286          *n++= '\'';
287          o++;
288          break;
289       case '"':
290          *n++= '\\';
291          *n++= '"';
292          o++;
293          break;
294       case '\032':
295          *n++= '\\';
296          *n++= 'Z';
297          o++;
298          break;
299       default:
300          *n++= *o++;
301       }
302    }
303    *n = 0;
304 #endif
305 }
306
307 /*
308  * Submit a general SQL command (cmd), and for each row returned,
309  *  the sqlite_handler is called with the ctx.
310  */
311 int db_sql_query(B_DB *mdb, char *query, DB_RESULT_HANDLER *result_handler, void *ctx)
312 {
313    SQL_ROW row;
314   
315    db_lock(mdb);
316    if (sql_query(mdb, query) != 0) {
317       Mmsg(&mdb->errmsg, _("Query failed: %s: ERR=%s\n"), query, sql_strerror(mdb));
318       db_unlock(mdb);
319       return 0;
320    }
321    if (result_handler != NULL) {
322       if ((mdb->result = sql_store_result(mdb)) != NULL) {
323          int num_fields = sql_num_fields(mdb);
324
325          while ((row = sql_fetch_row(mdb)) != NULL) {
326             if (result_handler(ctx, num_fields, row))
327                break;
328          }
329
330          sql_free_result(mdb);
331       }
332    }
333    db_unlock(mdb);
334    return 1;
335
336 }
337
338
339 static void
340 list_dashes(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
341 {
342    SQL_FIELD  *field;
343    unsigned int i, j;
344
345    sql_field_seek(mdb, 0);
346    send(ctx, "+");
347    for (i = 0; i < sql_num_fields(mdb); i++) {
348       field = sql_fetch_field(mdb);
349       for (j = 0; j < field->max_length + 2; j++)
350               send(ctx, "-");
351       send(ctx, "+");
352    }
353    send(ctx, "\n");
354 }
355
356 /*
357  * If full_list is set, we list vertically, otherwise, we 
358  * list on one line horizontally.      
359  */
360 void
361 list_result(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx, e_list_type type)
362 {
363    SQL_FIELD *field;
364    SQL_ROW row;
365    unsigned int i, col_len, max_len = 0;
366    char buf[2000], ewc[30];
367
368    if (mdb->result == NULL) {
369       send(ctx, _("No results to list.\n"));
370       return;
371    }
372    /* determine column display widths */
373    sql_field_seek(mdb, 0);
374    for (i = 0; i < sql_num_fields(mdb); i++) {
375       field = sql_fetch_field(mdb);
376       col_len = strlen(field->name);
377       if (type == VERT_LIST) {
378          if (col_len > max_len) {
379             max_len = col_len;
380          }
381       } else {
382          if (IS_NUM(field->type) && field->max_length > 0) { /* fixup for commas */
383             field->max_length += (field->max_length - 1) / 3;
384          }
385          if (col_len < field->max_length) {
386             col_len = field->max_length;
387          }
388          if (col_len < 4 && !IS_NOT_NULL(field->flags)) {
389             col_len = 4;                 /* 4 = length of the word "NULL" */
390          }
391          field->max_length = col_len;    /* reset column info */
392       }
393    }
394
395    if (type == VERT_LIST) {
396       goto vertical_list;
397    }
398
399    list_dashes(mdb, send, ctx);
400    send(ctx, "|");
401    sql_field_seek(mdb, 0);
402    for (i = 0; i < sql_num_fields(mdb); i++) {
403       field = sql_fetch_field(mdb);
404       bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, field->name);
405       send(ctx, buf);
406    }
407    send(ctx, "\n");
408    list_dashes(mdb, send, ctx);
409
410    while ((row = sql_fetch_row(mdb)) != NULL) {
411       sql_field_seek(mdb, 0);
412       send(ctx, "|");
413       for (i = 0; i < sql_num_fields(mdb); i++) {
414          field = sql_fetch_field(mdb);
415          if (row[i] == NULL) {
416             bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, "NULL");
417          } else if (IS_NUM(field->type)) {
418             bsnprintf(buf, sizeof(buf), " %*s |", (int)field->max_length,       
419                add_commas(row[i], ewc));
420          } else {
421             bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, row[i]);
422          }
423          send(ctx, buf);
424       }
425       send(ctx, "\n");
426    }
427    list_dashes(mdb, send, ctx);
428    return;
429
430 vertical_list:
431    
432    while ((row = sql_fetch_row(mdb)) != NULL) {
433       sql_field_seek(mdb, 0);
434       for (i = 0; i < sql_num_fields(mdb); i++) {
435          field = sql_fetch_field(mdb);
436          if (row[i] == NULL) {
437             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, "NULL");
438          } else if (IS_NUM(field->type)) {
439             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, 
440                add_commas(row[i], ewc));
441          } else {
442             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, row[i]);
443          }
444          send(ctx, buf);
445       }
446       send(ctx, "\n");
447    }
448    return;
449 }
450
451
452 #endif /* HAVE_MYSQL */