2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2011, Terry Wilson
6 * Terry Wilson <twilson@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
18 * Please follow coding guidelines
19 * http://svn.digium.com/view/asterisk/trunk/doc/CODING-GUIDELINES
24 * \brief SQLite 3 configuration engine
26 * \author\verbatim Terry Wilson <twilson@digium.com> \endverbatim
28 * This is a realtime configuration engine for the SQLite 3 Database
32 /*! \li \ref res_config_sqlite3.c uses the configuration file \ref res_config_sqlite3.conf
33 * \addtogroup configuration_file Configuration Files
37 * \page res_config_sqlite3.conf res_config_sqlite3.conf
38 * \verbinclude res_config_sqlite3.conf.sample
42 <depend>sqlite3</depend>
43 <support_level>core</support_level>
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
52 #include "asterisk/module.h"
53 #include "asterisk/config.h"
54 #include "asterisk/paths.h"
55 #include "asterisk/astobj2.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/app.h"
63 static struct ast_config *realtime_sqlite3_load(const char *database, const char *table, const char *configfile, struct ast_config *config, struct ast_flags flags, const char *suggested_include_file, const char *who_asked);
64 static struct ast_variable *realtime_sqlite3(const char *database, const char *table, va_list ap);
65 static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, va_list ap);
66 static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap);
67 static int realtime_sqlite3_update2(const char *database, const char *table, va_list ap);
68 static int realtime_sqlite3_store(const char *database, const char *table, va_list ap);
69 static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap);
70 static int realtime_sqlite3_require(const char *database, const char *table, va_list ap);
71 static int realtime_sqlite3_unload(const char *database, const char *table);
73 struct ast_config_engine sqlite3_config_engine = {
75 .load_func = realtime_sqlite3_load,
76 .realtime_func = realtime_sqlite3,
77 .realtime_multi_func = realtime_sqlite3_multi,
78 .update_func = realtime_sqlite3_update,
79 .update2_func = realtime_sqlite3_update2,
80 .store_func = realtime_sqlite3_store,
81 .destroy_func = realtime_sqlite3_destroy,
82 .require_func = realtime_sqlite3_require,
83 .unload_func = realtime_sqlite3_unload,
87 REALTIME_SQLITE3_REQ_WARN,
88 REALTIME_SQLITE3_REQ_CLOSE,
89 REALTIME_SQLITE3_REQ_CHAR,
92 struct realtime_sqlite3_db {
93 AST_DECLARE_STRING_FIELDS(
94 AST_STRING_FIELD(name);
95 AST_STRING_FIELD(filename);
100 unsigned int requirements:2;
101 unsigned int dirty:1;
102 unsigned int debug:1;
103 unsigned int exiting:1;
104 unsigned int wakeup:1;
108 struct ao2_container *databases;
111 AST_MUTEX_DEFINE_STATIC(config_lock);
113 /* We need a separate buffer for each field we might use concurrently */
114 AST_THREADSTORAGE(escape_table_buf);
115 AST_THREADSTORAGE(escape_column_buf);
116 AST_THREADSTORAGE(escape_value_buf);
118 static int realtime_sqlite3_execute_handle(struct realtime_sqlite3_db *db, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync);
119 void db_start_batch(struct realtime_sqlite3_db *db);
120 void db_stop_batch(struct realtime_sqlite3_db *db);
122 static inline const char *sqlite3_escape_string_helper(struct ast_threadstorage *ts, const char *param)
124 size_t maxlen = strlen(param) * 2 + sizeof("\"\"");
125 /* It doesn't appear that sqlite3_snprintf will do more than double the
126 * length of a string with %q as an option. %Q could double and possibly
127 * add two quotes, and convert NULL pointers to the word "NULL", but we
128 * don't allow those anyway. Just going to use %q for now. */
129 struct ast_str *buf = ast_str_thread_get(ts, maxlen);
130 char *tmp = ast_str_buffer(buf);
131 char q = ts == &escape_value_buf ? '\'' : '"';
134 *tmp++ = q; /* Initial quote */
135 while ((*tmp++ = *param++)) {
136 /* Did we just copy a quote? Then double it. */
137 if (*(tmp - 1) == q) {
141 *tmp = '\0'; /* Terminate past NULL from copy */
142 *(tmp - 1) = q; /* Replace original NULL with the quote */
145 return ast_str_buffer(buf);
148 static inline const char *sqlite3_escape_table(const char *param)
150 return sqlite3_escape_string_helper(&escape_table_buf, param);
153 static inline const char *sqlite3_escape_column(const char *param)
155 return sqlite3_escape_string_helper(&escape_column_buf, param);
158 /* Not inlining this function because it uses strdupa and I don't know if the compiler would be dumb */
159 static const char *sqlite3_escape_column_op(const char *param)
161 size_t maxlen = strlen(param) * 2 + sizeof("\"\" =");
162 struct ast_str *buf = ast_str_thread_get(&escape_column_buf, maxlen);
163 char *tmp = ast_str_buffer(buf);
168 while ((*tmp++ = *param++)) {
169 /* If we have seen a space, don't double quotes. XXX If we ever make the column/op field
170 * available to users via an API, we will definitely need to avoid allowing special
171 * characters like ';' in the data past the space as it will be unquoted data */
175 if (*(tmp - 1) == ' ') {
179 } else if (*(tmp - 1) == '"') {
184 strcpy(tmp - 1, "\" =");
189 return ast_str_buffer(buf);
192 static inline const char *sqlite3_escape_value(const char *param)
194 return sqlite3_escape_string_helper(&escape_value_buf, param);
197 static int db_hash_fn(const void *obj, const int flags)
199 const struct realtime_sqlite3_db *db = obj;
201 return ast_str_hash(flags & OBJ_KEY ? (const char *) obj : db->name);
204 static int db_cmp_fn(void *obj, void *arg, int flags) {
205 struct realtime_sqlite3_db *db = obj, *other = arg;
206 const char *name = arg;
208 return !strcasecmp(db->name, flags & OBJ_KEY ? name : other->name) ? CMP_MATCH | CMP_STOP : 0;
211 static void db_destructor(void *obj)
213 struct realtime_sqlite3_db *db = obj;
215 ast_debug(1, "Destroying db: %s\n", db->name);
216 ast_string_field_free_memory(db);
220 sqlite3_close(db->handle);
225 static struct realtime_sqlite3_db *find_database(const char *database)
227 return ao2_find(databases, database, OBJ_KEY);
230 static void unref_db(struct realtime_sqlite3_db **db)
236 static int stop_batch_cb(void *obj, void *arg, int flags)
238 struct realtime_sqlite3_db *db = obj;
244 static int mark_dirty_cb(void *obj, void *arg, int flags)
246 struct realtime_sqlite3_db *db = obj;
251 static void mark_all_databases_dirty(void)
253 ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA, mark_dirty_cb, NULL);
256 static int is_dirty_cb(void *obj, void *arg, int flags)
258 struct realtime_sqlite3_db *db = obj;
266 static void unlink_dirty_databases(void)
268 ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, is_dirty_cb, NULL);
271 static int str_to_requirements(const char *data)
273 if (!strcasecmp(data, "createclose")) {
274 return REALTIME_SQLITE3_REQ_CLOSE;
275 } else if (!strcasecmp(data, "createchar")) {
276 return REALTIME_SQLITE3_REQ_CHAR;
279 return REALTIME_SQLITE3_REQ_WARN;
282 /*! \note Since this is called while a query is executing, we should already hold the db lock */
283 static void trace_cb(void *arg, const char *sql)
285 struct realtime_sqlite3_db *db = arg;
286 ast_debug(3, "DB: %s SQL: %s\n", db->name, sql);
289 /*! \brief Wrap commands in transactions increased write performance */
290 static void *db_sync_thread(void *data)
292 struct realtime_sqlite3_db *db = data;
294 realtime_sqlite3_execute_handle(db, "BEGIN TRANSACTION", NULL, NULL, 0);
297 ast_cond_wait(&db->cond, ao2_object_get_lockaddr(db));
300 if (realtime_sqlite3_execute_handle(db, "COMMIT", NULL, NULL, 0) < 0) {
301 realtime_sqlite3_execute_handle(db, "ROLLBACK", NULL, NULL, 0);
307 realtime_sqlite3_execute_handle(db, "BEGIN TRANSACTION", NULL, NULL, 0);
309 usleep(1000 * db->batch);
318 /*! \brief Open a database and appropriately set debugging on the db handle */
319 static int db_open(struct realtime_sqlite3_db *db)
322 if (sqlite3_open(db->filename, &db->handle) != SQLITE_OK) {
323 ast_log(LOG_WARNING, "Could not open %s: %s\n", db->filename, sqlite3_errmsg(db->handle));
329 sqlite3_trace(db->handle, trace_cb, db);
331 sqlite3_trace(db->handle, NULL, NULL);
339 static void db_sync(struct realtime_sqlite3_db *db)
342 ast_cond_signal(&db->cond);
345 void db_start_batch(struct realtime_sqlite3_db *db)
348 ast_cond_init(&db->cond, NULL);
350 ast_pthread_create_background(&db->syncthread, NULL, db_sync_thread, db);
354 void db_stop_batch(struct realtime_sqlite3_db *db)
359 pthread_join(db->syncthread, NULL);
363 /*! \brief Create a db object based on a config category
364 * \note Opening the db handle and linking to databases must be handled outside of this function
366 static struct realtime_sqlite3_db *new_realtime_sqlite3_db(struct ast_config *config, const char *cat)
368 struct ast_variable *var;
369 struct realtime_sqlite3_db *db;
371 if (!(db = ao2_alloc(sizeof(*db), db_destructor))) {
375 if (ast_string_field_init(db, 64)) {
381 db->requirements = REALTIME_SQLITE3_REQ_WARN;
383 ast_string_field_set(db, name, cat);
385 for (var = ast_variable_browse(config, cat); var; var = var->next) {
386 if (!strcasecmp(var->name, "dbfile")) {
387 ast_string_field_set(db, filename, var->value);
388 } else if (!strcasecmp(var->name, "requirements")) {
389 db->requirements = str_to_requirements(var->value);
390 } else if (!strcasecmp(var->name, "batch")) {
391 ast_app_parse_timelen(var->value, (int *) &db->batch, TIMELEN_MILLISECONDS);
392 } else if (!strcasecmp(var->name, "debug")) {
393 db->debug = ast_true(var->value);
397 if (ast_strlen_zero(db->filename)) {
398 ast_log(LOG_WARNING, "Must specify dbfile in res_config_sqlite3.conf\n");
406 /*! \brief Update an existing db object based on config data
407 * \param db The database object to update
408 * \param config The configuration data with which to update the db
409 * \param cat The config category (which becomes db->name)
411 static int update_realtime_sqlite3_db(struct realtime_sqlite3_db *db, struct ast_config *config, const char *cat)
413 struct realtime_sqlite3_db *new;
415 if (!(new = new_realtime_sqlite3_db(config, cat))) {
419 /* Copy fields that don't need anything special done on change */
420 db->requirements = new->requirements;
422 /* Handle changes that require immediate behavior modification */
423 if (db->debug != new->debug) {
425 sqlite3_trace(db->handle, NULL, NULL);
427 sqlite3_trace(db->handle, trace_cb, db);
429 db->debug = new->debug;
432 if (strcmp(db->filename, new->filename)) {
433 sqlite3_close(db->handle);
434 ast_string_field_set(db, filename, new->filename);
435 db_open(db); /* Also handles setting appropriate debug on new handle */
438 if (db->batch != new->batch) {
439 if (db->batch == 0) {
440 db->batch = new->batch;
442 } else if (new->batch == 0) {
443 db->batch = new->batch;
446 db->batch = new->batch;
455 /*! \brief Create a varlist from a single sqlite3 result row */
456 static int row_to_varlist(void *arg, int num_columns, char **values, char **columns)
458 struct ast_variable **head = arg, *tail;
460 struct ast_variable *new;
462 if (!(new = ast_variable_new(columns[0], S_OR(values[0], ""), ""))) {
467 for (i = 1; i < num_columns; i++) {
468 if (!(new = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
469 ast_variables_destroy(*head);
480 /*! \brief Callback for creating an ast_config from a successive sqlite3 result rows */
481 static int append_row_to_cfg(void *arg, int num_columns, char **values, char **columns)
483 struct ast_config *cfg = arg;
484 struct ast_category *cat;
487 if (!(cat = ast_category_new("", "", 99999))) {
491 for (i = 0; i < num_columns; i++) {
492 struct ast_variable *var;
493 if (!(var = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
494 ast_log(LOG_ERROR, "Could not create new variable for '%s: %s', throwing away list\n", columns[i], values[i]);
497 ast_variable_append(cat, var);
499 ast_category_append(cfg, cat);
505 * Structure sent to the SQLite 3 callback function for static configuration.
507 * \see static_realtime_cb()
509 struct cfg_entry_args {
510 struct ast_config *cfg;
511 struct ast_category *cat;
513 struct ast_flags flags;
514 const char *who_asked;
517 /*! Exeute an SQL statement given the database object
520 * \retval > -1 Number of rows changed
522 static int realtime_sqlite3_execute_handle(struct realtime_sqlite3_db *db, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
528 if (sqlite3_exec(db->handle, sql, callback, arg, &errmsg) != SQLITE_OK) {
529 ast_log(LOG_WARNING, "Could not execute '%s': %s\n", sql, errmsg);
530 sqlite3_free(errmsg);
533 res = sqlite3_changes(db->handle);
544 /*! Exeute an SQL statement give the database name
547 * \retval > -1 Number of rows changed
549 static int realtime_sqlite3_execute(const char *database, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
551 struct realtime_sqlite3_db *db;
554 if (!(db = find_database(database))) {
555 ast_log(LOG_WARNING, "Could not find database: %s\n", database);
559 res = realtime_sqlite3_execute_handle(db, sql, callback, arg, sync);
565 /*! \note It is important that the COL_* enum matches the order of the columns selected in static_sql */
566 static const char *static_sql = "SELECT category, var_name, var_val FROM \"%q\" WHERE filename = %Q AND commented = 0 ORDER BY cat_metric ASC, var_metric ASC";
574 static int static_realtime_cb(void *arg, int num_columns, char **values, char **columns)
576 struct cfg_entry_args *args = arg;
577 struct ast_variable *var;
579 if (!strcmp(values[COL_VAR_NAME], "#include")) {
580 struct ast_config *cfg;
583 val = values[COL_VAR_VAL];
584 if (!(cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked))) {
585 ast_log(LOG_WARNING, "Unable to include %s\n", val);
593 if (!args->cat_name || strcmp(args->cat_name, values[COL_CATEGORY])) {
594 if (!(args->cat = ast_category_new(values[COL_CATEGORY], "", 99999))) {
595 ast_log(LOG_WARNING, "Unable to allocate category\n");
599 ast_free(args->cat_name);
601 if (!(args->cat_name = ast_strdup(values[COL_CATEGORY]))) {
602 ast_category_destroy(args->cat);
606 ast_category_append(args->cfg, args->cat);
609 if (!(var = ast_variable_new(values[COL_VAR_NAME], values[COL_VAR_VAL], ""))) {
610 ast_log(LOG_WARNING, "Unable to allocate variable\n");
614 ast_variable_append(args->cat, var);
619 /*! \brief Realtime callback for static realtime
620 * \return ast_config on success, NULL on failure
622 static struct ast_config *realtime_sqlite3_load(const char *database, const char *table, const char *configfile, struct ast_config *config, struct ast_flags flags, const char *suggested_include_file, const char *who_asked)
625 struct cfg_entry_args args;
627 if (ast_strlen_zero(table)) {
628 ast_log(LOG_WARNING, "Must have a table to query!\n");
632 if (!(sql = sqlite3_mprintf(static_sql, table, configfile))) {
633 ast_log(LOG_WARNING, "Couldn't allocate query\n");
639 args.cat_name = NULL;
641 args.who_asked = who_asked;
643 realtime_sqlite3_execute(database, sql, static_realtime_cb, &args, 0);
650 /*! \brief Helper function for single and multi-row realtime load functions */
651 static int realtime_sqlite3_helper(const char *database, const char *table, va_list ap, int is_multi, void *arg)
654 const char *param, *value;
657 if (ast_strlen_zero(table)) {
658 ast_log(LOG_WARNING, "Must have a table to query!\n");
662 if (!(sql = ast_str_create(128))) {
666 while ((param = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
668 ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s %s", sqlite3_escape_table(table),
669 sqlite3_escape_column_op(param), sqlite3_escape_value(value));
672 ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(param),
673 sqlite3_escape_value(value));
678 ast_str_append(&sql, 0, "%s", " LIMIT 1");
681 if (realtime_sqlite3_execute(database, ast_str_buffer(sql), is_multi ? append_row_to_cfg : row_to_varlist, arg, 0) < 0) {
691 /*! \brief Realtime callback for a single row query
692 * \return ast_variable list for single result on success, NULL on empty/failure
694 static struct ast_variable *realtime_sqlite3(const char *database, const char *table, va_list ap)
696 struct ast_variable *result_row = NULL;
698 realtime_sqlite3_helper(database, table, ap, 0, &result_row);
703 /*! \brief Realtime callback for a multi-row query
704 * \return ast_config containing possibly many results on success, NULL on empty/failure
706 static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, va_list ap)
708 struct ast_config *cfg;
710 if (!(cfg = ast_config_new())) {
714 if (realtime_sqlite3_helper(database, table, ap, 1, cfg)) {
715 ast_config_destroy(cfg);
722 /*! \brief Realtime callback for updating a row based on a single criteria
723 * \return Number of rows affected or -1 on error
725 static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap)
728 const char *key, *value;
731 if (ast_strlen_zero(table)) {
732 ast_log(LOG_WARNING, "Must have a table to query!\n");
736 if (!(sql = ast_str_create(128))) {
740 while ((key = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
742 ast_str_set(&sql, 0, "UPDATE %s SET %s = %s",
743 sqlite3_escape_table(table), sqlite3_escape_column(key), sqlite3_escape_value(value));
746 ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(key), sqlite3_escape_value(value));
750 ast_str_append(&sql, 0, " WHERE %s %s", sqlite3_escape_column_op(keyfield), sqlite3_escape_value(entity));
752 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
758 /*! \brief Realtime callback for updating a row based on multiple criteria
759 * \return Number of rows affected or -1 on error
761 static int realtime_sqlite3_update2(const char *database, const char *table, va_list ap)
764 struct ast_str *where_clause;
765 const char *key, *value;
768 if (ast_strlen_zero(table)) {
769 ast_log(LOG_WARNING, "Must have a table to query!\n");
773 if (!(sql = ast_str_create(128))) {
777 if (!(where_clause = ast_str_create(128))) {
782 while ((key = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
784 ast_str_set(&where_clause, 0, " WHERE %s %s", sqlite3_escape_column_op(key), sqlite3_escape_value(value));
787 ast_str_append(&where_clause, 0, " AND %s %s", sqlite3_escape_column_op(key), sqlite3_escape_value(value));
792 while ((key = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
794 ast_str_set(&sql, 0, "UPDATE %s SET %s = %s", sqlite3_escape_table(table), sqlite3_escape_column(key), sqlite3_escape_value(value));
797 ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(key), sqlite3_escape_value(value));
801 ast_str_append(&sql, 0, "%s", ast_str_buffer(where_clause));
803 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
806 ast_free(where_clause);
811 /*! \brief Realtime callback for inserting a row
812 * \return Number of rows affected or -1 on error
814 static int realtime_sqlite3_store(const char *database, const char *table, va_list ap)
816 struct ast_str *sql, *values;
817 const char *column, *value;
820 if (ast_strlen_zero(table)) {
821 ast_log(LOG_WARNING, "Must have a table to query!\n");
825 if (!(sql = ast_str_create(128))) {
829 if (!(values = ast_str_create(128))) {
834 while ((column = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
836 ast_str_set(&sql, 0, "INSERT INTO %s (%s", sqlite3_escape_table(table), sqlite3_escape_column(column));
837 ast_str_set(&values, 0, ") VALUES (%s", sqlite3_escape_value(value));
840 ast_str_append(&sql, 0, ", %s", sqlite3_escape_column(column));
841 ast_str_append(&values, 0, ", %s", sqlite3_escape_value(value));
845 ast_str_append(&sql, 0, "%s)", ast_str_buffer(values));
847 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
855 /*! \brief Realtime callback for deleting a row
856 * \return Number of rows affected or -1 on error
858 static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap)
861 const char *param, *value;
864 if (ast_strlen_zero(table)) {
865 ast_log(LOG_WARNING, "Must have a table to query!\n");
869 if (!(sql = ast_str_create(128))) {
873 while ((param = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
875 ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s %s", sqlite3_escape_table(table),
876 sqlite3_escape_column_op(param), sqlite3_escape_value(value));
879 ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(param), sqlite3_escape_value(value));
883 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
890 /*! \brief Convert Asterisk realtime types to SQLite 3 types
891 * \note SQLite 3 has NULL, INTEGER, REAL, TEXT, and BLOB types. Any column other than
892 * an INTEGER PRIMARY KEY will actually store any kind of data due to its dynamic
893 * typing. When we create columns, we'll go ahead and use these base types instead
894 * of messing with column widths, etc. */
896 static const char *get_sqlite_column_type(int type)
909 case RQ_UINTEGER8 : /* SQLite3 stores INTEGER as signed 8-byte */
923 /*! \brief Create a table if ast_realtime_require shows that we are configured to handle the data
925 static int handle_missing_table(struct realtime_sqlite3_db *db, const char *table, va_list ap)
928 int type, first = 1, res;
932 if (!(sql = ast_str_create(128))) {
936 while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
938 ast_str_set(&sql, 0, "CREATE TABLE IF NOT EXISTS %s (%s %s", sqlite3_escape_table(table),
939 sqlite3_escape_column(column), get_sqlite_column_type(type));
942 ast_str_append(&sql, 0, ", %s %s", sqlite3_escape_column(column), get_sqlite_column_type(type));
946 ast_str_append(&sql, 0, ")");
948 res = realtime_sqlite3_execute_handle(db, ast_str_buffer(sql), NULL, NULL, 1) < 0 ? -1 : 0;
954 /*! \brief If ast_realtime_require sends info about a column we don't have, create it
956 static int handle_missing_column(struct realtime_sqlite3_db *db, const char *table, const char *column, int type, size_t sz)
959 const char *sqltype = get_sqlite_column_type(type);
962 if (db->requirements == REALTIME_SQLITE3_REQ_WARN) {
963 ast_log(LOG_WARNING, "Missing column '%s' of type '%s' in %s.%s\n", column, sqltype, db->name, table);
965 } else if (db->requirements == REALTIME_SQLITE3_REQ_CHAR) {
969 if (!(sql = sqlite3_mprintf("ALTER TABLE \"%q\" ADD COLUMN \"%q\" %s", table, column, sqltype))) {
973 if (!(res = (realtime_sqlite3_execute_handle(db, sql, NULL, NULL, 1) < 0 ? -1 : 0))) {
974 ast_log(LOG_NOTICE, "Creating column '%s' type %s for table %s\n", column, sqltype, table);
982 static int str_hash_fn(const void *obj, const int flags)
984 return ast_str_hash((const char *) obj);
987 static int str_cmp_fn(void *obj, void *arg, int flags) {
988 return !strcasecmp((const char *) obj, (const char *) arg);
991 /*! \brief Callback for creating a hash of column names for comparison in realtime_sqlite3_require
993 static int add_column_name(void *arg, int num_columns, char **values, char **columns)
996 struct ao2_container *cnames = arg;
999 if (!(column = ao2_alloc(strlen(values[1]) + 1, NULL))) {
1003 strcpy(column, values[1]);
1005 ao2_link(cnames, column);
1006 ao2_ref(column, -1);
1011 /*! \brief Callback for ast_realtime_require
1012 * \retval 0 Required fields met specified standards
1013 * \retval -1 One or more fields was missing or insufficient
1015 static int realtime_sqlite3_require(const char *database, const char *table, va_list ap)
1022 struct ao2_container *columns;
1023 struct realtime_sqlite3_db *db;
1025 /* SQLite3 columns are dynamically typed, with type affinity. Built-in functions will
1026 * return the results as char * anyway. The only field that that cannot contain text
1027 * data is an INTEGER PRIMARY KEY, which must be a 64-bit signed integer. So, for
1028 * the purposes here we really only care whether the column exists and not what its
1029 * type or length is. */
1031 if (ast_strlen_zero(table)) {
1032 ast_log(LOG_WARNING, "Must have a table to query!\n");
1036 if (!(db = find_database(database))) {
1040 if (!(columns = ao2_container_alloc(31, str_hash_fn, str_cmp_fn))) {
1045 if (!(sql = sqlite3_mprintf("PRAGMA table_info(\"%q\")", table))) {
1047 ao2_ref(columns, -1);
1051 if ((res = realtime_sqlite3_execute_handle(db, sql, add_column_name, columns, 0)) < 0) {
1053 ao2_ref(columns, -1);
1056 } else if (res == 0) {
1057 /* Table does not exist */
1059 res = handle_missing_table(db, table, ap);
1060 ao2_ref(columns, -1);
1067 while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
1069 if (!(found = ao2_find(columns, column, OBJ_POINTER | OBJ_UNLINK))) {
1070 if (handle_missing_column(db, table, column, type, sz)) {
1072 ao2_ref(columns, -1);
1080 ao2_ref(columns, -1);
1086 /*! \brief Callback for clearing any cached info
1087 * \note We don't currently cache anything
1088 * \retval 0 If any cache was purged
1089 * \retval -1 If no cache was found
1091 static int realtime_sqlite3_unload(const char *database, const char *table)
1093 /* We currently do no caching */
1097 /*! \brief Parse the res_config_sqlite3 config file
1099 static int parse_config(int reload)
1101 struct ast_config *config;
1102 struct ast_flags config_flags = { CONFIG_FLAG_NOREALTIME | (reload ? CONFIG_FLAG_FILEUNCHANGED : 0) };
1103 static const char *config_filename = "res_config_sqlite3.conf";
1105 config = ast_config_load(config_filename, config_flags);
1107 if (config == CONFIG_STATUS_FILEUNCHANGED) {
1108 ast_debug(1, "%s was unchanged, skipping parsing\n", config_filename);
1112 ast_mutex_lock(&config_lock);
1114 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1115 ast_log(LOG_ERROR, "%s config file '%s'\n",
1116 config == CONFIG_STATUS_FILEMISSING ? "Missing" : "Invalid", config_filename);
1119 struct realtime_sqlite3_db *db;
1121 mark_all_databases_dirty();
1122 for (cat = ast_category_browse(config, NULL); cat; cat = ast_category_browse(config, cat)) {
1123 if (!strcasecmp(cat, "general")) {
1126 if (!(db = find_database(cat))) {
1127 if (!(db = new_realtime_sqlite3_db(config, cat))) {
1128 ast_log(LOG_WARNING, "Could not allocate new db for '%s' - skipping.\n", cat);
1136 ao2_link(databases, db);
1139 if (update_realtime_sqlite3_db(db, config, cat)) {
1146 unlink_dirty_databases();
1149 ast_mutex_unlock(&config_lock);
1151 ast_config_destroy(config);
1156 static int reload(void)
1162 static int unload_module(void)
1164 ast_mutex_lock(&config_lock);
1165 ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, stop_batch_cb, NULL);
1166 ao2_ref(databases, -1);
1168 ast_config_engine_deregister(&sqlite3_config_engine);
1169 ast_mutex_unlock(&config_lock);
1175 * \brief Load the module
1177 * Module loading including tests for configuration or dependencies.
1178 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1179 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1180 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1181 * configuration file or other non-critical problem return
1182 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1184 static int load_module(void)
1186 if (!((databases = ao2_container_alloc(DB_BUCKETS, db_hash_fn, db_cmp_fn)))) {
1187 return AST_MODULE_LOAD_FAILURE;
1190 if (parse_config(0)) {
1191 ao2_ref(databases, -1);
1192 return AST_MODULE_LOAD_FAILURE;
1195 if (!(ast_config_engine_register(&sqlite3_config_engine))) {
1196 ast_log(LOG_ERROR, "The config API must have changed, this shouldn't happen.\n");
1197 ao2_ref(databases, -1);
1198 return AST_MODULE_LOAD_FAILURE;
1201 return AST_MODULE_LOAD_SUCCESS;
1204 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SQLite 3 realtime config engine",
1205 .load = load_module,
1206 .unload = unload_module,
1208 .load_pri = AST_MODPRI_REALTIME_DRIVER,