2 * Bacula Catalog Database routines specific to PostgreSQL
3 * These are PostgreSQL specific routines
5 * Dan Langille, December 2004
6 * based upon work done by Kern Sibbald, March 2000
12 Copyright (C) 2000-2003 Kern Sibbald and John Walker
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.
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.
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,
32 /* The following is necessary so that we do not include
33 * the dummy external definition of DB.
35 #define __SQL_C /* indicate that this is sql.c */
40 #ifdef HAVE_POSTGRESQL
42 /* -----------------------------------------------------------------------
44 * PostgreSQL dependent defines and subroutines
46 * -----------------------------------------------------------------------
49 /* List of open databases */
50 static BQUEUE db_list = {&db_list, &db_list};
52 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
55 * Initialize database data structure. In principal this should
56 * never have errors, or it is really fatal.
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)
65 Jmsg(jcr, M_FATAL, 0, _("A user name for PostgreSQL must be supplied.\n"));
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);
75 return mdb; /* already open */
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);
84 mdb->db_password = bstrdup(db_password);
87 mdb->db_address = bstrdup(db_address);
90 mdb->db_socket = bstrdup(db_socket);
92 mdb->db_port = db_port;
93 mdb->have_insert_id = TRUE;
94 mdb->errmsg = get_pool_memory(PM_EMSG); /* get error message buffer */
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;
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 */
109 * Now actually open the database. This can generate errors,
110 * which are returned in the errmsg
113 db_open_database(JCR *jcr, B_DB *mdb)
118 if (mdb->connected) {
122 mdb->connected = FALSE;
124 if ((errstat=rwl_init(&mdb->lock)) != 0) {
125 Mmsg1(&mdb->errmsg, _("Unable to initialize DB lock. ERR=%s\n"),
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 */
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 */
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);
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);
166 if (!check_tables_version(jcr, mdb)) {
168 db_close_database(jcr, mdb);
172 mdb->connected = TRUE;
178 db_close_database(JCR *jcr, B_DB *mdb)
182 if (mdb->ref_count == 0) {
184 if (mdb->connected && mdb->db) {
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);
200 if (mdb->db_password) {
201 free(mdb->db_password);
203 if (mdb->db_address) {
204 free(mdb->db_address);
206 if (mdb->db_socket) {
207 free(mdb->db_socket);
215 * Return the next unique index (auto-increment) for
216 * the given table. Return NULL on error.
218 * For MySQL, NULL causes the auto-increment value
221 int db_next_index(JCR *jcr, B_DB *mdb, char *table, char *index)
223 strcpy(index, "NULL");
229 * Escape strings so that PostgreSQL is happy
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.
236 db_escape_string(char *snew, char *old, int len)
238 PQescapeString(snew, old, len);
242 * Submit a general SQL command (cmd), and for each row returned,
243 * the sqlite_handler is called with the ctx.
245 int db_sql_query(B_DB *mdb, char *query, DB_RESULT_HANDLER *result_handler, void *ctx)
250 Dmsg0(50, "db_sql_query started\n");
253 if (sql_query(mdb, query) != 0) {
254 Mmsg(&mdb->errmsg, _("Query failed: %s: ERR=%s\n"), query, sql_strerror(mdb));
256 Dmsg0(50, "db_sql_query failed\n");
259 Dmsg0(50, "db_sql_query succeeded. checking handler\n");
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);
266 Dmsg0(50, "db_sql_query sql_store_result suceeded\n");
267 while ((row = sql_fetch_row(mdb)) != NULL) {
269 Dmsg0(50, "db_sql_query sql_fetch_row worked\n");
270 if (result_handler(ctx, num_fields, row))
274 sql_free_result(mdb);
279 Dmsg0(50, "db_sql_query finished\n");
286 list_dashes(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx)
291 sql_field_seek(mdb, 0);
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++)
303 * If full_list is set, we list vertically, otherwise, we
304 * list on one line horizontally.
307 list_result(B_DB *mdb, DB_LIST_HANDLER *send, void *ctx, e_list_type type)
311 unsigned int i, col_len, max_len = 0;
312 char buf[2000], ewc[30];
314 if (mdb->result == NULL) {
315 send(ctx, _("No results to list.\n"));
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) {
328 if (IS_NUM(field->type) && field->max_length > 0) { /* fixup for commas */
329 field->max_length += (field->max_length - 1) / 3;
331 if (col_len < field->max_length) {
332 col_len = field->max_length;
334 if (col_len < 4 && !IS_NOT_NULL(field->flags)) {
335 col_len = 4; /* 4 = length of the word "NULL" */
337 field->max_length = col_len; /* reset column info */
341 if (type == VERT_LIST) {
345 list_dashes(mdb, 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);
354 list_dashes(mdb, send, ctx);
356 while ((row = sql_fetch_row(mdb)) != NULL) {
357 sql_field_seek(mdb, 0);
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));
367 bsnprintf(buf, sizeof(buf), " %-*s |", (int)field->max_length, row[i]);
373 list_dashes(mdb, send, ctx);
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));
388 bsnprintf(buf, sizeof(buf), " %*s: %s\n", max_len, field->name, row[i]);
397 POSTGRESQL_ROW my_postgresql_fetch_row(B_DB *mdb) {
400 POSTGRESQL_ROW row = NULL; // by default, return NULL
402 Dmsg0(50, "my_postgresql_fetch_row start\n");
403 ASSERT(mdb->row != NULL);
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]);
414 // increment the row number for the next call
419 Dmsg2(50, "my_postgresql_fetch_row row number '%d' is NOT acceptable (0..%d)\n", mdb->row_number, mdb->num_rows);
422 Dmsg1(50, "my_postgresql_fetch_row finishes returning %x\n", row);
427 POSTGRESQL_FIELD * my_postgresql_fetch_field(B_DB *mdb) {
428 mdb->field.name = PQfname (mdb->result, mdb->field_number);
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);
433 // I am not sure this returns what we can use
434 mdb->field.type = PQftype (mdb->result, mdb->field_number);
436 mdb->field.flags = PQgetisnull(mdb->result, mdb->row_number, mdb->field_number);
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;
447 void my_postgresql_field_seek(B_DB *mdb, int field) {
448 mdb->field_number = field;
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.
455 mdb->row_number = -1;
456 mdb->field_number = -1;
460 Dmsg0(50, "my_postgresql_query freeing space\n");
466 Dmsg1(50, "doing PQexec with '%s'\n", query);
467 mdb->result = PQexec(mdb->db, query);
468 if (PQresultStatus(mdb->result) == PGRES_TUPLES_OK) {
470 mdb->num_rows = PQntuples(mdb->result);
471 // how many fields in the set?
472 mdb->num_fields = PQnfields(mdb->result);
474 // point at the first row for the fetch row function
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);
484 Dmsg0(50, "my_postgresql_query finishing\n");
489 void my_postgresql_free_result (B_DB *mdb) {
490 PQclear(mdb->result);
496 #endif /* HAVE_POSTGRESQL */