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
33 <depend>sqlite3</depend>
34 <support_level>core</support_level>
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include "asterisk/module.h"
44 #include "asterisk/config.h"
45 #include "asterisk/paths.h"
46 #include "asterisk/astobj2.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/utils.h"
49 #include "asterisk/app.h"
54 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);
55 static struct ast_variable *realtime_sqlite3(const char *database, const char *table, va_list ap);
56 static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, va_list ap);
57 static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap);
58 static int realtime_sqlite3_update2(const char *database, const char *table, va_list ap);
59 static int realtime_sqlite3_store(const char *database, const char *table, va_list ap);
60 static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap);
61 static int realtime_sqlite3_require(const char *database, const char *table, va_list ap);
62 static int realtime_sqlite3_unload(const char *database, const char *table);
64 struct ast_config_engine sqlite3_config_engine = {
66 .load_func = realtime_sqlite3_load,
67 .realtime_func = realtime_sqlite3,
68 .realtime_multi_func = realtime_sqlite3_multi,
69 .update_func = realtime_sqlite3_update,
70 .update2_func = realtime_sqlite3_update2,
71 .store_func = realtime_sqlite3_store,
72 .destroy_func = realtime_sqlite3_destroy,
73 .require_func = realtime_sqlite3_require,
74 .unload_func = realtime_sqlite3_unload,
78 REALTIME_SQLITE3_REQ_WARN,
79 REALTIME_SQLITE3_REQ_CLOSE,
80 REALTIME_SQLITE3_REQ_CHAR,
83 struct realtime_sqlite3_db {
84 AST_DECLARE_STRING_FIELDS(
85 AST_STRING_FIELD(name);
86 AST_STRING_FIELD(filename);
91 unsigned int requirements:2;
94 unsigned int exiting:1;
95 unsigned int wakeup:1;
99 struct ao2_container *databases;
102 AST_MUTEX_DEFINE_STATIC(config_lock);
104 /* We need a separate buffer for each field we might use concurrently */
105 AST_THREADSTORAGE(escape_table_buf);
106 AST_THREADSTORAGE(escape_column_buf);
107 AST_THREADSTORAGE(escape_value_buf);
109 static int realtime_sqlite3_execute_handle(struct realtime_sqlite3_db *db, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync);
110 void db_start_batch(struct realtime_sqlite3_db *db);
111 void db_stop_batch(struct realtime_sqlite3_db *db);
113 static inline const char *sqlite3_escape_string_helper(struct ast_threadstorage *ts, const char *param)
115 size_t maxlen = strlen(param) * 2 + sizeof("\"\"");
116 /* It doesn't appear that sqlite3_snprintf will do more than double the
117 * length of a string with %q as an option. %Q could double and possibly
118 * add two quotes, and convert NULL pointers to the word "NULL", but we
119 * don't allow those anyway. Just going to use %q for now. */
120 struct ast_str *buf = ast_str_thread_get(ts, maxlen);
121 char *tmp = ast_str_buffer(buf);
122 char q = ts == &escape_value_buf ? '\'' : '"';
125 *tmp++ = q; /* Initial quote */
126 while ((*tmp++ = *param++)) {
127 /* Did we just copy a quote? Then double it. */
128 if (*(tmp - 1) == q) {
132 *tmp = '\0'; /* Terminate past NULL from copy */
133 *(tmp - 1) = q; /* Replace original NULL with the quote */
136 return ast_str_buffer(buf);
139 static inline const char *sqlite3_escape_table(const char *param)
141 return sqlite3_escape_string_helper(&escape_table_buf, param);
144 static inline const char *sqlite3_escape_column(const char *param)
146 return sqlite3_escape_string_helper(&escape_column_buf, param);
149 /* Not inlining this function because it uses strdupa and I don't know if the compiler would be dumb */
150 static const char *sqlite3_escape_column_op(const char *param)
152 size_t maxlen = strlen(param) * 2 + sizeof("\"\" =");
153 struct ast_str *buf = ast_str_thread_get(&escape_column_buf, maxlen);
154 char *tmp = ast_str_buffer(buf);
159 while ((*tmp++ = *param++)) {
160 /* If we have seen a space, don't double quotes. XXX If we ever make the column/op field
161 * available to users via an API, we will definitely need to avoid allowing special
162 * characters like ';' in the data past the space as it will be unquoted data */
166 if (*(tmp - 1) == ' ') {
170 } else if (*(tmp - 1) == '"') {
175 strcpy(tmp - 1, "\" =");
180 return ast_str_buffer(buf);
183 static inline const char *sqlite3_escape_value(const char *param)
185 return sqlite3_escape_string_helper(&escape_value_buf, param);
188 static int db_hash_fn(const void *obj, const int flags)
190 const struct realtime_sqlite3_db *db = obj;
192 return ast_str_hash(flags & OBJ_KEY ? (const char *) obj : db->name);
195 static int db_cmp_fn(void *obj, void *arg, int flags) {
196 struct realtime_sqlite3_db *db = obj, *other = arg;
197 const char *name = arg;
199 return !strcasecmp(db->name, flags & OBJ_KEY ? name : other->name) ? CMP_MATCH | CMP_STOP : 0;
202 static void db_destructor(void *obj)
204 struct realtime_sqlite3_db *db = obj;
206 ast_debug(1, "Destroying db: %s\n", db->name);
207 ast_string_field_free_memory(db);
211 sqlite3_close(db->handle);
216 static struct realtime_sqlite3_db *find_database(const char *database)
218 return ao2_find(databases, database, OBJ_KEY);
221 static void unref_db(struct realtime_sqlite3_db **db)
227 static int stop_batch_cb(void *obj, void *arg, int flags)
229 struct realtime_sqlite3_db *db = obj;
235 static int mark_dirty_cb(void *obj, void *arg, int flags)
237 struct realtime_sqlite3_db *db = obj;
242 static void mark_all_databases_dirty(void)
244 ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA, mark_dirty_cb, NULL);
247 static int is_dirty_cb(void *obj, void *arg, int flags)
249 struct realtime_sqlite3_db *db = obj;
257 static void unlink_dirty_databases(void)
259 ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, is_dirty_cb, NULL);
262 static int str_to_requirements(const char *data)
264 if (!strcasecmp(data, "createclose")) {
265 return REALTIME_SQLITE3_REQ_CLOSE;
266 } else if (!strcasecmp(data, "createchar")) {
267 return REALTIME_SQLITE3_REQ_CHAR;
270 return REALTIME_SQLITE3_REQ_WARN;
273 /*! \note Since this is called while a query is executing, we should already hold the db lock */
274 static void trace_cb(void *arg, const char *sql)
276 struct realtime_sqlite3_db *db = arg;
277 ast_debug(3, "DB: %s SQL: %s\n", db->name, sql);
280 /*! \brief Wrap commands in transactions increased write performance */
281 static void *db_sync_thread(void *data)
283 struct realtime_sqlite3_db *db = data;
285 realtime_sqlite3_execute_handle(db, "BEGIN TRANSACTION", NULL, NULL, 0);
288 ast_cond_wait(&db->cond, ao2_object_get_lockaddr(db));
291 if (realtime_sqlite3_execute_handle(db, "COMMIT", NULL, NULL, 0) < 0) {
292 realtime_sqlite3_execute_handle(db, "ROLLBACK", NULL, NULL, 0);
298 realtime_sqlite3_execute_handle(db, "BEGIN TRANSACTION", NULL, NULL, 0);
300 usleep(1000 * db->batch);
309 /*! \brief Open a database and appropriately set debugging on the db handle */
310 static int db_open(struct realtime_sqlite3_db *db)
313 if (sqlite3_open(db->filename, &db->handle) != SQLITE_OK) {
314 ast_log(LOG_WARNING, "Could not open %s: %s\n", db->filename, sqlite3_errmsg(db->handle));
320 sqlite3_trace(db->handle, trace_cb, db);
322 sqlite3_trace(db->handle, NULL, NULL);
330 static void db_sync(struct realtime_sqlite3_db *db)
333 ast_cond_signal(&db->cond);
336 void db_start_batch(struct realtime_sqlite3_db *db)
339 ast_cond_init(&db->cond, NULL);
341 ast_pthread_create_background(&db->syncthread, NULL, db_sync_thread, db);
345 void db_stop_batch(struct realtime_sqlite3_db *db)
350 pthread_join(db->syncthread, NULL);
354 /*! \brief Create a db object based on a config category
355 * \note Opening the db handle and linking to databases must be handled outside of this function
357 static struct realtime_sqlite3_db *new_realtime_sqlite3_db(struct ast_config *config, const char *cat)
359 struct ast_variable *var;
360 struct realtime_sqlite3_db *db;
362 if (!(db = ao2_alloc(sizeof(*db), db_destructor))) {
366 if (ast_string_field_init(db, 64)) {
372 db->requirements = REALTIME_SQLITE3_REQ_WARN;
374 ast_string_field_set(db, name, cat);
376 for (var = ast_variable_browse(config, cat); var; var = var->next) {
377 if (!strcasecmp(var->name, "dbfile")) {
378 ast_string_field_set(db, filename, var->value);
379 } else if (!strcasecmp(var->name, "requirements")) {
380 db->requirements = str_to_requirements(var->value);
381 } else if (!strcasecmp(var->name, "batch")) {
382 ast_app_parse_timelen(var->value, (int *) &db->batch, TIMELEN_MILLISECONDS);
383 } else if (!strcasecmp(var->name, "debug")) {
384 db->debug = ast_true(var->value);
388 if (ast_strlen_zero(db->filename)) {
389 ast_log(LOG_WARNING, "Must specify dbfile in res_config_sqlite3.conf\n");
397 /*! \brief Update an existing db object based on config data
398 * \param db The database object to update
399 * \param config The configuration data with which to update the db
400 * \param cat The config category (which becomes db->name)
402 static int update_realtime_sqlite3_db(struct realtime_sqlite3_db *db, struct ast_config *config, const char *cat)
404 struct realtime_sqlite3_db *new;
406 if (!(new = new_realtime_sqlite3_db(config, cat))) {
410 /* Copy fields that don't need anything special done on change */
411 db->requirements = new->requirements;
413 /* Handle changes that require immediate behavior modification */
414 if (db->debug != new->debug) {
416 sqlite3_trace(db->handle, NULL, NULL);
418 sqlite3_trace(db->handle, trace_cb, db);
420 db->debug = new->debug;
423 if (strcmp(db->filename, new->filename)) {
424 sqlite3_close(db->handle);
425 ast_string_field_set(db, filename, new->filename);
426 db_open(db); /* Also handles setting appropriate debug on new handle */
429 if (db->batch != new->batch) {
430 if (db->batch == 0) {
431 db->batch = new->batch;
433 } else if (new->batch == 0) {
434 db->batch = new->batch;
437 db->batch = new->batch;
446 /*! \brief Create a varlist from a single sqlite3 result row */
447 static int row_to_varlist(void *arg, int num_columns, char **values, char **columns)
449 struct ast_variable **head = arg, *tail;
451 struct ast_variable *new;
453 if (!(new = ast_variable_new(columns[0], S_OR(values[0], ""), ""))) {
458 for (i = 1; i < num_columns; i++) {
459 if (!(new = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
460 ast_variables_destroy(*head);
471 /*! \brief Callback for creating an ast_config from a successive sqlite3 result rows */
472 static int append_row_to_cfg(void *arg, int num_columns, char **values, char **columns)
474 struct ast_config *cfg = arg;
475 struct ast_category *cat;
478 if (!(cat = ast_category_new("", "", 99999))) {
482 for (i = 0; i < num_columns; i++) {
483 struct ast_variable *var;
484 if (!(var = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
485 ast_log(LOG_ERROR, "Could not create new variable for '%s: %s', throwing away list\n", columns[i], values[i]);
488 ast_variable_append(cat, var);
490 ast_category_append(cfg, cat);
496 * Structure sent to the SQLite 3 callback function for static configuration.
498 * \see static_realtime_cb()
500 struct cfg_entry_args {
501 struct ast_config *cfg;
502 struct ast_category *cat;
504 struct ast_flags flags;
505 const char *who_asked;
508 /*! Exeute an SQL statement given the database object
511 * \retval > -1 Number of rows changed
513 static int realtime_sqlite3_execute_handle(struct realtime_sqlite3_db *db, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
519 if (sqlite3_exec(db->handle, sql, callback, arg, &errmsg) != SQLITE_OK) {
520 ast_log(LOG_WARNING, "Could not execute '%s': %s\n", sql, errmsg);
521 sqlite3_free(errmsg);
524 res = sqlite3_changes(db->handle);
535 /*! Exeute an SQL statement give the database name
538 * \retval > -1 Number of rows changed
540 static int realtime_sqlite3_execute(const char *database, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
542 struct realtime_sqlite3_db *db;
545 if (!(db = find_database(database))) {
546 ast_log(LOG_WARNING, "Could not find database: %s\n", database);
550 res = realtime_sqlite3_execute_handle(db, sql, callback, arg, sync);
556 /*! \note It is important that the COL_* enum matches the order of the columns selected in static_sql */
557 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";
565 static int static_realtime_cb(void *arg, int num_columns, char **values, char **columns)
567 struct cfg_entry_args *args = arg;
568 struct ast_variable *var;
570 if (!strcmp(values[COL_VAR_NAME], "#include")) {
571 struct ast_config *cfg;
574 val = values[COL_VAR_VAL];
575 if (!(cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked))) {
576 ast_log(LOG_WARNING, "Unable to include %s\n", val);
584 if (!args->cat_name || strcmp(args->cat_name, values[COL_CATEGORY])) {
585 if (!(args->cat = ast_category_new(values[COL_CATEGORY], "", 99999))) {
586 ast_log(LOG_WARNING, "Unable to allocate category\n");
590 ast_free(args->cat_name);
592 if (!(args->cat_name = ast_strdup(values[COL_CATEGORY]))) {
593 ast_category_destroy(args->cat);
597 ast_category_append(args->cfg, args->cat);
600 if (!(var = ast_variable_new(values[COL_VAR_NAME], values[COL_VAR_VAL], ""))) {
601 ast_log(LOG_WARNING, "Unable to allocate variable\n");
605 ast_variable_append(args->cat, var);
610 /*! \brief Realtime callback for static realtime
611 * \return ast_config on success, NULL on failure
613 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)
616 struct cfg_entry_args args;
618 if (ast_strlen_zero(table)) {
619 ast_log(LOG_WARNING, "Must have a table to query!\n");
623 if (!(sql = sqlite3_mprintf(static_sql, table, configfile))) {
624 ast_log(LOG_WARNING, "Couldn't allocate query\n");
630 args.cat_name = NULL;
632 args.who_asked = who_asked;
634 realtime_sqlite3_execute(database, sql, static_realtime_cb, &args, 0);
641 /*! \brief Helper function for single and multi-row realtime load functions */
642 static int realtime_sqlite3_helper(const char *database, const char *table, va_list ap, int is_multi, void *arg)
645 const char *param, *value;
648 if (ast_strlen_zero(table)) {
649 ast_log(LOG_WARNING, "Must have a table to query!\n");
653 if (!(sql = ast_str_create(128))) {
657 while ((param = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
659 ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s %s", sqlite3_escape_table(table),
660 sqlite3_escape_column_op(param), sqlite3_escape_value(value));
663 ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(param),
664 sqlite3_escape_value(value));
669 ast_str_append(&sql, 0, "%s", " LIMIT 1");
672 if (realtime_sqlite3_execute(database, ast_str_buffer(sql), is_multi ? append_row_to_cfg : row_to_varlist, arg, 0) < 0) {
682 /*! \brief Realtime callback for a single row query
683 * \return ast_variable list for single result on success, NULL on empty/failure
685 static struct ast_variable *realtime_sqlite3(const char *database, const char *table, va_list ap)
687 struct ast_variable *result_row = NULL;
689 realtime_sqlite3_helper(database, table, ap, 0, &result_row);
694 /*! \brief Realtime callback for a multi-row query
695 * \return ast_config containing possibly many results on success, NULL on empty/failure
697 static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, va_list ap)
699 struct ast_config *cfg;
701 if (!(cfg = ast_config_new())) {
705 if (realtime_sqlite3_helper(database, table, ap, 1, cfg)) {
706 ast_config_destroy(cfg);
713 /*! \brief Realtime callback for updating a row based on a single criteria
714 * \return Number of rows affected or -1 on error
716 static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap)
719 const char *key, *value;
722 if (ast_strlen_zero(table)) {
723 ast_log(LOG_WARNING, "Must have a table to query!\n");
727 if (!(sql = ast_str_create(128))) {
731 while ((key = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
733 ast_str_set(&sql, 0, "UPDATE %s SET %s = %s",
734 sqlite3_escape_table(table), sqlite3_escape_column(key), sqlite3_escape_value(value));
737 ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(key), sqlite3_escape_value(value));
741 ast_str_append(&sql, 0, " WHERE %s %s", sqlite3_escape_column_op(keyfield), sqlite3_escape_value(entity));
743 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
749 /*! \brief Realtime callback for updating a row based on multiple criteria
750 * \return Number of rows affected or -1 on error
752 static int realtime_sqlite3_update2(const char *database, const char *table, va_list ap)
755 struct ast_str *where_clause;
756 const char *key, *value;
759 if (ast_strlen_zero(table)) {
760 ast_log(LOG_WARNING, "Must have a table to query!\n");
764 if (!(sql = ast_str_create(128))) {
768 if (!(where_clause = ast_str_create(128))) {
773 while ((key = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
775 ast_str_set(&where_clause, 0, " WHERE %s %s", sqlite3_escape_column_op(key), sqlite3_escape_value(value));
778 ast_str_append(&where_clause, 0, " AND %s %s", sqlite3_escape_column_op(key), sqlite3_escape_value(value));
783 while ((key = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
785 ast_str_set(&sql, 0, "UPDATE %s SET %s = %s", sqlite3_escape_table(table), sqlite3_escape_column(key), sqlite3_escape_value(value));
788 ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(key), sqlite3_escape_value(value));
792 ast_str_append(&sql, 0, "%s", ast_str_buffer(where_clause));
794 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
797 ast_free(where_clause);
802 /*! \brief Realtime callback for inserting a row
803 * \return Number of rows affected or -1 on error
805 static int realtime_sqlite3_store(const char *database, const char *table, va_list ap)
807 struct ast_str *sql, *values;
808 const char *column, *value;
811 if (ast_strlen_zero(table)) {
812 ast_log(LOG_WARNING, "Must have a table to query!\n");
816 if (!(sql = ast_str_create(128))) {
820 if (!(values = ast_str_create(128))) {
825 while ((column = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
827 ast_str_set(&sql, 0, "INSERT INTO %s (%s", sqlite3_escape_table(table), sqlite3_escape_column(column));
828 ast_str_set(&values, 0, ") VALUES (%s", sqlite3_escape_value(value));
831 ast_str_append(&sql, 0, ", %s", sqlite3_escape_column(column));
832 ast_str_append(&values, 0, ", %s", sqlite3_escape_value(value));
836 ast_str_append(&sql, 0, "%s)", ast_str_buffer(values));
838 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
846 /*! \brief Realtime callback for deleting a row
847 * \return Number of rows affected or -1 on error
849 static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap)
852 const char *param, *value;
855 if (ast_strlen_zero(table)) {
856 ast_log(LOG_WARNING, "Must have a table to query!\n");
860 if (!(sql = ast_str_create(128))) {
864 while ((param = va_arg(ap, const char *)) && (value = va_arg(ap, const char *))) {
866 ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s %s", sqlite3_escape_table(table),
867 sqlite3_escape_column_op(param), sqlite3_escape_value(value));
870 ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(param), sqlite3_escape_value(value));
874 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
881 /*! \brief Convert Asterisk realtime types to SQLite 3 types
882 * \note SQLite 3 has NULL, INTEGER, REAL, TEXT, and BLOB types. Any column other than
883 * an INTEGER PRIMARY KEY will actually store any kind of data due to its dynamic
884 * typing. When we create columns, we'll go ahead and use these base types instead
885 * of messing with column widths, etc. */
887 static const char *get_sqlite_column_type(int type)
900 case RQ_UINTEGER8 : /* SQLite3 stores INTEGER as signed 8-byte */
914 /*! \brief Create a table if ast_realtime_require shows that we are configured to handle the data
916 static int handle_missing_table(struct realtime_sqlite3_db *db, const char *table, va_list ap)
919 int type, first = 1, res;
923 if (!(sql = ast_str_create(128))) {
927 while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
929 ast_str_set(&sql, 0, "CREATE TABLE IF NOT EXISTS %s (%s %s", sqlite3_escape_table(table),
930 sqlite3_escape_column(column), get_sqlite_column_type(type));
933 ast_str_append(&sql, 0, ", %s %s", sqlite3_escape_column(column), get_sqlite_column_type(type));
937 ast_str_append(&sql, 0, ")");
939 res = realtime_sqlite3_execute_handle(db, ast_str_buffer(sql), NULL, NULL, 1) < 0 ? -1 : 0;
945 /*! \brief If ast_realtime_require sends info about a column we don't have, create it
947 static int handle_missing_column(struct realtime_sqlite3_db *db, const char *table, const char *column, int type, size_t sz)
950 const char *sqltype = get_sqlite_column_type(type);
953 if (db->requirements == REALTIME_SQLITE3_REQ_WARN) {
954 ast_log(LOG_WARNING, "Missing column '%s' of type '%s' in %s.%s\n", column, sqltype, db->name, table);
956 } else if (db->requirements == REALTIME_SQLITE3_REQ_CHAR) {
960 if (!(sql = sqlite3_mprintf("ALTER TABLE \"%q\" ADD COLUMN \"%q\" %s", table, column, sqltype))) {
964 if (!(res = realtime_sqlite3_execute_handle(db, sql, NULL, NULL, 1) < 0 ? -1 : 0)) {
965 ast_log(LOG_NOTICE, "Creating column '%s' type %s for table %s\n", column, sqltype, table);
973 static int str_hash_fn(const void *obj, const int flags)
975 return ast_str_hash((const char *) obj);
978 static int str_cmp_fn(void *obj, void *arg, int flags) {
979 return !strcasecmp((const char *) obj, (const char *) arg);
982 /*! \brief Callback for creating a hash of column names for comparison in realtime_sqlite3_require
984 static int add_column_name(void *arg, int num_columns, char **values, char **columns)
987 struct ao2_container *cnames = arg;
990 if (!(column = ao2_alloc(strlen(values[1]) + 1, NULL))) {
994 strcpy(column, values[1]);
996 ao2_link(cnames, column);
1002 /*! \brief Callback for ast_realtime_require
1003 * \retval 0 Required fields met specified standards
1004 * \retval -1 One or more fields was missing or insufficient
1006 static int realtime_sqlite3_require(const char *database, const char *table, va_list ap)
1013 struct ao2_container *columns;
1014 struct realtime_sqlite3_db *db;
1016 /* SQLite3 columns are dynamically typed, with type affinity. Built-in functions will
1017 * return the results as char * anyway. The only field that that cannot contain text
1018 * data is an INTEGER PRIMARY KEY, which must be a 64-bit signed integer. So, for
1019 * the purposes here we really only care whether the column exists and not what its
1020 * type or length is. */
1022 if (ast_strlen_zero(table)) {
1023 ast_log(LOG_WARNING, "Must have a table to query!\n");
1027 if (!(db = find_database(database))) {
1031 if (!(columns = ao2_container_alloc(31, str_hash_fn, str_cmp_fn))) {
1036 if (!(sql = sqlite3_mprintf("PRAGMA table_info(\"%q\")", table))) {
1038 ao2_ref(columns, -1);
1042 if ((res = realtime_sqlite3_execute_handle(db, sql, add_column_name, columns, 0)) < 0) {
1044 ao2_ref(columns, -1);
1047 } else if (res == 0) {
1048 /* Table does not exist */
1050 res = handle_missing_table(db, table, ap);
1051 ao2_ref(columns, -1);
1058 while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
1060 if (!(found = ao2_find(columns, column, OBJ_POINTER | OBJ_UNLINK))) {
1061 if (handle_missing_column(db, table, column, type, sz)) {
1063 ao2_ref(columns, -1);
1071 ao2_ref(columns, -1);
1077 /*! \brief Callback for clearing any cached info
1078 * \note We don't currently cache anything
1079 * \retval 0 If any cache was purged
1080 * \retval -1 If no cache was found
1082 static int realtime_sqlite3_unload(const char *database, const char *table)
1084 /* We currently do no caching */
1088 /*! \brief Parse the res_config_sqlite3 config file
1090 static int parse_config(int reload)
1092 struct ast_config *config;
1093 struct ast_flags config_flags = { CONFIG_FLAG_NOREALTIME | (reload ? CONFIG_FLAG_FILEUNCHANGED : 0) };
1094 static const char *config_filename = "res_config_sqlite3.conf";
1096 config = ast_config_load(config_filename, config_flags);
1098 if (config == CONFIG_STATUS_FILEUNCHANGED) {
1099 ast_debug(1, "%s was unchanged, skipping parsing\n", config_filename);
1103 ast_mutex_lock(&config_lock);
1105 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1106 ast_log(LOG_ERROR, "%s config file '%s'\n",
1107 config == CONFIG_STATUS_FILEMISSING ? "Missing" : "Invalid", config_filename);
1110 struct realtime_sqlite3_db *db;
1112 mark_all_databases_dirty();
1113 for (cat = ast_category_browse(config, NULL); cat; cat = ast_category_browse(config, cat)) {
1114 if (!strcasecmp(cat, "general")) {
1117 if (!(db = find_database(cat))) {
1118 if (!(db = new_realtime_sqlite3_db(config, cat))) {
1119 ast_log(LOG_WARNING, "Could not allocate new db for '%s' - skipping.\n", cat);
1127 ao2_link(databases, db);
1130 if (update_realtime_sqlite3_db(db, config, cat)) {
1137 unlink_dirty_databases();
1140 ast_mutex_unlock(&config_lock);
1142 ast_config_destroy(config);
1147 static int reload(void)
1153 static int unload_module(void)
1155 ast_mutex_lock(&config_lock);
1156 ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, stop_batch_cb, NULL);
1157 ao2_ref(databases, -1);
1159 ast_config_engine_deregister(&sqlite3_config_engine);
1160 ast_mutex_unlock(&config_lock);
1165 static int load_module(void)
1167 if (!((databases = ao2_container_alloc(DB_BUCKETS, db_hash_fn, db_cmp_fn)))) {
1168 return AST_MODULE_LOAD_FAILURE;
1171 if (parse_config(0)) {
1172 ao2_ref(databases, -1);
1173 return AST_MODULE_LOAD_FAILURE;
1176 if (!(ast_config_engine_register(&sqlite3_config_engine))) {
1177 ast_log(LOG_ERROR, "The config API must have changed, this shouldn't happen.\n");
1178 ao2_ref(databases, -1);
1179 return AST_MODULE_LOAD_FAILURE;
1182 return AST_MODULE_LOAD_SUCCESS;
1185 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SQLite 3 realtime config engine",
1186 .load = load_module,
1187 .unload = unload_module,
1189 .load_pri = AST_MODPRI_REALTIME_DRIVER,