Code

a30f548db2c6661242970d5db6c639b93aa480c8
[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 #include "utils/dbi.h"
29 #include "utils/error.h"
31 #include <assert.h>
33 #include <dbi/dbi.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
40 /*
41  * private data types
42  */
44 typedef struct {
45         char *key;
46         char *value;
47 } sdb_dbi_option_t;
49 struct sdb_dbi_options {
50         sdb_dbi_option_t *options;
51         size_t options_num;
52 };
54 struct sdb_dbi_client {
55         char *driver;
56         char *database;
58         dbi_conn conn;
60         sdb_dbi_options_t *options;
61 };
63 /*
64  * private helper functions
65  */
67 static const char *
68 sdb_dbi_strerror(dbi_conn conn)
69 {
70         const char *errmsg = NULL;
71         dbi_conn_error(conn, &errmsg);
72         return errmsg;
73 } /* sdb_dbi_strerror */
75 static int
76 sdb_dbi_get_field(dbi_result res, unsigned int i,
77                 int type, sdb_data_t *data)
78 {
79         switch (type) {
80                 case SDB_TYPE_INTEGER:
81                         data->data.integer = dbi_result_get_longlong_idx(res, i);
82                         break;
83                 case SDB_TYPE_DECIMAL:
84                         data->data.decimal = dbi_result_get_double_idx(res, i);
85                         break;
86                 case SDB_TYPE_STRING:
87                         data->data.string = dbi_result_get_string_copy_idx(res, i);
88                         break;
89                 case SDB_TYPE_DATETIME:
90                         {
91                                 /* libdbi does not provide any higher resolutions than that */
92                                 time_t datetime = dbi_result_get_datetime_idx(res, i);
93                                 data->data.datetime = SECS_TO_SDB_TIME(datetime);
94                         }
95                         break;
96                 case SDB_TYPE_BINARY:
97                         {
98                                 size_t length = dbi_result_get_field_length_idx(res, i);
99                                 unsigned char *datum = dbi_result_get_binary_copy_idx(res, i);
100                                 data->data.binary.length = length;
101                                 data->data.binary.datum = datum;
102                         }
103                         break;
104                 default:
105                         sdb_log(SDB_LOG_ERR, "dbi: Unexpected type %i while "
106                                         "parsing query result.", type);
107                         return -1;
108         }
110         data->type = type;
111         return 0;
112 } /* sdb_dbi_get_field */
114 static int
115 sdb_dbi_get_data(sdb_dbi_client_t *client, dbi_result res,
116                 unsigned int num_fields, sdb_dbi_data_cb callback,
117                 sdb_object_t *user_data)
119         sdb_data_t data[num_fields];
120         int types[num_fields];
121         unsigned int i;
123         unsigned long long num_rows;
124         unsigned long long success = 0, n;
126         assert(client && res && callback);
127         assert(num_fields > 0);
129         for (i = 0; i < num_fields; ++i) {
130                 types[i] = dbi_result_get_field_type_idx(res, i + 1);
131                 if (types[i] == DBI_TYPE_ERROR) {
132                         sdb_log(SDB_LOG_ERR, "dbi: failed to fetch data: %s",
133                                         sdb_dbi_strerror(client->conn));
134                         return -1;
135                 }
136                 types[i] = DBI_TYPE_TO_SC(types[i]);
137         }
139         num_rows = dbi_result_get_numrows(res);
140         if (num_rows < 1)
141                 return -1;
143         for (n = 0; n < num_rows; ++n) {
144                 int status;
146                 if (! dbi_result_seek_row(res, n + 1)) {
147                         sdb_log(SDB_LOG_ERR, "dbi: Failed to retrieve row %llu: %s",
148                                         n, sdb_dbi_strerror(client->conn));
149                         continue;
150                 }
152                 for (i = 0; i < num_fields; ++i)
153                         if (sdb_dbi_get_field(res, (unsigned int)(i + 1),
154                                                 types[i], &data[i]))
155                                 continue;
157                 status = callback(client, num_fields, data, user_data);
158                 for (i = 0; i < num_fields; ++i)
159                         sdb_data_free_datum(&data[i]);
161                 if (status)
162                         continue;
164                 ++success;
165         }
167         if (! success)
168                 return -1;
169         return 0;
170 } /* sdb_dbi_get_data */
172 /*
173  * public API
174  */
176 sdb_dbi_options_t *
177 sdb_dbi_options_create(void)
179         sdb_dbi_options_t *options;
181         options = malloc(sizeof(*options));
182         if (! options)
183                 return NULL;
185         options->options = NULL;
186         options->options_num = 0;
187         return options;
188 } /* sdb_dbi_options_create */
190 int
191 sdb_dbi_options_add(sdb_dbi_options_t *options,
192                 const char *key, const char *value)
194         sdb_dbi_option_t *new;
196         if ((! options) || (! key) || (! value))
197                 return -1;
199         new = realloc(options->options,
200                         (options->options_num + 1) * sizeof(*options->options));
201         if (! new)
202                 return -1;
204         options->options = new;
205         new = options->options + options->options_num;
207         new->key = strdup(key);
208         new->value = strdup(value);
210         if ((! new->key) || (! new->value)) {
211                 if (new->key)
212                         free(new->key);
213                 if (new->value)
214                         free(new->value);
215                 return -1;
216         }
218         ++options->options_num;
219         return 0;
220 } /* sdb_dbi_options_add */
222 void
223 sdb_dbi_options_destroy(sdb_dbi_options_t *options)
225         size_t i;
227         if (! options)
228                 return;
230         for (i = 0; i < options->options_num; ++i) {
231                 sdb_dbi_option_t *opt = options->options + i;
233                 if (opt->key)
234                         free(opt->key);
235                 if (opt->value)
236                         free(opt->value);
237         }
239         if (options->options)
240                 free(options->options);
241         options->options = NULL;
242         options->options_num = 0;
243         free(options);
244 } /* sdb_dbi_options_destroy */
246 sdb_dbi_client_t *
247 sdb_dbi_client_create(const char *driver, const char *database)
249         sdb_dbi_client_t *client;
251         if ((! driver) || (! database))
252                 return NULL;
254         client = malloc(sizeof(*client));
255         if (! client)
256                 return NULL;
257         memset(client, 0, sizeof(*client));
259         client->conn = NULL;
260         client->options = NULL;
262         client->driver = strdup(driver);
263         client->database = strdup(database);
264         if ((! client->driver) || (! client->database)) {
265                 sdb_dbi_client_destroy(client);
266                 return NULL;
267         }
268         return client;
269 } /* sdb_dbi_client_create */
271 int
272 sdb_dbi_client_set_options(sdb_dbi_client_t *client,
273                 sdb_dbi_options_t *options)
275         if (! client)
276                 return -1;
278         if (client->options)
279                 sdb_dbi_options_destroy(client->options);
280         client->options = options;
281         return 0;
282 } /* sdb_dbi_client_set_options */
284 int
285 sdb_dbi_client_connect(sdb_dbi_client_t *client)
287         dbi_driver driver;
288         size_t i;
290         if ((! client) || (! client->driver) || (! client->database))
291                 return -1;
293         if (client->conn) {
294                 dbi_conn_close(client->conn);
295                 client->conn = NULL;
296         }
298         driver = dbi_driver_open(client->driver);
299         if (! driver) {
300                 sdb_error_set("dbi: failed to open DBI driver '%s'; "
301                                 "possibly it's not installed.\n",
302                                 client->driver);
304                 sdb_error_append("dbi: known drivers:\n");
305                 for (driver = dbi_driver_list(NULL); driver;
306                                 driver = dbi_driver_list(driver)) {
307                         sdb_error_append("\t- %s\n", dbi_driver_get_name(driver));
308                 }
309                 sdb_error_chomp();
310                 sdb_error_log(SDB_LOG_ERR);
311                 return -1;
312         }
314         client->conn = dbi_conn_open(driver);
315         if (! client->conn) {
316                 sdb_log(SDB_LOG_ERR, "dbi: failed to open connection "
317                                 "object.");
318                 return -1;
319         }
321         if (client->options) {
322                 for (i = 0; i < client->options->options_num; ++i) {
323                         const char *opt;
325                         if (! dbi_conn_set_option(client->conn,
326                                                 client->options->options[i].key,
327                                                 client->options->options[i].value))
328                                 continue;
329                         /* else: error */
331                         sdb_error_set("dbi: failed to set option '%s': %s\n",
332                                         client->options->options[i].key,
333                                         sdb_dbi_strerror(client->conn));
335                         sdb_error_append("dbi: known driver options:\n");
336                         for (opt = dbi_conn_get_option_list(client->conn, NULL); opt;
337                                         opt = dbi_conn_get_option_list(client->conn, opt))
338                                 sdb_error_append("\t- %s\n", opt);
339                         sdb_error_chomp();
340                         sdb_error_log(SDB_LOG_ERR);
342                         dbi_conn_close(client->conn);
343                         client->conn = NULL;
344                         return -1;
345                 }
346         }
348         if (dbi_conn_set_option(client->conn, "dbname", client->database)) {
349                 sdb_log(SDB_LOG_ERR, "dbi: failed to set option 'dbname': %s",
350                                 sdb_dbi_strerror(client->conn));
351                 dbi_conn_close(client->conn);
352                 client->conn = NULL;
353                 return -1;
354         }
356         if (dbi_conn_connect(client->conn) < 0) {
357                 sdb_log(SDB_LOG_ERR, "dbi: failed to connect to database '%s': %s",
358                                 client->database, sdb_dbi_strerror(client->conn));
359                 dbi_conn_close(client->conn);
360                 client->conn = NULL;
361                 return -1;
362         }
363         return 0;
364 } /* sdb_dbi_client_connect */
366 int
367 sdb_dbi_client_check_conn(sdb_dbi_client_t *client)
369         if (! client)
370                 return -1;
372         if (! client->conn)
373                 return sdb_dbi_client_connect(client);
375         if (dbi_conn_ping(client->conn))
376                 return 0;
377         return sdb_dbi_client_connect(client);
378 } /* sdb_dbi_client_check_conn */
380 int
381 sdb_dbi_exec_query(sdb_dbi_client_t *client, const char *query,
382                 sdb_dbi_data_cb callback, sdb_object_t *user_data, int n, ...)
384         dbi_result res;
385         unsigned int num_fields;
387         int status;
389         if ((! client) || (! client->conn) || (! query))
390                 return -1;
392         res = dbi_conn_query(client->conn, query);
393         if (! res) {
394                 sdb_log(SDB_LOG_ERR, "dbi: failed to execute query '%s': %s",
395                                 query, sdb_dbi_strerror(client->conn));
396                 return -1;
397         }
399         if (dbi_result_get_numrows(res) == DBI_ROW_ERROR) {
400                 sdb_log(SDB_LOG_ERR, "dbi: failed to fetch rows for query "
401                                 "'%s': %s", query, sdb_dbi_strerror(client->conn));
402                 dbi_result_free(res);
403                 return -1;
404         }
406         if (dbi_result_get_numrows(res) < 1) { /* no data */
407                 dbi_result_free(res);
408                 return 0;
409         }
411         num_fields = dbi_result_get_numfields(res);
413         if (n >= 0) {
414                 va_list types;
415                 int i;
417                 if (n != (int)num_fields) {
418                         sdb_log(SDB_LOG_ERR, "dbi: number of returned fields (%i) "
419                                         "does not match the number of requested fields (%i) "
420                                         "for query '%s'.", num_fields, n, query);
421                         dbi_result_free(res);
422                         return -1;
423                 }
425                 va_start(types, n);
426                 status = 0;
428                 for (i = 0; i < n; ++i) {
429                         unsigned short field_type = dbi_result_get_field_type_idx(res,
430                                         (unsigned int)(i + 1));
432                         unsigned int type = va_arg(types, unsigned int);
434                         field_type = DBI_TYPE_TO_SC(field_type);
436                         /* column count starts at 1 */
437                         if ((unsigned int)field_type != type) {
438                                 sdb_log(SDB_LOG_ERR, "dbi: type of column '%s' (%u) "
439                                                 "does not match requested type (%u).",
440                                                 dbi_result_get_field_name(res, (unsigned int)i + 1),
441                                                 field_type, type);
442                                 status = -1;
443                         }
444                 }
446                 va_end(types);
448                 if (status) {
449                         dbi_result_free(res);
450                         return status;
451                 }
452         }
454         if (num_fields < 1) { /* no data */
455                 dbi_result_free(res);
456                 return 0;
457         }
459         status = sdb_dbi_get_data(client, res, num_fields, callback, user_data);
461         dbi_result_free(res);
462         return status;
463 } /* sdb_dbi_exec_query */
465 void
466 sdb_dbi_client_destroy(sdb_dbi_client_t *client)
468         if (! client)
469                 return;
471         if (client->driver)
472                 free(client->driver);
473         client->driver = NULL;
475         if (client->database)
476                 free(client->database);
477         client->database = NULL;
479         if (client->conn)
480                 dbi_conn_close(client->conn);
481         client->conn = NULL;
483         if (client->options)
484                 sdb_dbi_options_destroy(client->options);
485         client->options = NULL;
487         free(client);
488 } /* sdb_dbi_client_destroy */
490 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */