Code

frontend: Remove stale UNIX sockets before trying to bind().
[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_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                                 const unsigned char *datum = dbi_result_get_binary_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                 if (! dbi_result_seek_row(res, n + 1)) {
145                         sdb_log(SDB_LOG_ERR, "dbi: Failed to retrieve row %llu: %s",
146                                         n, sdb_dbi_strerror(client->conn));
147                         continue;
148                 }
150                 for (i = 0; i < num_fields; ++i)
151                         if (sdb_dbi_get_field(res, (unsigned int)(i + 1),
152                                                 types[i], &data[i]))
153                                 continue;
155                 if (callback(client, num_fields, data, user_data))
156                         continue;
158                 ++success;
159         }
161         if (! success)
162                 return -1;
163         return 0;
164 } /* sdb_dbi_get_data */
166 /*
167  * public API
168  */
170 sdb_dbi_options_t *
171 sdb_dbi_options_create(void)
173         sdb_dbi_options_t *options;
175         options = malloc(sizeof(options));
176         if (! options)
177                 return NULL;
179         options->options = NULL;
180         options->options_num = 0;
181         return options;
182 } /* sdb_dbi_options_create */
184 int
185 sdb_dbi_options_add(sdb_dbi_options_t *options,
186                 const char *key, const char *value)
188         sdb_dbi_option_t *new;
190         if ((! options) || (! key) || (! value))
191                 return -1;
193         new = realloc(options->options,
194                         (options->options_num + 1) * sizeof(*options->options));
195         if (! new)
196                 return -1;
198         options->options = new;
199         new = options->options + options->options_num;
201         new->key = strdup(key);
202         new->value = strdup(value);
204         if ((! new->key) || (! new->value)) {
205                 if (new->key)
206                         free(new->key);
207                 if (new->value)
208                         free(new->value);
209                 return -1;
210         }
212         ++options->options_num;
213         return 0;
214 } /* sdb_dbi_options_add */
216 void
217 sdb_dbi_options_destroy(sdb_dbi_options_t *options)
219         size_t i;
221         if (! options)
222                 return;
224         for (i = 0; i < options->options_num; ++i) {
225                 sdb_dbi_option_t *opt = options->options + i;
227                 if (opt->key)
228                         free(opt->key);
229                 if (opt->value)
230                         free(opt->value);
231         }
233         if (options->options)
234                 free(options->options);
235         options->options = NULL;
236         options->options_num = 0;
237         free(options);
238 } /* sdb_dbi_options_destroy */
240 sdb_dbi_client_t *
241 sdb_dbi_client_create(const char *driver, const char *database)
243         sdb_dbi_client_t *client;
245         if ((! driver) || (! database))
246                 return NULL;
248         client = malloc(sizeof(*client));
249         if (! client)
250                 return NULL;
251         memset(client, 0, sizeof(*client));
253         client->conn = NULL;
254         client->options = NULL;
256         client->driver = strdup(driver);
257         client->database = strdup(database);
258         if ((! client->driver) || (! client->database)) {
259                 sdb_dbi_client_destroy(client);
260                 return NULL;
261         }
262         return client;
263 } /* sdb_dbi_client_create */
265 int
266 sdb_dbi_client_set_options(sdb_dbi_client_t *client,
267                 sdb_dbi_options_t *options)
269         if (! client)
270                 return -1;
272         if (client->options)
273                 sdb_dbi_options_destroy(client->options);
274         client->options = options;
275         return 0;
276 } /* sdb_dbi_client_set_options */
278 int
279 sdb_dbi_client_connect(sdb_dbi_client_t *client)
281         dbi_driver driver;
282         size_t i;
284         if ((! client) || (! client->driver) || (! client->database))
285                 return -1;
287         if (client->conn)
288                 dbi_conn_close(client->conn);
290         driver = dbi_driver_open(client->driver);
291         if (! driver) {
292                 sdb_error_set("dbi: failed to open DBI driver '%s'; "
293                                 "possibly it's not installed.\n",
294                                 client->driver);
296                 sdb_error_append("dbi: known drivers:\n");
297                 for (driver = dbi_driver_list(NULL); driver;
298                                 driver = dbi_driver_list(driver)) {
299                         sdb_error_append("\t- %s\n", dbi_driver_get_name(driver));
300                 }
301                 sdb_error_chomp();
302                 sdb_error_log(SDB_LOG_ERR);
303                 return -1;
304         }
306         client->conn = dbi_conn_open(driver);
307         if (! client->conn) {
308                 sdb_log(SDB_LOG_ERR, "dbi: failed to open connection "
309                                 "object.");
310                 return -1;
311         }
313         if (client->options) {
314                 for (i = 0; i < client->options->options_num; ++i) {
315                         const char *opt;
317                         if (! dbi_conn_set_option(client->conn,
318                                                 client->options->options[i].key,
319                                                 client->options->options[i].value))
320                                 continue;
321                         /* else: error */
323                         sdb_error_set("dbi: failed to set option '%s': %s\n",
324                                         client->options->options[i].key,
325                                         sdb_dbi_strerror(client->conn));
327                         sdb_error_append("dbi: known driver options:\n");
328                         for (opt = dbi_conn_get_option_list(client->conn, NULL); opt;
329                                         opt = dbi_conn_get_option_list(client->conn, opt))
330                                 sdb_error_append("\t- %s\n", opt);
331                         sdb_error_chomp();
332                         sdb_error_log(SDB_LOG_ERR);
334                         dbi_conn_close(client->conn);
335                         return -1;
336                 }
337         }
339         if (dbi_conn_set_option(client->conn, "dbname", client->database)) {
340                 sdb_log(SDB_LOG_ERR, "dbi: failed to set option 'dbname': %s",
341                                 sdb_dbi_strerror(client->conn));
342                 dbi_conn_close(client->conn);
343                 return -1;
344         }
346         if (dbi_conn_connect(client->conn) < 0) {
347                 sdb_log(SDB_LOG_ERR, "dbi: failed to connect to database '%s': %s",
348                                 client->database, sdb_dbi_strerror(client->conn));
349                 dbi_conn_close(client->conn);
350                 return -1;
351         }
352         return 0;
353 } /* sdb_dbi_client_connect */
355 int
356 sdb_dbi_client_check_conn(sdb_dbi_client_t *client)
358         if (! client)
359                 return -1;
361         if (! client->conn)
362                 return sdb_dbi_client_connect(client);
364         if (dbi_conn_ping(client->conn))
365                 return 0;
366         return sdb_dbi_client_connect(client);
367 } /* sdb_dbi_client_check_conn */
369 int
370 sdb_dbi_exec_query(sdb_dbi_client_t *client, const char *query,
371                 sdb_dbi_data_cb callback, sdb_object_t *user_data, int n, ...)
373         dbi_result res;
374         unsigned int num_fields;
376         int status;
378         if ((! client) || (! client->conn) || (! query))
379                 return -1;
381         res = dbi_conn_query(client->conn, query);
382         if (! res) {
383                 sdb_log(SDB_LOG_ERR, "dbi: failed to execute query '%s': %s",
384                                 query, sdb_dbi_strerror(client->conn));
385                 return -1;
386         }
388         if (dbi_result_get_numrows(res) == DBI_ROW_ERROR) {
389                 sdb_log(SDB_LOG_ERR, "dbi: failed to fetch rows for query "
390                                 "'%s': %s", query, sdb_dbi_strerror(client->conn));
391                 dbi_result_free(res);
392                 return -1;
393         }
395         if (dbi_result_get_numrows(res) < 1) { /* no data */
396                 dbi_result_free(res);
397                 return 0;
398         }
400         num_fields = dbi_result_get_numfields(res);
402         if (n >= 0) {
403                 va_list types;
404                 int i;
406                 if (n != (int)num_fields) {
407                         sdb_log(SDB_LOG_ERR, "dbi: number of returned fields (%i) "
408                                         "does not match the number of requested fields (%i) "
409                                         "for query '%s'.", num_fields, n, query);
410                         dbi_result_free(res);
411                         return -1;
412                 }
414                 va_start(types, n);
415                 status = 0;
417                 for (i = 0; i < n; ++i) {
418                         unsigned short field_type = dbi_result_get_field_type_idx(res,
419                                         (unsigned int)(i + 1));
421                         unsigned int type = va_arg(types, unsigned int);
423                         field_type = DBI_TYPE_TO_SC(field_type);
425                         /* column count starts at 1 */
426                         if ((unsigned int)field_type != type) {
427                                 sdb_log(SDB_LOG_ERR, "dbi: type of column '%s' (%u) "
428                                                 "does not match requested type (%u).",
429                                                 dbi_result_get_field_name(res, (unsigned int)i + 1),
430                                                 field_type, type);
431                                 status = -1;
432                         }
433                 }
435                 va_end(types);
437                 if (status) {
438                         dbi_result_free(res);
439                         return status;
440                 }
441         }
443         if (num_fields < 1) { /* no data */
444                 dbi_result_free(res);
445                 return 0;
446         }
448         status = sdb_dbi_get_data(client, res, num_fields, callback, user_data);
450         dbi_result_free(res);
451         return status;
452 } /* sdb_dbi_exec_query */
454 void
455 sdb_dbi_client_destroy(sdb_dbi_client_t *client)
457         if (! client)
458                 return;
460         if (client->driver)
461                 free(client->driver);
462         client->driver = NULL;
464         if (client->database)
465                 free(client->database);
466         client->database = NULL;
468         if (client->conn)
469                 dbi_conn_close(client->conn);
471         if (client->options)
472                 sdb_dbi_options_destroy(client->options);
473         client->options = NULL;
475         free(client);
476 } /* sdb_dbi_client_destroy */
478 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */