]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/mysql.c
Add address and socket for MySQL
[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(void *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    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->db_user = bstrdup(db_user);
79    mdb->db_password = bstrdup(db_password);
80    if (db_address) {
81       mdb->db_address = bstrdup(db_address);
82    }
83    if (db_socket) {
84       mdb->db_socket = bstrdup(db_socket);
85    }
86    mdb->db_port = db_port;
87    mdb->have_insert_id = TRUE;
88    mdb->errmsg = get_pool_memory(PM_EMSG); /* get error message buffer */
89    *mdb->errmsg = 0;
90    mdb->cmd = get_pool_memory(PM_EMSG);    /* get command buffer */
91    mdb->cached_path = get_pool_memory(PM_FNAME);
92    mdb->cached_path_id = 0;
93    mdb->ref_count = 1;
94    mdb->fname = get_pool_memory(PM_FNAME);
95    mdb->path = get_pool_memory(PM_FNAME);
96    mdb->esc_name = get_pool_memory(PM_FNAME);
97    qinsert(&db_list, &mdb->bq);            /* put db in list */
98    V(mutex);
99    return mdb;
100 }
101
102 /*
103  * Now actually open the database.  This can generate errors,
104  * which are returned in the errmsg
105  */
106 int
107 db_open_database(void *jcr, B_DB *mdb)
108 {
109    int errstat;
110
111    P(mutex);
112    if (mdb->connected) {
113       V(mutex);
114       return 1;
115    }
116    mdb->connected = FALSE;
117
118    if ((errstat=rwl_init(&mdb->lock)) != 0) {
119       Mmsg1(&mdb->errmsg, _("Unable to initialize DB lock. ERR=%s\n"), 
120             strerror(errstat));
121       V(mutex);
122       return 0;
123    }
124
125    /* connect to the database */
126 #ifdef HAVE_EMBEDDED_MYSQL
127    mysql_server_init(0, NULL, NULL);
128 #endif
129    mysql_init(&(mdb->mysql));
130    Dmsg0(50, "mysql_init done\n");
131    mdb->db = mysql_real_connect(
132         &(mdb->mysql),                /* db */
133         mdb->db_address,              /* default = localhost */
134         mdb->db_user,                 /*  login name */
135         mdb->db_password,             /*  password */
136         mdb->db_name,                 /* database name */
137         mdb->db_port,                 /* default port */
138         mdb->db_socket,               /* default = socket */
139         0);                           /* flags = none */
140
141    /* If no connect, try once more incase it is a timing problem */
142    if (mdb->db == NULL) {
143       mdb->db = mysql_real_connect(
144            &(mdb->mysql),                /* db */
145            mdb->db_address,              /* default = localhost */
146            mdb->db_user,                 /*  login name */
147            mdb->db_password,             /*  password */
148            mdb->db_name,                 /* database name */
149            mdb->db_port,                 /* default port */
150            mdb->db_socket,               /* default = socket */
151            0);                           /* flags = none */
152    }
153     
154    Dmsg0(50, "mysql_real_connect done\n");
155    Dmsg3(50, "db_user=%s db_name=%s db_password=%s\n", mdb->db_user, mdb->db_name, 
156             mdb->db_password==NULL?"(NULL)":mdb->db_password);
157   
158    if (mdb->db == NULL) {
159       Mmsg2(&mdb->errmsg, _("Unable to connect to MySQL server. \n\
160 Database=%s User=%s\n\
161 It is probably not running or your password is incorrect.\n"), 
162          mdb->db_name, mdb->db_user);
163       V(mutex);
164       return 0;
165    }
166
167    if (!check_tables_version(jcr, mdb)) {
168       V(mutex);
169       return 0;
170    }
171
172    mdb->connected = TRUE;
173    V(mutex);
174    return 1;
175 }
176
177 void
178 db_close_database(void *jcr, B_DB *mdb)
179 {
180    P(mutex);
181    mdb->ref_count--;
182    if (mdb->ref_count == 0) {
183       qdchain(&mdb->bq);
184       if (mdb->connected && mdb->db) {
185          sql_close(mdb);
186 #ifdef HAVE_EMBEDDED_MYSQL
187          mysql_server_end();
188 #endif
189       }
190 /*    pthread_mutex_destroy(&mdb->mutex); */
191       rwl_destroy(&mdb->lock);       
192       free_pool_memory(mdb->errmsg);
193       free_pool_memory(mdb->cmd);
194       free_pool_memory(mdb->cached_path);
195       free_pool_memory(mdb->fname);
196       free_pool_memory(mdb->path);
197       free_pool_memory(mdb->esc_name);
198       if (mdb->db_name) {
199          free(mdb->db_name);
200       }
201       if (mdb->db_user) {
202          free(mdb->db_user);
203       }
204       if (mdb->db_password) {
205          free(mdb->db_password);
206       }
207       if (mdb->db_address) {
208          free(mdb->db_address);
209       }
210       if (mdb->db_socket) {
211          free(mdb->db_socket);
212       }
213       free(mdb);
214    }
215    V(mutex);
216 }
217
218 /*
219  * Return the next unique index (auto-increment) for
220  * the given table.  Return NULL on error.
221  *  
222  * For MySQL, NULL causes the auto-increment value
223  *  to be updated.
224  */
225 int db_next_index(void *jcr, B_DB *mdb, char *table, char *index)
226 {
227    strcpy(index, "NULL");
228    return 1;
229 }   
230
231
232 /*
233  * Escape strings so that MySQL is happy
234  *
235  *   NOTE! len is the length of the old string. Your new
236  *         string must be long enough (max 2*old) to hold
237  *         the escaped output.
238  */
239 void
240 db_escape_string(char *snew, char *old, int len)
241 {
242    mysql_escape_string(snew, old, len);
243
244 #ifdef DO_IT_MYSELF
245    char *n, *o;
246
247    n = snew;
248    o = old;
249    while (len--) {
250       switch (*o) {
251       case 0:
252          *n++= '\\';
253          *n++= '0';
254          o++;
255          break;
256       case '\n':
257          *n++= '\\';
258          *n++= 'n';
259          o++;
260          break;
261       case '\r':
262          *n++= '\\';
263          *n++= 'r';
264          o++;
265          break;
266       case '\\':
267          *n++= '\\';
268          *n++= '\\';
269          o++;
270          break;
271       case '\'':
272          *n++= '\\';
273          *n++= '\'';
274          o++;
275          break;
276       case '"':
277          *n++= '\\';
278          *n++= '"';
279          o++;
280          break;
281       case '\032':
282          *n++= '\\';
283          *n++= 'Z';
284          o++;
285          break;
286       default:
287          *n++= *o++;
288       }
289    }
290    *n = 0;
291 #endif
292 }
293
294 /*
295  * Submit a general SQL command (cmd), and for each row returned,
296  *  the sqlite_handler is called with the ctx.
297  */
298 int db_sql_query(B_DB *mdb, char *query, DB_RESULT_HANDLER *result_handler, void *ctx)
299 {
300    SQL_ROW row;
301   
302    db_lock(mdb);
303    if (sql_query(mdb, query) != 0) {
304       Mmsg(&mdb->errmsg, _("Query failed: %s: ERR=%s\n"), query, sql_strerror(mdb));
305       db_unlock(mdb);
306       return 0;
307    }
308    if (result_handler != NULL) {
309       if ((mdb->result = sql_store_result(mdb)) != NULL) {
310          int num_fields = sql_num_fields(mdb);
311
312          while ((row = sql_fetch_row(mdb)) != NULL) {
313             if (result_handler(ctx, num_fields, row))
314                break;
315          }
316
317          sql_free_result(mdb);
318       }
319    }
320    db_unlock(mdb);
321    return 1;
322
323 }
324
325
326 static void
327 list_dashes(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
328 {
329    SQL_FIELD  *field;
330    unsigned int i, j;
331
332    sql_field_seek(mdb, 0);
333    send(ctx, "+");
334    for (i = 0; i < sql_num_fields(mdb); i++) {
335       field = sql_fetch_field(mdb);
336       for (j = 0; j < field->max_length + 2; j++)
337               send(ctx, "-");
338       send(ctx, "+");
339    }
340    send(ctx, "\n");
341 }
342
343 void
344 list_result(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
345 {
346    SQL_FIELD *field;
347    SQL_ROW    row;
348    unsigned int i, col_len;
349    char buf[2000], ewc[30];
350
351    if (mdb->result == NULL) {
352       send(ctx, _("No results to list.\n"));
353       return;
354    }
355    /* determine column display widths */
356    sql_field_seek(mdb, 0);
357    for (i = 0; i < sql_num_fields(mdb); i++) {
358       field = sql_fetch_field(mdb);
359       if (IS_NUM(field->type) && field->max_length > 0) { /* fixup for commas */
360          field->max_length += (field->max_length - 1) / 3;
361       }
362       col_len = strlen(field->name);
363       if (col_len < field->max_length)
364               col_len = field->max_length;
365       if (col_len < 4 && !IS_NOT_NULL(field->flags))
366               col_len = 4;    /* 4 = length of the word "NULL" */
367       field->max_length = col_len;    /* reset column info */
368    }
369
370    list_dashes(mdb, send, ctx);
371    send(ctx, "|");
372    sql_field_seek(mdb, 0);
373    for (i = 0; i < sql_num_fields(mdb); i++) {
374       field = sql_fetch_field(mdb);
375       sprintf(buf, " %-*s |", (int)field->max_length, field->name);
376       send(ctx, buf);
377    }
378    send(ctx, "\n");
379    list_dashes(mdb, send, ctx);
380
381    while ((row = sql_fetch_row(mdb)) != NULL) {
382       sql_field_seek(mdb, 0);
383       send(ctx, "|");
384       for (i = 0; i < sql_num_fields(mdb); i++) {
385          field = sql_fetch_field(mdb);
386          if (row[i] == NULL) {
387             sprintf(buf, " %-*s |", (int)field->max_length, "NULL");
388          } else if (IS_NUM(field->type)) {
389             sprintf(buf, " %*s |", (int)field->max_length,       
390                add_commas(row[i], ewc));
391          } else {
392             sprintf(buf, " %-*s |", (int)field->max_length, row[i]);
393          }
394          send(ctx, buf);
395       }
396       send(ctx, "\n");
397    }
398    list_dashes(mdb, send, ctx);
399 }
400
401
402 #endif /* HAVE_MYSQL */