Code

dbi utils: Use the new _r interface.
[sysdb.git] / src / utils / dbi.c
1 /*
2  * SysDB - src/utils/dbi.c
3  * Copyright (C) 2012 Sebastian 'tokkee' Harl <sh@tokkee.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
28 #if HAVE_CONFIG_H
29 #       include "config.h"
30 #endif /* HAVE_CONFIG_H */
32 #include "utils/dbi.h"
33 #include "utils/error.h"
35 #include <assert.h>
37 #include <dbi/dbi.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
44 /*
45  * private data types
46  */
48 typedef struct {
49         char *key;
50         char *value;
51 } sdb_dbi_option_t;
53 struct sdb_dbi_options {
54         sdb_dbi_option_t *options;
55         size_t options_num;
56 };
58 struct sdb_dbi_client {
59         char *driver;
60         char *database;
62         dbi_conn conn;
63         dbi_inst inst;
65         sdb_dbi_options_t *options;
66 };
68 /*
69  * private helper functions
70  */
72 static const char *
73 sdb_dbi_strerror(dbi_conn conn)
74 {
75         const char *errmsg = NULL;
76         dbi_conn_error(conn, &errmsg);
77         return errmsg;
78 } /* sdb_dbi_strerror */
80 static int
81 sdb_dbi_get_field(dbi_result res, unsigned int i,
82                 int type, sdb_data_t *data)
83 {
84         switch (type) {
85                 case SDB_TYPE_INTEGER:
86                         data->data.integer = dbi_result_get_longlong_idx(res, i);
87                         break;
88                 case SDB_TYPE_DECIMAL:
89                         data->data.decimal = dbi_result_get_double_idx(res, i);
90                         break;
91                 case SDB_TYPE_STRING:
92                         data->data.string = dbi_result_get_string_copy_idx(res, i);
93                         break;
94                 case SDB_TYPE_DATETIME:
95                         {
96                                 /* libdbi does not provide any higher resolutions than that */
97                                 time_t datetime = dbi_result_get_datetime_idx(res, i);
98                                 data->data.datetime = SECS_TO_SDB_TIME(datetime);
99                         }
100                         break;
101                 case SDB_TYPE_BINARY:
102                         {
103                                 size_t length = dbi_result_get_field_length_idx(res, i);
104                                 unsigned char *datum = dbi_result_get_binary_copy_idx(res, i);
105                                 data->data.binary.length = length;
106                                 data->data.binary.datum = datum;
107                         }
108                         break;
109                 default:
110                         sdb_log(SDB_LOG_ERR, "dbi: Unexpected type %i while "
111                                         "parsing query result.", type);
112                         return -1;
113         }
115         data->type = type;
116         return 0;
117 } /* sdb_dbi_get_field */
119 static int
120 sdb_dbi_get_data(sdb_dbi_client_t *client, dbi_result res,
121                 unsigned int num_fields, sdb_dbi_data_cb callback,
122                 sdb_object_t *user_data)
124         sdb_data_t data[num_fields];
125         int types[num_fields];
126         unsigned int i;
128         unsigned long long num_rows;
129         unsigned long long success = 0, n;
131         assert(client && res && callback);
132         assert(num_fields > 0);
134         for (i = 0; i < num_fields; ++i) {
135                 types[i] = dbi_result_get_field_type_idx(res, i + 1);
136                 if (types[i] == DBI_TYPE_ERROR) {
137                         sdb_log(SDB_LOG_ERR, "dbi: failed to fetch data: %s",
138                                         sdb_dbi_strerror(client->conn));
139                         return -1;
140                 }
141                 types[i] = DBI_TYPE_TO_SC(types[i]);
142         }
144         num_rows = dbi_result_get_numrows(res);
145         if (num_rows < 1)
146                 return -1;
148         for (n = 0; n < num_rows; ++n) {
149                 int status;
151                 if (! dbi_result_seek_row(res, n + 1)) {
152                         sdb_log(SDB_LOG_ERR, "dbi: Failed to retrieve row %llu: %s",
153                                         n, sdb_dbi_strerror(client->conn));
154                         continue;
155                 }
157                 for (i = 0; i < num_fields; ++i)
158                         if (sdb_dbi_get_field(res, (unsigned int)(i + 1),
159                                                 types[i], &data[i]))
160                                 continue;
162                 status = callback(client, num_fields, data, user_data);
163                 for (i = 0; i < num_fields; ++i)
164                         sdb_data_free_datum(&data[i]);
166                 if (status)
167                         continue;
169                 ++success;
170         }
172         if (! success)
173                 return -1;
174         return 0;
175 } /* sdb_dbi_get_data */
177 /*
178  * public API
179  */
181 sdb_dbi_options_t *
182 sdb_dbi_options_create(void)
184         sdb_dbi_options_t *options;
186         options = malloc(sizeof(*options));
187         if (! options)
188                 return NULL;
190         options->options = NULL;
191         options->options_num = 0;
192         return options;
193 } /* sdb_dbi_options_create */
195 int
196 sdb_dbi_options_add(sdb_dbi_options_t *options,
197                 const char *key, const char *value)
199         sdb_dbi_option_t *new;
201         if ((! options) || (! key) || (! value))
202                 return -1;
204         new = realloc(options->options,
205                         (options->options_num + 1) * sizeof(*options->options));
206         if (! new)
207                 return -1;
209         options->options = new;
210         new = options->options + options->options_num;
212         new->key = strdup(key);
213         new->value = strdup(value);
215         if ((! new->key) || (! new->value)) {
216                 if (new->key)
217                         free(new->key);
218                 if (new->value)
219                         free(new->value);
220                 return -1;
221         }
223         ++options->options_num;
224         return 0;
225 } /* sdb_dbi_options_add */
227 void
228 sdb_dbi_options_destroy(sdb_dbi_options_t *options)
230         size_t i;
232         if (! options)
233                 return;
235         for (i = 0; i < options->options_num; ++i) {
236                 sdb_dbi_option_t *opt = options->options + i;
238                 if (opt->key)
239                         free(opt->key);
240                 if (opt->value)
241                         free(opt->value);
242         }
244         if (options->options)
245                 free(options->options);
246         options->options = NULL;
247         options->options_num = 0;
248         free(options);
249 } /* sdb_dbi_options_destroy */
251 sdb_dbi_client_t *
252 sdb_dbi_client_create(const char *driver, const char *database)
254         sdb_dbi_client_t *client;
256         if ((! driver) || (! database))
257                 return NULL;
259         client = malloc(sizeof(*client));
260         if (! client)
261                 return NULL;
262         memset(client, 0, sizeof(*client));
264         client->conn = NULL;
265         client->options = NULL;
267         if (dbi_initialize_r(/* driverdir = */ NULL, &client->inst) < 0) {
268                 free(client);
269                 return NULL;
270         }
272         client->driver = strdup(driver);
273         client->database = strdup(database);
274         if ((! client->driver) || (! client->database)) {
275                 sdb_dbi_client_destroy(client);
276                 return NULL;
277         }
278         return client;
279 } /* sdb_dbi_client_create */
281 int
282 sdb_dbi_client_set_options(sdb_dbi_client_t *client,
283                 sdb_dbi_options_t *options)
285         if (! client)
286                 return -1;
288         if (client->options)
289                 sdb_dbi_options_destroy(client->options);
290         client->options = options;
291         return 0;
292 } /* sdb_dbi_client_set_options */
294 int
295 sdb_dbi_client_connect(sdb_dbi_client_t *client)
297         dbi_driver driver;
298         size_t i;
300         if ((! client) || (! client->driver) || (! client->database))
301                 return -1;
303         if (client->conn) {
304                 dbi_conn_close(client->conn);
305                 client->conn = NULL;
306         }
308         driver = dbi_driver_open_r(client->driver, client->inst);
309         if (! driver) {
310                 sdb_error_set("dbi: failed to open DBI driver '%s'; "
311                                 "possibly it's not installed.\n",
312                                 client->driver);
314                 sdb_error_append("dbi: known drivers:\n");
315                 for (driver = dbi_driver_list_r(NULL, client->inst); driver;
316                                 driver = dbi_driver_list_r(driver, client->inst)) {
317                         sdb_error_append("\t- %s\n", dbi_driver_get_name(driver));
318                 }
319                 sdb_error_chomp();
320                 sdb_error_log(SDB_LOG_ERR);
321                 return -1;
322         }
324         client->conn = dbi_conn_open(driver);
325         if (! client->conn) {
326                 sdb_log(SDB_LOG_ERR, "dbi: failed to open connection "
327                                 "object.");
328                 return -1;
329         }
331         if (client->options) {
332                 for (i = 0; i < client->options->options_num; ++i) {
333                         const char *opt;
335                         if (! dbi_conn_set_option(client->conn,
336                                                 client->options->options[i].key,
337                                                 client->options->options[i].value))
338                                 continue;
339                         /* else: error */
341                         sdb_error_set("dbi: failed to set option '%s': %s\n",
342                                         client->options->options[i].key,
343                                         sdb_dbi_strerror(client->conn));
345                         sdb_error_append("dbi: known driver options:\n");
346                         for (opt = dbi_conn_get_option_list(client->conn, NULL); opt;
347                                         opt = dbi_conn_get_option_list(client->conn, opt))
348                                 sdb_error_append("\t- %s\n", opt);
349                         sdb_error_chomp();
350                         sdb_error_log(SDB_LOG_ERR);
352                         dbi_conn_close(client->conn);
353                         client->conn = NULL;
354                         return -1;
355                 }
356         }
358         if (dbi_conn_set_option(client->conn, "dbname", client->database)) {
359                 sdb_log(SDB_LOG_ERR, "dbi: failed to set option 'dbname': %s",
360                                 sdb_dbi_strerror(client->conn));
361                 dbi_conn_close(client->conn);
362                 client->conn = NULL;
363                 return -1;
364         }
366         if (dbi_conn_connect(client->conn) < 0) {
367                 sdb_log(SDB_LOG_ERR, "dbi: failed to connect to database '%s': %s",
368                                 client->database, sdb_dbi_strerror(client->conn));
369                 dbi_conn_close(client->conn);
370                 client->conn = NULL;
371                 return -1;
372         }
373         return 0;
374 } /* sdb_dbi_client_connect */
376 int
377 sdb_dbi_client_check_conn(sdb_dbi_client_t *client)
379         if (! client)
380                 return -1;
382         if (! client->conn)
383                 return sdb_dbi_client_connect(client);
385         if (dbi_conn_ping(client->conn))
386                 return 0;
387         return sdb_dbi_client_connect(client);
388 } /* sdb_dbi_client_check_conn */
390 int
391 sdb_dbi_exec_query(sdb_dbi_client_t *client, const char *query,
392                 sdb_dbi_data_cb callback, sdb_object_t *user_data, int n, ...)
394         dbi_result res;
395         unsigned int num_fields;
397         int status;
399         if ((! client) || (! client->conn) || (! query))
400                 return -1;
402         res = dbi_conn_query(client->conn, query);
403         if (! res) {
404                 sdb_log(SDB_LOG_ERR, "dbi: failed to execute query '%s': %s",
405                                 query, sdb_dbi_strerror(client->conn));
406                 return -1;
407         }
409         if (dbi_result_get_numrows(res) == DBI_ROW_ERROR) {
410                 sdb_log(SDB_LOG_ERR, "dbi: failed to fetch rows for query "
411                                 "'%s': %s", query, sdb_dbi_strerror(client->conn));
412                 dbi_result_free(res);
413                 return -1;
414         }
416         if (dbi_result_get_numrows(res) < 1) { /* no data */
417                 dbi_result_free(res);
418                 return 0;
419         }
421         num_fields = dbi_result_get_numfields(res);
423         if (n >= 0) {
424                 va_list types;
425                 int i;
427                 if (n != (int)num_fields) {
428                         sdb_log(SDB_LOG_ERR, "dbi: number of returned fields (%i) "
429                                         "does not match the number of requested fields (%i) "
430                                         "for query '%s'.", num_fields, n, query);
431                         dbi_result_free(res);
432                         return -1;
433                 }
435                 va_start(types, n);
436                 status = 0;
438                 for (i = 0; i < n; ++i) {
439                         unsigned short field_type = dbi_result_get_field_type_idx(res,
440                                         (unsigned int)(i + 1));
442                         unsigned int type = va_arg(types, unsigned int);
444                         field_type = DBI_TYPE_TO_SC(field_type);
446                         /* column count starts at 1 */
447                         if ((unsigned int)field_type != type) {
448                                 sdb_log(SDB_LOG_ERR, "dbi: type of column '%s' (%u) "
449                                                 "does not match requested type (%u).",
450                                                 dbi_result_get_field_name(res, (unsigned int)i + 1),
451                                                 field_type, type);
452                                 status = -1;
453                         }
454                 }
456                 va_end(types);
458                 if (status) {
459                         dbi_result_free(res);
460                         return status;
461                 }
462         }
464         if (num_fields < 1) { /* no data */
465                 dbi_result_free(res);
466                 return 0;
467         }
469         status = sdb_dbi_get_data(client, res, num_fields, callback, user_data);
471         dbi_result_free(res);
472         return status;
473 } /* sdb_dbi_exec_query */
475 void
476 sdb_dbi_client_destroy(sdb_dbi_client_t *client)
478         if (! client)
479                 return;
481         if (client->driver)
482                 free(client->driver);
483         client->driver = NULL;
485         if (client->database)
486                 free(client->database);
487         client->database = NULL;
489         if (client->conn)
490                 dbi_conn_close(client->conn);
491         client->conn = NULL;
493         dbi_shutdown_r(client->inst);
495         if (client->options)
496                 sdb_dbi_options_destroy(client->options);
497         client->options = NULL;
499         free(client);
500 } /* sdb_dbi_client_destroy */
502 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */