]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/cats/postgresql.c
It is maxvolbytes, not mavvolbytes
[bacula/bacula] / bacula / src / cats / postgresql.c
1 /*
2  * Bacula Catalog Database routines specific to PostgreSQL
3  *   These are PostgreSQL specific routines
4  *
5  *    Dan Langille, December 2004
6  *    based upon work done by 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_POSTGRESQL
41
42 /* -----------------------------------------------------------------------
43  *
44  *   PostgreSQL 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 PostgreSQL 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    mdb->db = PQsetdbLogin(
133         mdb->db_address,              /* default = localhost */
134         (char *) mdb->db_port,    /* default port */
135         NULL,                     /* pg options */
136         NULL,                     /* tty, ignored */
137         mdb->db_name,                 /* database name */
138         mdb->db_user,                 /* login name */
139         mdb->db_password);            /* password */
140
141    /* If no connect, try once more in case it is a timing problem */
142    if (PQstatus(mdb->db) != CONNECTION_OK) {
143    mdb->db = PQsetdbLogin(
144         mdb->db_address,              /* default = localhost */
145         (char *) mdb->db_port,    /* default port */
146         NULL,                     /* pg options */
147         NULL,                     /* tty, ignored */
148         mdb->db_name,                 /* database name */
149         mdb->db_user,                 /* login name */
150         mdb->db_password);            /* password */
151    }
152     
153    Dmsg0(50, "pg_real_connect done\n");
154    Dmsg3(50, "db_user=%s db_name=%s db_password=%s\n", mdb->db_user, mdb->db_name, 
155             mdb->db_password==NULL?"(NULL)":mdb->db_password);
156   
157    if (PQstatus(mdb->db) != CONNECTION_OK) {
158       Mmsg2(&mdb->errmsg, _("Unable to connect to PostgreSQL server.\n"
159             "Database=%s User=%s\n"
160             "It is probably not running or your password is incorrect.\n"),
161             mdb->db_name, mdb->db_user);
162       V(mutex);
163       return 0;
164    }
165
166    if (!check_tables_version(jcr, mdb)) {
167       V(mutex);
168       db_close_database(jcr, mdb);
169       return 0;
170    }
171
172    mdb->connected = TRUE;
173    V(mutex);
174    return 1;
175 }
176
177 void
178 db_close_database(JCR *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       }
187       rwl_destroy(&mdb->lock);       
188       free_pool_memory(mdb->errmsg);
189       free_pool_memory(mdb->cmd);
190       free_pool_memory(mdb->cached_path);
191       free_pool_memory(mdb->fname);
192       free_pool_memory(mdb->path);
193       free_pool_memory(mdb->esc_name);
194       if (mdb->db_name) {
195          free(mdb->db_name);
196       }
197       if (mdb->db_user) {
198          free(mdb->db_user);
199       }
200       if (mdb->db_password) {
201          free(mdb->db_password);
202       }
203       if (mdb->db_address) {
204          free(mdb->db_address);
205       }
206       if (mdb->db_socket) {
207          free(mdb->db_socket);
208       }
209       free(mdb);
210    }
211    V(mutex);
212 }
213
214 /*
215  * Return the next unique index (auto-increment) for
216  * the given table.  Return NULL on error.
217  *  
218  * For MySQL, NULL causes the auto-increment value
219  *  to be updated.
220  */
221 int db_next_index(JCR *jcr, B_DB *mdb, char *table, char *index)
222 {
223    strcpy(index, "NULL");
224    return 1;
225 }   
226
227
228 /*
229  * Escape strings so that PostgreSQL is happy
230  *
231  *   NOTE! len is the length of the old string. Your new
232  *         string must be long enough (max 2*old+1) to hold
233  *         the escaped output.
234  */
235 void
236 db_escape_string(char *snew, char *old, int len)
237 {
238    PQescapeString(snew, old, len);
239 }
240
241 /*
242  * Submit a general SQL command (cmd), and for each row returned,
243  *  the sqlite_handler is called with the ctx.
244  */
245 int db_sql_query(B_DB *mdb, char *query, DB_RESULT_HANDLER *result_handler, void *ctx)
246 {
247    SQL_ROW row;
248    int     numrows;
249
250    Dmsg0(50, "db_sql_query started\n");
251   
252    db_lock(mdb);
253    if (sql_query(mdb, query) != 0) {
254       Mmsg(&mdb->errmsg, _("Query failed: %s: ERR=%s\n"), query, sql_strerror(mdb));
255       db_unlock(mdb);
256       Dmsg0(50, "db_sql_query failed\n");
257       return 0;
258    }
259    Dmsg0(50, "db_sql_query succeeded. checking handler\n");
260
261    if (result_handler != NULL) {
262       Dmsg0(50, "db_sql_query invoking handler\n");
263       if ((mdb->result = sql_store_result(mdb)) != NULL) {
264          int num_fields = sql_num_fields(mdb);
265
266          Dmsg0(50, "db_sql_query sql_store_result suceeded\n");
267          while ((row = sql_fetch_row(mdb)) != NULL) {
268
269             Dmsg0(50, "db_sql_query sql_fetch_row worked\n");
270             if (result_handler(ctx, num_fields, row))
271                    break;
272          }
273
274          sql_free_result(mdb);
275       }
276    }
277    db_unlock(mdb);
278
279    Dmsg0(50, "db_sql_query finished\n");
280
281    return 1;
282 }
283
284
285 static void
286 list_dashes(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
287 {
288    SQL_FIELD  *field;
289    unsigned int i, j;
290
291    sql_field_seek(mdb, 0);
292    send(ctx, "+");
293    for (i = 0; i < sql_num_fields(mdb); i++) {
294       field = sql_fetch_field(mdb);
295       for (j = 0; j < field->max_length + 2; j++)
296               send(ctx, "-");
297       send(ctx, "+");
298    }
299    send(ctx, "\n");
300 }
301
302 /*
303  * If full_list is set, we list vertically, otherwise, we 
304  * list on one line horizontally.      
305  */
306 void
307 list_result(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx, e_list_type type)
308 {
309    SQL_FIELD *field;
310    SQL_ROW row;
311    unsigned int i, col_len, max_len = 0;
312    char buf[2000], ewc[30];
313
314    if (mdb->result == NULL) {
315       send(ctx, _("No results to list.\n"));
316       return;
317    }
318    /* determine column display widths */
319    sql_field_seek(mdb, 0);
320    for (i = 0; i < sql_num_fields(mdb); i++) {
321       field   = sql_fetch_field(mdb);
322       col_len = strlen(field->name);
323       if (type == VERT_LIST) {
324          if (col_len > max_len) {
325             max_len = col_len;
326          }
327       } else {
328          if (IS_NUM(field->type) && field->max_length > 0) { /* fixup for commas */
329             field->max_length += (field->max_length - 1) / 3;
330          }
331          if (col_len < field->max_length) {
332             col_len = field->max_length;
333          }
334          if (col_len < 4 && !IS_NOT_NULL(field->flags)) {
335             col_len = 4;                 /* 4 = length of the word "NULL" */
336          }
337          field->max_length = col_len;    /* reset column info */
338       }
339    }
340
341    if (type == VERT_LIST) {
342       goto vertical_list;
343    }
344
345    list_dashes(mdb, send, ctx);
346    send(ctx, "|");
347    sql_field_seek(mdb, 0);
348    for (i = 0; i < sql_num_fields(mdb); i++) {
349       field = sql_fetch_field(mdb);
350       bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, field->name);
351       send(ctx, buf);
352    }
353    send(ctx, "\n");
354    list_dashes(mdb, send, ctx);
355
356    while ((row = sql_fetch_row(mdb)) != NULL) {
357       sql_field_seek(mdb, 0);
358       send(ctx, "|");
359       for (i = 0; i < sql_num_fields(mdb); i++) {
360       field = sql_fetch_field(mdb);
361       if (row[i] == NULL) {
362          bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, "NULL");
363       } else if (IS_NUM(field->type)) {
364          bsnprintf(buf, sizeof(buf), " %*s |", (int)field->max_length,       
365              add_commas(row[i], ewc));
366          } else {
367              bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, row[i]);
368          }
369          send(ctx, buf);
370       }
371       send(ctx, "\n");
372    }
373    list_dashes(mdb, send, ctx);
374    return;
375
376 vertical_list:
377    
378    while ((row = sql_fetch_row(mdb)) != NULL) {
379       sql_field_seek(mdb, 0);
380       for (i = 0; i < sql_num_fields(mdb); i++) {
381       field = sql_fetch_field(mdb);
382       if (row[i] == NULL) {
383          bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, "NULL");
384       } else if (IS_NUM(field->type)) {
385             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, 
386                 add_commas(row[i], ewc));
387          } else {
388             bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, row[i]);
389          }
390          send(ctx, buf);
391       }
392       send(ctx, "\n");
393    }
394    return;
395 }
396
397 POSTGRESQL_ROW my_postgresql_fetch_row(B_DB *mdb) {
398         int            nFields;
399         int            j;
400         POSTGRESQL_ROW row = NULL; // by default, return NULL
401
402         Dmsg0(50, "my_postgresql_fetch_row start\n");
403         ASSERT(mdb->row != NULL);
404
405         // if still within the result set
406         if (mdb->row_number < mdb->num_rows) {
407                 Dmsg2(50, "my_postgresql_fetch_row row number '%d' is acceptable (0..%d)\n", mdb->row_number, mdb->num_rows);
408                 // allocate space for one row
409                 // get each value from this row
410                 for (j = 0; j < mdb->num_fields; j++) {
411                         mdb->row[j] = PQgetvalue(mdb->result, mdb->row_number, j);
412                         Dmsg2(50, "my_postgresql_fetch_row field '%d' is '%s'\n", j, mdb->row[j]);
413                 }
414                 // increment the row number for the next call
415                 mdb->row_number++;
416
417                 row = mdb->row;
418         } else {
419                 Dmsg2(50, "my_postgresql_fetch_row row number '%d' is NOT acceptable (0..%d)\n", mdb->row_number, mdb->num_rows);
420         }
421
422         Dmsg1(50, "my_postgresql_fetch_row finishes returning %x\n", row);
423
424         return row;
425 }
426
427 POSTGRESQL_FIELD * my_postgresql_fetch_field(B_DB *mdb) {
428         mdb->field.name       = PQfname    (mdb->result, mdb->field_number);
429
430         // I am not sure this returns the max width of the result set
431         mdb->field.max_length = PQfsize    (mdb->result, mdb->field_number);
432
433         // I am not sure this returns what we can use
434         mdb->field.type       = PQftype    (mdb->result, mdb->field_number);
435
436         mdb->field.flags      = PQgetisnull(mdb->result, mdb->row_number, mdb->field_number);
437
438         return &mdb->field;
439 }
440
441 void my_postgresql_data_seek(B_DB *mdb, int row) {
442         // set the row number to be returned on the next call
443         // to my_postgresql_fetch_row
444         mdb->row_number = row;
445 }
446
447 void my_postgresql_field_seek(B_DB *mdb, int field) {
448         mdb->field_number = field;
449 }
450
451 int my_postgresql_query(B_DB *mdb, char *query) {
452         Dmsg0(50, "my_postgresql_query started\n");
453         // We are starting a new query.  reset everything.
454         mdb->num_rows     = -1;
455         mdb->row_number   = -1;
456         mdb->field_number = -1;
457
458         if (mdb->row) {
459
460                 Dmsg0(50, "my_postgresql_query freeing space\n");
461                 free(mdb->row);
462                 mdb->row = NULL;
463         }
464
465
466         Dmsg1(50, "doing PQexec with '%s'\n", query);
467         mdb->result = PQexec(mdb->db, query);
468         if (PQresultStatus(mdb->result) == PGRES_TUPLES_OK) {
469
470                 mdb->num_rows   = PQntuples(mdb->result);
471                 // how many fields in the set?
472                 mdb->num_fields = PQnfields(mdb->result);
473
474                 // point at the first row for the fetch row function
475                 mdb->row_number = 0;
476
477                 mdb->row = (POSTGRESQL_ROW) malloc(sizeof(char *) * mdb->num_fields);
478                 Dmsg2(50, "PQexec was OK.  rows=%d columns=%d\n", mdb->num_rows, mdb->num_fields);
479                 mdb->status = 0;
480         } else {
481                 mdb->status = 1;
482         }
483
484         Dmsg0(50, "my_postgresql_query finishing\n");
485
486         return mdb->status;
487 }
488
489 void my_postgresql_free_result (B_DB *mdb) {
490         PQclear(mdb->result);
491         free(mdb->row);
492         mdb->row = NULL;
493 }
494
495
496 #endif /* HAVE_POSTGRESQL */