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, const struct ast_variable *fields);
65 static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, const struct ast_variable *fields);
66 static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields);
67 static int realtime_sqlite3_update2(const char *database, const char *table, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields);
68 static int realtime_sqlite3_store(const char *database, const char *table, const struct ast_variable *fields);
69 static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields);
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));
327 sqlite3_busy_timeout(db->handle, 1000);
330 sqlite3_trace(db->handle, trace_cb, db);
332 sqlite3_trace(db->handle, NULL, NULL);
340 static void db_sync(struct realtime_sqlite3_db *db)
343 ast_cond_signal(&db->cond);
346 void db_start_batch(struct realtime_sqlite3_db *db)
349 ast_cond_init(&db->cond, NULL);
351 ast_pthread_create_background(&db->syncthread, NULL, db_sync_thread, db);
355 void db_stop_batch(struct realtime_sqlite3_db *db)
360 pthread_join(db->syncthread, NULL);
364 /*! \brief Create a db object based on a config category
365 * \note Opening the db handle and linking to databases must be handled outside of this function
367 static struct realtime_sqlite3_db *new_realtime_sqlite3_db(struct ast_config *config, const char *cat)
369 struct ast_variable *var;
370 struct realtime_sqlite3_db *db;
372 if (!(db = ao2_alloc(sizeof(*db), db_destructor))) {
376 if (ast_string_field_init(db, 64)) {
382 db->requirements = REALTIME_SQLITE3_REQ_WARN;
384 ast_string_field_set(db, name, cat);
386 for (var = ast_variable_browse(config, cat); var; var = var->next) {
387 if (!strcasecmp(var->name, "dbfile")) {
388 ast_string_field_set(db, filename, var->value);
389 } else if (!strcasecmp(var->name, "requirements")) {
390 db->requirements = str_to_requirements(var->value);
391 } else if (!strcasecmp(var->name, "batch")) {
392 ast_app_parse_timelen(var->value, (int *) &db->batch, TIMELEN_MILLISECONDS);
393 } else if (!strcasecmp(var->name, "debug")) {
394 db->debug = ast_true(var->value);
398 if (ast_strlen_zero(db->filename)) {
399 ast_log(LOG_WARNING, "Must specify dbfile in res_config_sqlite3.conf\n");
407 /*! \brief Update an existing db object based on config data
408 * \param db The database object to update
409 * \param config The configuration data with which to update the db
410 * \param cat The config category (which becomes db->name)
412 static int update_realtime_sqlite3_db(struct realtime_sqlite3_db *db, struct ast_config *config, const char *cat)
414 struct realtime_sqlite3_db *new;
416 if (!(new = new_realtime_sqlite3_db(config, cat))) {
420 /* Copy fields that don't need anything special done on change */
421 db->requirements = new->requirements;
423 /* Handle changes that require immediate behavior modification */
424 if (db->debug != new->debug) {
426 sqlite3_trace(db->handle, NULL, NULL);
428 sqlite3_trace(db->handle, trace_cb, db);
430 db->debug = new->debug;
433 if (strcmp(db->filename, new->filename)) {
434 sqlite3_close(db->handle);
435 ast_string_field_set(db, filename, new->filename);
436 db_open(db); /* Also handles setting appropriate debug on new handle */
439 if (db->batch != new->batch) {
440 if (db->batch == 0) {
441 db->batch = new->batch;
443 } else if (new->batch == 0) {
444 db->batch = new->batch;
447 db->batch = new->batch;
456 /*! \brief Create a varlist from a single sqlite3 result row */
457 static int row_to_varlist(void *arg, int num_columns, char **values, char **columns)
459 struct ast_variable **head = arg, *tail;
461 struct ast_variable *new;
463 if (!(new = ast_variable_new(columns[0], S_OR(values[0], ""), ""))) {
468 for (i = 1; i < num_columns; i++) {
469 if (!(new = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
470 ast_variables_destroy(*head);
481 /*! \brief Callback for creating an ast_config from a successive sqlite3 result rows */
482 static int append_row_to_cfg(void *arg, int num_columns, char **values, char **columns)
484 struct ast_config *cfg = arg;
485 struct ast_category *cat;
488 if (!(cat = ast_category_new("", "", 99999))) {
492 for (i = 0; i < num_columns; i++) {
493 struct ast_variable *var;
494 if (!(var = ast_variable_new(columns[i], S_OR(values[i], ""), ""))) {
495 ast_log(LOG_ERROR, "Could not create new variable for '%s: %s', throwing away list\n", columns[i], values[i]);
498 ast_variable_append(cat, var);
500 ast_category_append(cfg, cat);
506 * Structure sent to the SQLite 3 callback function for static configuration.
508 * \see static_realtime_cb()
510 struct cfg_entry_args {
511 struct ast_config *cfg;
512 struct ast_category *cat;
514 struct ast_flags flags;
515 const char *who_asked;
518 /*! Exeute an SQL statement given the database object
521 * \retval > -1 Number of rows changed
523 static int realtime_sqlite3_execute_handle(struct realtime_sqlite3_db *db, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
529 if (sqlite3_exec(db->handle, sql, callback, arg, &errmsg) != SQLITE_OK) {
530 ast_log(LOG_WARNING, "Could not execute '%s': %s\n", sql, errmsg);
531 sqlite3_free(errmsg);
534 res = sqlite3_changes(db->handle);
545 /*! Exeute an SQL statement give the database name
548 * \retval > -1 Number of rows changed
550 static int realtime_sqlite3_execute(const char *database, const char *sql, int (*callback)(void*, int, char **, char **), void *arg, int sync)
552 struct realtime_sqlite3_db *db;
555 if (!(db = find_database(database))) {
556 ast_log(LOG_WARNING, "Could not find database: %s\n", database);
560 res = realtime_sqlite3_execute_handle(db, sql, callback, arg, sync);
566 /*! \note It is important that the COL_* enum matches the order of the columns selected in static_sql */
567 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";
575 static int static_realtime_cb(void *arg, int num_columns, char **values, char **columns)
577 struct cfg_entry_args *args = arg;
578 struct ast_variable *var;
580 if (!strcmp(values[COL_VAR_NAME], "#include")) {
581 struct ast_config *cfg;
584 val = values[COL_VAR_VAL];
585 if (!(cfg = ast_config_internal_load(val, args->cfg, args->flags, "", args->who_asked))) {
586 ast_log(LOG_WARNING, "Unable to include %s\n", val);
594 if (!args->cat_name || strcmp(args->cat_name, values[COL_CATEGORY])) {
595 if (!(args->cat = ast_category_new(values[COL_CATEGORY], "", 99999))) {
596 ast_log(LOG_WARNING, "Unable to allocate category\n");
600 ast_free(args->cat_name);
602 if (!(args->cat_name = ast_strdup(values[COL_CATEGORY]))) {
603 ast_category_destroy(args->cat);
607 ast_category_append(args->cfg, args->cat);
610 if (!(var = ast_variable_new(values[COL_VAR_NAME], values[COL_VAR_VAL], ""))) {
611 ast_log(LOG_WARNING, "Unable to allocate variable\n");
615 ast_variable_append(args->cat, var);
620 /*! \brief Realtime callback for static realtime
621 * \return ast_config on success, NULL on failure
623 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)
626 struct cfg_entry_args args;
628 if (ast_strlen_zero(table)) {
629 ast_log(LOG_WARNING, "Must have a table to query!\n");
633 if (!(sql = sqlite3_mprintf(static_sql, table, configfile))) {
634 ast_log(LOG_WARNING, "Couldn't allocate query\n");
640 args.cat_name = NULL;
642 args.who_asked = who_asked;
644 realtime_sqlite3_execute(database, sql, static_realtime_cb, &args, 0);
651 /*! \brief Helper function for single and multi-row realtime load functions */
652 static int realtime_sqlite3_helper(const char *database, const char *table, const struct ast_variable *fields, int is_multi, void *arg)
655 const struct ast_variable *field;
658 if (ast_strlen_zero(table)) {
659 ast_log(LOG_WARNING, "Must have a table to query!\n");
663 if (!(sql = ast_str_create(128))) {
667 for (field = fields; field; field = field->next) {
669 ast_str_set(&sql, 0, "SELECT * FROM %s WHERE %s %s", sqlite3_escape_table(table),
670 sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
673 ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(field->name),
674 sqlite3_escape_value(field->value));
679 ast_str_append(&sql, 0, "%s", " LIMIT 1");
682 if (realtime_sqlite3_execute(database, ast_str_buffer(sql), is_multi ? append_row_to_cfg : row_to_varlist, arg, 0) < 0) {
692 /*! \brief Realtime callback for a single row query
693 * \return ast_variable list for single result on success, NULL on empty/failure
695 static struct ast_variable *realtime_sqlite3(const char *database, const char *table, const struct ast_variable *fields)
697 struct ast_variable *result_row = NULL;
699 realtime_sqlite3_helper(database, table, fields, 0, &result_row);
704 /*! \brief Realtime callback for a multi-row query
705 * \return ast_config containing possibly many results on success, NULL on empty/failure
707 static struct ast_config *realtime_sqlite3_multi(const char *database, const char *table, const struct ast_variable *fields)
709 struct ast_config *cfg;
711 if (!(cfg = ast_config_new())) {
715 if (realtime_sqlite3_helper(database, table, fields, 1, cfg)) {
716 ast_config_destroy(cfg);
723 /*! \brief Realtime callback for updating a row based on a single criteria
724 * \return Number of rows affected or -1 on error
726 static int realtime_sqlite3_update(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields)
729 const struct ast_variable *field;
732 if (ast_strlen_zero(table)) {
733 ast_log(LOG_WARNING, "Must have a table to query!\n");
737 if (!(sql = ast_str_create(128))) {
741 for (field = fields; field; field = field->next) {
743 ast_str_set(&sql, 0, "UPDATE %s SET %s = %s",
744 sqlite3_escape_table(table), sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
747 ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
751 ast_str_append(&sql, 0, " WHERE %s %s", sqlite3_escape_column_op(keyfield), sqlite3_escape_value(entity));
753 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
759 /*! \brief Realtime callback for updating a row based on multiple criteria
760 * \return Number of rows affected or -1 on error
762 static int realtime_sqlite3_update2(const char *database, const char *table, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
765 struct ast_str *where_clause;
766 const struct ast_variable *field;
769 if (ast_strlen_zero(table)) {
770 ast_log(LOG_WARNING, "Must have a table to query!\n");
774 if (!(sql = ast_str_create(128))) {
778 if (!(where_clause = ast_str_create(128))) {
783 for (field = lookup_fields; field; field = field->next) {
785 ast_str_set(&where_clause, 0, " WHERE %s %s", sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
788 ast_str_append(&where_clause, 0, " AND %s %s", sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
793 for (field = update_fields; field; field = field->next) {
795 ast_str_set(&sql, 0, "UPDATE %s SET %s = %s", sqlite3_escape_table(table), sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
798 ast_str_append(&sql, 0, ", %s = %s", sqlite3_escape_column(field->name), sqlite3_escape_value(field->value));
802 ast_str_append(&sql, 0, "%s", ast_str_buffer(where_clause));
804 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
807 ast_free(where_clause);
812 /*! \brief Realtime callback for inserting a row
813 * \return Number of rows affected or -1 on error
815 static int realtime_sqlite3_store(const char *database, const char *table, const struct ast_variable *fields)
817 struct ast_str *sql, *values;
818 const struct ast_variable *field;
821 if (ast_strlen_zero(table)) {
822 ast_log(LOG_WARNING, "Must have a table to query!\n");
826 if (!(sql = ast_str_create(128))) {
830 if (!(values = ast_str_create(128))) {
835 for (field = fields; field; field = field->next) {
837 ast_str_set(&sql, 0, "INSERT INTO %s (%s", sqlite3_escape_table(table), sqlite3_escape_column(field->name));
838 ast_str_set(&values, 0, ") VALUES (%s", sqlite3_escape_value(field->value));
841 ast_str_append(&sql, 0, ", %s", sqlite3_escape_column(field->name));
842 ast_str_append(&values, 0, ", %s", sqlite3_escape_value(field->value));
846 ast_str_append(&sql, 0, "%s)", ast_str_buffer(values));
848 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
856 /*! \brief Realtime callback for deleting a row
857 * \return Number of rows affected or -1 on error
859 static int realtime_sqlite3_destroy(const char *database, const char *table, const char *keyfield, const char *entity, const struct ast_variable *fields)
862 const struct ast_variable *field;
865 if (ast_strlen_zero(table)) {
866 ast_log(LOG_WARNING, "Must have a table to query!\n");
870 if (!(sql = ast_str_create(128))) {
874 for (field = fields; field; field = field->next) {
876 ast_str_set(&sql, 0, "DELETE FROM %s WHERE %s %s", sqlite3_escape_table(table),
877 sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
880 ast_str_append(&sql, 0, " AND %s %s", sqlite3_escape_column_op(field->name), sqlite3_escape_value(field->value));
884 res = realtime_sqlite3_execute(database, ast_str_buffer(sql), NULL, NULL, 1);
891 /*! \brief Convert Asterisk realtime types to SQLite 3 types
892 * \note SQLite 3 has NULL, INTEGER, REAL, TEXT, and BLOB types. Any column other than
893 * an INTEGER PRIMARY KEY will actually store any kind of data due to its dynamic
894 * typing. When we create columns, we'll go ahead and use these base types instead
895 * of messing with column widths, etc. */
897 static const char *get_sqlite_column_type(int type)
910 case RQ_UINTEGER8 : /* SQLite3 stores INTEGER as signed 8-byte */
924 /*! \brief Create a table if ast_realtime_require shows that we are configured to handle the data
926 static int handle_missing_table(struct realtime_sqlite3_db *db, const char *table, va_list ap)
929 int type, first = 1, res;
933 if (!(sql = ast_str_create(128))) {
937 while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
939 ast_str_set(&sql, 0, "CREATE TABLE IF NOT EXISTS %s (%s %s", sqlite3_escape_table(table),
940 sqlite3_escape_column(column), get_sqlite_column_type(type));
943 ast_str_append(&sql, 0, ", %s %s", sqlite3_escape_column(column), get_sqlite_column_type(type));
947 ast_str_append(&sql, 0, ")");
949 res = realtime_sqlite3_execute_handle(db, ast_str_buffer(sql), NULL, NULL, 1) < 0 ? -1 : 0;
955 /*! \brief If ast_realtime_require sends info about a column we don't have, create it
957 static int handle_missing_column(struct realtime_sqlite3_db *db, const char *table, const char *column, int type, size_t sz)
960 const char *sqltype = get_sqlite_column_type(type);
963 if (db->requirements == REALTIME_SQLITE3_REQ_WARN) {
964 ast_log(LOG_WARNING, "Missing column '%s' of type '%s' in %s.%s\n", column, sqltype, db->name, table);
966 } else if (db->requirements == REALTIME_SQLITE3_REQ_CHAR) {
970 if (!(sql = sqlite3_mprintf("ALTER TABLE \"%q\" ADD COLUMN \"%q\" %s", table, column, sqltype))) {
974 if (!(res = (realtime_sqlite3_execute_handle(db, sql, NULL, NULL, 1) < 0 ? -1 : 0))) {
975 ast_log(LOG_NOTICE, "Creating column '%s' type %s for table %s\n", column, sqltype, table);
983 static int str_hash_fn(const void *obj, const int flags)
985 return ast_str_hash((const char *) obj);
988 static int str_cmp_fn(void *obj, void *arg, int flags) {
989 return !strcasecmp((const char *) obj, (const char *) arg);
992 /*! \brief Callback for creating a hash of column names for comparison in realtime_sqlite3_require
994 static int add_column_name(void *arg, int num_columns, char **values, char **columns)
997 struct ao2_container *cnames = arg;
1000 if (!(column = ao2_alloc(strlen(values[1]) + 1, NULL))) {
1004 strcpy(column, values[1]);
1006 ao2_link(cnames, column);
1007 ao2_ref(column, -1);
1012 /*! \brief Callback for ast_realtime_require
1013 * \retval 0 Required fields met specified standards
1014 * \retval -1 One or more fields was missing or insufficient
1016 static int realtime_sqlite3_require(const char *database, const char *table, va_list ap)
1023 struct ao2_container *columns;
1024 struct realtime_sqlite3_db *db;
1026 /* SQLite3 columns are dynamically typed, with type affinity. Built-in functions will
1027 * return the results as char * anyway. The only field that that cannot contain text
1028 * data is an INTEGER PRIMARY KEY, which must be a 64-bit signed integer. So, for
1029 * the purposes here we really only care whether the column exists and not what its
1030 * type or length is. */
1032 if (ast_strlen_zero(table)) {
1033 ast_log(LOG_WARNING, "Must have a table to query!\n");
1037 if (!(db = find_database(database))) {
1041 if (!(columns = ao2_container_alloc(31, str_hash_fn, str_cmp_fn))) {
1046 if (!(sql = sqlite3_mprintf("PRAGMA table_info(\"%q\")", table))) {
1048 ao2_ref(columns, -1);
1052 if ((res = realtime_sqlite3_execute_handle(db, sql, add_column_name, columns, 0)) < 0) {
1054 ao2_ref(columns, -1);
1057 } else if (res == 0) {
1058 /* Table does not exist */
1060 res = handle_missing_table(db, table, ap);
1061 ao2_ref(columns, -1);
1068 while ((column = va_arg(ap, typeof(column))) && (type = va_arg(ap, typeof(type))) && (sz = va_arg(ap, typeof(sz)))) {
1070 if (!(found = ao2_find(columns, column, OBJ_POINTER | OBJ_UNLINK))) {
1071 if (handle_missing_column(db, table, column, type, sz)) {
1073 ao2_ref(columns, -1);
1081 ao2_ref(columns, -1);
1087 /*! \brief Callback for clearing any cached info
1088 * \note We don't currently cache anything
1089 * \retval 0 If any cache was purged
1090 * \retval -1 If no cache was found
1092 static int realtime_sqlite3_unload(const char *database, const char *table)
1094 /* We currently do no caching */
1098 /*! \brief Parse the res_config_sqlite3 config file
1100 static int parse_config(int reload)
1102 struct ast_config *config;
1103 struct ast_flags config_flags = { CONFIG_FLAG_NOREALTIME | (reload ? CONFIG_FLAG_FILEUNCHANGED : 0) };
1104 static const char *config_filename = "res_config_sqlite3.conf";
1106 config = ast_config_load(config_filename, config_flags);
1108 if (config == CONFIG_STATUS_FILEUNCHANGED) {
1109 ast_debug(1, "%s was unchanged, skipping parsing\n", config_filename);
1113 ast_mutex_lock(&config_lock);
1115 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1116 ast_log(LOG_ERROR, "%s config file '%s'\n",
1117 config == CONFIG_STATUS_FILEMISSING ? "Missing" : "Invalid", config_filename);
1120 struct realtime_sqlite3_db *db;
1122 mark_all_databases_dirty();
1123 for (cat = ast_category_browse(config, NULL); cat; cat = ast_category_browse(config, cat)) {
1124 if (!strcasecmp(cat, "general")) {
1127 if (!(db = find_database(cat))) {
1128 if (!(db = new_realtime_sqlite3_db(config, cat))) {
1129 ast_log(LOG_WARNING, "Could not allocate new db for '%s' - skipping.\n", cat);
1137 ao2_link(databases, db);
1140 if (update_realtime_sqlite3_db(db, config, cat)) {
1147 unlink_dirty_databases();
1150 ast_mutex_unlock(&config_lock);
1152 ast_config_destroy(config);
1157 static int reload(void)
1163 static int unload_module(void)
1165 ast_mutex_lock(&config_lock);
1166 ao2_callback(databases, OBJ_MULTIPLE | OBJ_NODATA | OBJ_UNLINK, stop_batch_cb, NULL);
1167 ao2_ref(databases, -1);
1169 ast_config_engine_deregister(&sqlite3_config_engine);
1170 ast_mutex_unlock(&config_lock);
1176 * \brief Load the module
1178 * Module loading including tests for configuration or dependencies.
1179 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1180 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1181 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1182 * configuration file or other non-critical problem return
1183 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1185 static int load_module(void)
1187 if (!((databases = ao2_container_alloc(DB_BUCKETS, db_hash_fn, db_cmp_fn)))) {
1188 return AST_MODULE_LOAD_FAILURE;
1191 if (parse_config(0)) {
1192 ao2_ref(databases, -1);
1193 return AST_MODULE_LOAD_FAILURE;
1196 if (!(ast_config_engine_register(&sqlite3_config_engine))) {
1197 ast_log(LOG_ERROR, "The config API must have changed, this shouldn't happen.\n");
1198 ao2_ref(databases, -1);
1199 return AST_MODULE_LOAD_FAILURE;
1202 return AST_MODULE_LOAD_SUCCESS;
1205 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SQLite 3 realtime config engine",
1206 .load = load_module,
1207 .unload = unload_module,
1209 .load_pri = AST_MODPRI_REALTIME_DRIVER,