mark this revision as merged manually
[asterisk/asterisk.git] / cdr / cdr_adaptive_odbc.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007, Tilghman Lesher
5  *
6  * Tilghman Lesher <cdr_adaptive_odbc__v1@the-tilghman.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief Adaptive ODBC CDR backend
22  * 
23  * \author Tilghman Lesher <cdr_adaptive_odbc__v1@the-tilghman.com>
24  * \ingroup cdr_drivers
25  */
26
27 /*** MODULEINFO
28         <depend>unixodbc_or_iodbc</depend>
29         <use>unixodbc</use>
30         <use>iodbc</use>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <sys/types.h>
38 #include <time.h>
39
40 #include <sql.h>
41 #include <sqlext.h>
42 #include <sqltypes.h>
43
44 #include "asterisk/config.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/lock.h"
47 #include "asterisk/linkedlists.h"
48 #include "asterisk/res_odbc.h"
49 #include "asterisk/cdr.h"
50 #include "asterisk/module.h"
51
52 #define CONFIG  "cdr_adaptive_odbc.conf"
53
54 static char *name = "Adaptive ODBC";
55 /* Optimization to reduce number of memory allocations */
56 static int maxsize = 512, maxsize2 = 512;
57
58 struct columns {
59         char *name;
60         char *cdrname;
61         char *filtervalue;
62         SQLSMALLINT type;
63         SQLINTEGER size;
64         SQLSMALLINT decimals;
65         SQLSMALLINT radix;
66         SQLSMALLINT nullable;
67         SQLINTEGER octetlen;
68         AST_LIST_ENTRY(columns) list;
69 };
70
71 struct tables {
72         char *connection;
73         char *table;
74         unsigned int usegmtime:1;
75         AST_LIST_HEAD_NOLOCK(odbc_columns, columns) columns;
76         AST_RWLIST_ENTRY(tables) list;
77 };
78
79 static AST_RWLIST_HEAD_STATIC(odbc_tables, tables);
80
81 static int load_config(void)
82 {
83         struct ast_config *cfg;
84         struct ast_variable *var;
85         const char *tmp, *catg;
86         struct tables *tableptr;
87         struct columns *entry;
88         struct odbc_obj *obj;
89         char columnname[80];
90         char connection[40];
91         char table[40];
92         int lenconnection, lentable, usegmtime = 0;
93         SQLLEN sqlptr;
94         int res = 0;
95         SQLHSTMT stmt = NULL;
96         struct ast_flags config_flags = { 0 }; /* Part of our config comes from the database */
97
98         cfg = ast_config_load(CONFIG, config_flags);
99         if (!cfg) {
100                 ast_log(LOG_WARNING, "Unable to load " CONFIG ".  No adaptive ODBC CDRs.\n");
101                 return -1;
102         }
103
104         for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
105                 var = ast_variable_browse(cfg, catg);
106                 if (!var)
107                         continue;
108
109                 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "connection"))) {
110                         ast_log(LOG_WARNING, "No connection parameter found in '%s'.  Skipping.\n", catg);
111                         continue;
112                 }
113                 ast_copy_string(connection, tmp, sizeof(connection));
114                 lenconnection = strlen(connection);
115
116                 if (!ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "usegmtime"))) {
117                         usegmtime = ast_true(tmp);
118                 }
119
120                 /* When loading, we want to be sure we can connect. */
121                 obj = ast_odbc_request_obj(connection, 1);
122                 if (!obj) {
123                         ast_log(LOG_WARNING, "No such connection '%s' in the '%s' section of " CONFIG ".  Check res_odbc.conf.\n", connection, catg);
124                         continue;
125                 }
126
127                 if (ast_strlen_zero(tmp = ast_variable_retrieve(cfg, catg, "table"))) {
128                         ast_log(LOG_NOTICE, "No table name found.  Assuming 'cdr'.\n");
129                         tmp = "cdr";
130                 }
131                 ast_copy_string(table, tmp, sizeof(table));
132                 lentable = strlen(table);
133
134                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
135                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
136                         ast_log(LOG_WARNING, "SQL Alloc Handle failed on connection '%s'!\n", connection);
137                         ast_odbc_release_obj(obj);
138                         continue;
139                 }
140
141                 res = SQLColumns(stmt, NULL, 0, NULL, 0, (unsigned char *)table, SQL_NTS, (unsigned char *)"%", SQL_NTS);
142                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
143                         ast_log(LOG_ERROR, "Unable to query database columns on connection '%s'.  Skipping.\n", connection);
144                         ast_odbc_release_obj(obj);
145                         continue;
146                 }
147
148                 tableptr = ast_calloc(sizeof(char), sizeof(*tableptr) + lenconnection + 1 + lentable + 1);
149                 if (!tableptr) {
150                         ast_log(LOG_ERROR, "Out of memory creating entry for table '%s' on connection '%s'\n", table, connection);
151                         ast_odbc_release_obj(obj);
152                         res = -1;
153                         break;
154                 }
155
156                 tableptr->usegmtime = usegmtime;
157                 tableptr->connection = (char *)tableptr + sizeof(*tableptr);
158                 tableptr->table = (char *)tableptr + sizeof(*tableptr) + lenconnection + 1;
159                 ast_copy_string(tableptr->connection, connection, lenconnection + 1);
160                 ast_copy_string(tableptr->table, table, lentable + 1);
161
162                 ast_verb(3, "Found adaptive CDR table %s@%s.\n", tableptr->table, tableptr->connection);
163
164                 /* Check for filters first */
165                 for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
166                         if (strncmp(var->name, "filter", 6) == 0) {
167                                 char *cdrvar = ast_strdupa(var->name + 6);
168                                 cdrvar = ast_strip(cdrvar);
169                                 ast_verb(3, "Found filter %s for cdr variable %s in %s@%s\n", var->value, cdrvar, tableptr->table, tableptr->connection);
170
171                                 entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(cdrvar) + 1 + strlen(var->value) + 1);
172                                 if (!entry) {
173                                         ast_log(LOG_ERROR, "Out of memory creating filter entry for CDR variable '%s' in table '%s' on connection '%s'\n", cdrvar, table, connection);
174                                         res = -1;
175                                         break;
176                                 }
177
178                                 /* NULL column entry means this isn't a column in the database */
179                                 entry->name = NULL;
180                                 entry->cdrname = (char *)entry + sizeof(*entry);
181                                 entry->filtervalue = (char *)entry + sizeof(*entry) + strlen(cdrvar) + 1;
182                                 strcpy(entry->cdrname, cdrvar);
183                                 strcpy(entry->filtervalue, var->value);
184
185                                 AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
186                         }
187                 }
188
189                 while ((res = SQLFetch(stmt)) != SQL_NO_DATA && res != SQL_ERROR) {
190                         char *cdrvar = "";
191
192                         SQLGetData(stmt,  4, SQL_C_CHAR, columnname, sizeof(columnname), &sqlptr);
193
194                         /* Is there an alias for this column? */
195
196                         /* NOTE: This seems like a non-optimal parse method, but I'm going
197                          * for user configuration readability, rather than fast parsing. We
198                          * really don't parse this file all that often, anyway.
199                          */
200                         for (var = ast_variable_browse(cfg, catg); var; var = var->next) {
201                                 if (strncmp(var->name, "alias", 5) == 0 && strcasecmp(var->value, columnname) == 0) {
202                                         char *alias = ast_strdupa(var->name + 5);
203                                         cdrvar = ast_strip(alias);
204                                         ast_verb(3, "Found alias %s for column %s in %s@%s\n", cdrvar, columnname, tableptr->table, tableptr->connection);
205                                         break;
206                                 }
207                         }
208
209                         entry = ast_calloc(sizeof(char), sizeof(*entry) + strlen(columnname) + 1 + strlen(cdrvar) + 1);
210                         if (!entry) {
211                                 ast_log(LOG_ERROR, "Out of memory creating entry for column '%s' in table '%s' on connection '%s'\n", columnname, table, connection);
212                                 res = -1;
213                                 break;
214                         }
215                         entry->name = (char *)entry + sizeof(*entry);
216                         strcpy(entry->name, columnname);
217
218                         if (!ast_strlen_zero(cdrvar)) {
219                                 entry->cdrname = entry->name + strlen(columnname) + 1;
220                                 strcpy(entry->cdrname, cdrvar);
221                         } else /* Point to same place as the column name */
222                                 entry->cdrname = (char *)entry + sizeof(*entry);
223
224                         SQLGetData(stmt,  5, SQL_C_SHORT, &entry->type, sizeof(entry->type), NULL);
225                         SQLGetData(stmt,  7, SQL_C_LONG, &entry->size, sizeof(entry->size), NULL);
226                         SQLGetData(stmt,  9, SQL_C_SHORT, &entry->decimals, sizeof(entry->decimals), NULL);
227                         SQLGetData(stmt, 10, SQL_C_SHORT, &entry->radix, sizeof(entry->radix), NULL);
228                         SQLGetData(stmt, 11, SQL_C_SHORT, &entry->nullable, sizeof(entry->nullable), NULL);
229                         SQLGetData(stmt, 16, SQL_C_LONG, &entry->octetlen, sizeof(entry->octetlen), NULL);
230
231                         /* Specification states that the octenlen should be the maximum number of bytes
232                          * returned in a char or binary column, but it seems that some drivers just set
233                          * it to NULL. (Bad Postgres! No biscuit!) */
234                         if (entry->octetlen == 0)
235                                 entry->octetlen = entry->size;
236
237                         ast_verb(10, "Found %s column with type %hd with len %ld, octetlen %ld, and numlen (%hd,%hd)\n", entry->name, entry->type, (long) entry->size, (long) entry->octetlen, entry->decimals, entry->radix);
238                         /* Insert column info into column list */
239                         AST_LIST_INSERT_TAIL(&(tableptr->columns), entry, list);
240                         res = 0;
241                 }
242
243                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
244                 ast_odbc_release_obj(obj);
245
246                 if (AST_LIST_FIRST(&(tableptr->columns)))
247                         AST_RWLIST_INSERT_TAIL(&odbc_tables, tableptr, list);
248                 else
249                         ast_free(tableptr);
250         }
251         return res;
252 }
253
254 static int free_config(void)
255 {
256         struct tables *table;
257         struct columns *entry;
258         while ((table = AST_RWLIST_REMOVE_HEAD(&odbc_tables, list))) {
259                 while ((entry = AST_LIST_REMOVE_HEAD(&(table->columns), list))) {
260                         ast_free(entry);
261                 }
262                 ast_free(table);
263         }
264         return 0;
265 }
266
267 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
268 {
269         int res, i;
270         char *sql = data;
271         SQLHSTMT stmt;
272         SQLINTEGER nativeerror = 0, numfields = 0;
273         SQLSMALLINT diagbytes = 0;
274         unsigned char state[10], diagnostic[256];
275
276         res = SQLAllocHandle (SQL_HANDLE_STMT, obj->con, &stmt);
277         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
278                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
279                 return NULL;
280         }
281
282         res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
283         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
284                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
285                 SQLGetDiagField(SQL_HANDLE_STMT, stmt, 1, SQL_DIAG_NUMBER, &numfields, SQL_IS_INTEGER, &diagbytes);
286                 for (i = 0; i < numfields; i++) {
287                         SQLGetDiagRec(SQL_HANDLE_STMT, stmt, i + 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
288                         ast_log(LOG_WARNING, "SQL Execute returned an error %d: %s: %s (%d)\n", res, state, diagnostic, diagbytes);
289                         if (i > 10) {
290                                 ast_log(LOG_WARNING, "Oh, that was good.  There are really %d diagnostics?\n", (int)numfields);
291                                 break;
292                         }
293                 }
294                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
295                 return NULL;
296         }
297
298         return stmt;
299 }
300
301 #define LENGTHEN_BUF1(size)                                                                                                             \
302                         do {                                                                                                                            \
303                                 /* Lengthen buffer, if necessary */                                                             \
304                                 if (sql->used + size + 1 > sql->len) {                          \
305                                         if (ast_str_make_space(&sql, ((sql->len + size + 1) / 512 + 1) * 512) != 0) { \
306                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
307                                                 ast_free(sql);                                                                                  \
308                                                 ast_free(sql2);                                                                                 \
309                                                 AST_RWLIST_UNLOCK(&odbc_tables);                                                \
310                                                 return -1;                                                                                              \
311                                         }                                                                                                                       \
312                                 }                                                                                                                               \
313                         } while (0)
314
315 #define LENGTHEN_BUF2(size)                                                                                                             \
316                         do {                                                                                                                            \
317                                 if (sql2->used + size + 1 > sql2->len) {                        \
318                                         if (ast_str_make_space(&sql2, ((sql2->len + size + 3) / 512 + 1) * 512) != 0) { \
319                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR '%s:%s' failed.\n", tableptr->connection, tableptr->table); \
320                                                 ast_free(sql);                                                                                  \
321                                                 ast_free(sql2);                                                                                 \
322                                                 AST_RWLIST_UNLOCK(&odbc_tables);                                                \
323                                                 return -1;                                                                                              \
324                                         }                                                                                                                       \
325                                 }                                                                                                                               \
326                         } while (0)
327
328 static int odbc_log(struct ast_cdr *cdr)
329 {
330         struct tables *tableptr;
331         struct columns *entry;
332         struct odbc_obj *obj;
333         struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
334         char *tmp;
335         char colbuf[1024], *colptr;
336         SQLHSTMT stmt = NULL;
337         SQLLEN rows = 0;
338
339         if (!sql || !sql2) {
340                 if (sql)
341                         ast_free(sql);
342                 if (sql2)
343                         ast_free(sql2);
344                 return -1;
345         }
346
347         if (AST_RWLIST_RDLOCK(&odbc_tables)) {
348                 ast_log(LOG_ERROR, "Unable to lock table list.  Insert CDR(s) failed.\n");
349                 ast_free(sql);
350                 ast_free(sql2);
351                 return -1;
352         }
353
354         AST_LIST_TRAVERSE(&odbc_tables, tableptr, list) {
355                 ast_str_set(&sql, 0, "INSERT INTO %s (", tableptr->table);
356                 ast_str_set(&sql2, 0, " VALUES (");
357
358                 /* No need to check the connection now; we'll handle any failure in prepare_and_execute */
359                 if (!(obj = ast_odbc_request_obj(tableptr->connection, 0))) {
360                         ast_log(LOG_WARNING, "cdr_adaptive_odbc: Unable to retrieve database handle for '%s:%s'.  CDR failed: %s\n", tableptr->connection, tableptr->table, sql->str);
361                         continue;
362                 }
363
364                 AST_LIST_TRAVERSE(&(tableptr->columns), entry, list) {
365                         int datefield = 0;
366                         if (strcasecmp(entry->cdrname, "start") == 0) {
367                                 datefield = 1;
368                         } else if (strcasecmp(entry->cdrname, "answer") == 0) {
369                                 datefield = 2;
370                         } else if (strcasecmp(entry->cdrname, "end") == 0) {
371                                 datefield = 3;
372                         }
373
374                         /* Check if we have a similarly named variable */
375                         if (datefield && tableptr->usegmtime) {
376                                 struct timeval date_tv = (datefield == 1) ? cdr->start : (datefield == 2) ? cdr->answer : cdr->end;
377                                 struct ast_tm tm = { 0, };
378                                 ast_localtime(&date_tv, &tm, "UTC");
379                                 ast_strftime(colbuf, sizeof(colbuf), "%Y-%m-%d %H:%M:%S", &tm);
380                         } else {
381                                 ast_cdr_getvar(cdr, entry->cdrname, &colptr, colbuf, sizeof(colbuf), 0, datefield ? 0 : 1);
382                         }
383
384                         if (colptr) {
385                                 /* Check first if the column filters this entry.  Note that this
386                                  * is very specifically NOT ast_strlen_zero(), because the filter
387                                  * could legitimately specify that the field is blank, which is
388                                  * different from the field being unspecified (NULL). */
389                                 if (entry->filtervalue && strcasecmp(colptr, entry->filtervalue) != 0) {
390                                         ast_verb(4, "CDR column '%s' with value '%s' does not match filter of"
391                                                 " '%s'.  Cancelling this CDR.\n",
392                                                 entry->cdrname, colptr, entry->filtervalue);
393                                         goto early_release;
394                                 }
395
396                                 /* Only a filter? */
397                                 if (ast_strlen_zero(entry->name))
398                                         continue;
399
400                                 LENGTHEN_BUF1(strlen(entry->name));
401
402                                 switch (entry->type) {
403                                 case SQL_CHAR:
404                                 case SQL_VARCHAR:
405                                 case SQL_LONGVARCHAR:
406                                 case SQL_BINARY:
407                                 case SQL_VARBINARY:
408                                 case SQL_LONGVARBINARY:
409                                 case SQL_GUID:
410                                         /* For these two field names, get the rendered form, instead of the raw
411                                          * form (but only when we're dealing with a character-based field).
412                                          */
413                                         if (strcasecmp(entry->name, "disposition") == 0)
414                                                 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
415                                         else if (strcasecmp(entry->name, "amaflags") == 0)
416                                                 ast_cdr_getvar(cdr, entry->name, &colptr, colbuf, sizeof(colbuf), 0, 0);
417
418                                         /* Truncate too-long fields */
419                                         if (entry->type != SQL_GUID) {
420                                                 if (strlen(colptr) > entry->octetlen)
421                                                         colptr[entry->octetlen] = '\0';
422                                         }
423
424                                         ast_str_append(&sql, 0, "%s,", entry->name);
425                                         LENGTHEN_BUF2(strlen(colptr));
426
427                                         /* Encode value, with escaping */
428                                         ast_str_append(&sql2, 0, "'");
429                                         for (tmp = colptr; *tmp; tmp++) {
430                                                 if (*tmp == '\'') {
431                                                         ast_str_append(&sql2, 0, "''");
432                                                 } else if (*tmp == '\\' && ast_odbc_backslash_is_escape(obj)) {
433                                                         ast_str_append(&sql2, 0, "\\\\");
434                                                 } else {
435                                                         ast_str_append(&sql2, 0, "%c", *tmp);
436                                                 }
437                                         }
438                                         ast_str_append(&sql2, 0, "',");
439                                         break;
440                                 case SQL_TYPE_DATE:
441                                         {
442                                                 int year = 0, month = 0, day = 0;
443                                                 if (sscanf(colptr, "%d-%d-%d", &year, &month, &day) != 3 || year <= 0 ||
444                                                         month <= 0 || month > 12 || day < 0 || day > 31 ||
445                                                         ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
446                                                         (month == 2 && year % 400 == 0 && day > 29) ||
447                                                         (month == 2 && year % 100 == 0 && day > 28) ||
448                                                         (month == 2 && year % 4 == 0 && day > 29) ||
449                                                         (month == 2 && year % 4 != 0 && day > 28)) {
450                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid date ('%s').\n", entry->name, colptr);
451                                                         break;
452                                                 }
453
454                                                 if (year > 0 && year < 100)
455                                                         year += 2000;
456
457                                                 ast_str_append(&sql, 0, "%s,", entry->name);
458                                                 LENGTHEN_BUF2(17);
459                                                 ast_str_append(&sql2, 0, "{ d '%04d-%02d-%02d' },", year, month, day);
460                                         }
461                                         break;
462                                 case SQL_TYPE_TIME:
463                                         {
464                                                 int hour = 0, minute = 0, second = 0;
465                                                 int count = sscanf(colptr, "%d:%d:%d", &hour, &minute, &second);
466
467                                                 if ((count != 2 && count != 3) || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
468                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid time ('%s').\n", entry->name, colptr);
469                                                         break;
470                                                 }
471
472                                                 ast_str_append(&sql, 0, "%s,", entry->name);
473                                                 LENGTHEN_BUF2(15);
474                                                 ast_str_append(&sql2, 0, "{ t '%02d:%02d:%02d' },", hour, minute, second);
475                                         }
476                                         break;
477                                 case SQL_TYPE_TIMESTAMP:
478                                 case SQL_TIMESTAMP:
479                                         {
480                                                 int year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
481                                                 int count = sscanf(colptr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
482
483                                                 if ((count != 3 && count != 5 && count != 6) || year <= 0 ||
484                                                         month <= 0 || month > 12 || day < 0 || day > 31 ||
485                                                         ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) ||
486                                                         (month == 2 && year % 400 == 0 && day > 29) ||
487                                                         (month == 2 && year % 100 == 0 && day > 28) ||
488                                                         (month == 2 && year % 4 == 0 && day > 29) ||
489                                                         (month == 2 && year % 4 != 0 && day > 28) ||
490                                                         hour > 23 || minute > 59 || second > 59 || hour < 0 || minute < 0 || second < 0) {
491                                                         ast_log(LOG_WARNING, "CDR variable %s is not a valid timestamp ('%s').\n", entry->name, colptr);
492                                                         break;
493                                                 }
494
495                                                 if (year > 0 && year < 100)
496                                                         year += 2000;
497
498                                                 ast_str_append(&sql, 0, "%s,", entry->name);
499                                                 LENGTHEN_BUF2(26);
500                                                 ast_str_append(&sql2, 0, "{ ts '%04d-%02d-%02d %02d:%02d:%02d' },", year, month, day, hour, minute, second);
501                                         }
502                                         break;
503                                 case SQL_INTEGER:
504                                         {
505                                                 int integer = 0;
506                                                 if (sscanf(colptr, "%d", &integer) != 1) {
507                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
508                                                         break;
509                                                 }
510
511                                                 ast_str_append(&sql, 0, "%s,", entry->name);
512                                                 LENGTHEN_BUF2(12);
513                                                 ast_str_append(&sql2, 0, "%d,", integer);
514                                         }
515                                         break;
516                                 case SQL_BIGINT:
517                                         {
518                                                 long long integer = 0;
519                                                 if (sscanf(colptr, "%lld", &integer) != 1) {
520                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
521                                                         break;
522                                                 }
523
524                                                 ast_str_append(&sql, 0, "%s,", entry->name);
525                                                 LENGTHEN_BUF2(24);
526                                                 ast_str_append(&sql2, 0, "%lld,", integer);
527                                         }
528                                         break;
529                                 case SQL_SMALLINT:
530                                         {
531                                                 short integer = 0;
532                                                 if (sscanf(colptr, "%hd", &integer) != 1) {
533                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
534                                                         break;
535                                                 }
536
537                                                 ast_str_append(&sql, 0, "%s,", entry->name);
538                                                 LENGTHEN_BUF2(6);
539                                                 ast_str_append(&sql2, 0, "%d,", integer);
540                                         }
541                                         break;
542                                 case SQL_TINYINT:
543                                         {
544                                                 char integer = 0;
545                                                 if (sscanf(colptr, "%hhd", &integer) != 1) {
546                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
547                                                         break;
548                                                 }
549
550                                                 ast_str_append(&sql, 0, "%s,", entry->name);
551                                                 LENGTHEN_BUF2(4);
552                                                 ast_str_append(&sql2, 0, "%d,", integer);
553                                         }
554                                         break;
555                                 case SQL_BIT:
556                                         {
557                                                 char integer = 0;
558                                                 if (sscanf(colptr, "%hhd", &integer) != 1) {
559                                                         ast_log(LOG_WARNING, "CDR variable %s is not an integer.\n", entry->name);
560                                                         break;
561                                                 }
562                                                 if (integer != 0)
563                                                         integer = 1;
564
565                                                 ast_str_append(&sql, 0, "%s,", entry->name);
566                                                 LENGTHEN_BUF2(2);
567                                                 ast_str_append(&sql2, 0, "%d,", integer);
568                                         }
569                                         break;
570                                 case SQL_NUMERIC:
571                                 case SQL_DECIMAL:
572                                         {
573                                                 double number = 0.0;
574                                                 if (sscanf(colptr, "%lf", &number) != 1) {
575                                                         ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
576                                                         break;
577                                                 }
578
579                                                 ast_str_append(&sql, 0, "%s,", entry->name);
580                                                 LENGTHEN_BUF2(entry->decimals);
581                                                 ast_str_append(&sql2, 0, "%*.*lf,", entry->decimals, entry->radix, number);
582                                         }
583                                         break;
584                                 case SQL_FLOAT:
585                                 case SQL_REAL:
586                                 case SQL_DOUBLE:
587                                         {
588                                                 double number = 0.0;
589                                                 if (sscanf(colptr, "%lf", &number) != 1) {
590                                                         ast_log(LOG_WARNING, "CDR variable %s is not an numeric type.\n", entry->name);
591                                                         break;
592                                                 }
593
594                                                 ast_str_append(&sql, 0, "%s,", entry->name);
595                                                 LENGTHEN_BUF2(entry->decimals);
596                                                 ast_str_append(&sql2, 0, "%lf,", number);
597                                         }
598                                         break;
599                                 default:
600                                         ast_log(LOG_WARNING, "Column type %d (field '%s:%s:%s') is unsupported at this time.\n", entry->type, tableptr->connection, tableptr->table, entry->name);
601                                 }
602                         }
603                 }
604
605                 /* Concatenate the two constructed buffers */
606                 LENGTHEN_BUF1(sql2->used);
607                 sql->str[sql->used - 1] = ')';
608                 sql2->str[sql2->used - 1] = ')';
609                 ast_str_append(&sql, 0, "%s", sql2->str);
610
611                 ast_verb(11, "[%s]\n", sql->str);
612
613                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, sql->str);
614                 if (stmt) {
615                         SQLRowCount(stmt, &rows);
616                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
617                 }
618                 if (rows == 0) {
619                         ast_log(LOG_WARNING, "cdr_adaptive_odbc: Insert failed on '%s:%s'.  CDR failed: %s\n", tableptr->connection, tableptr->table, sql->str);
620                 }
621 early_release:
622                 ast_odbc_release_obj(obj);
623         }
624         AST_RWLIST_UNLOCK(&odbc_tables);
625
626         /* Next time, just allocate buffers that are that big to start with. */
627         if (sql->used > maxsize)
628                 maxsize = sql->used;
629         if (sql2->used > maxsize2)
630                 maxsize2 = sql2->used;
631
632         ast_free(sql);
633         ast_free(sql2);
634         return 0;
635 }
636
637 static int unload_module(void)
638 {
639         ast_cdr_unregister(name);
640         usleep(1);
641         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
642                 ast_cdr_register(name, ast_module_info->description, odbc_log);
643                 ast_log(LOG_ERROR, "Unable to lock column list.  Unload failed.\n");
644                 return -1;
645         }
646
647         free_config();
648         AST_RWLIST_UNLOCK(&odbc_tables);
649         return 0;
650 }
651
652 static int load_module(void)
653 {
654         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
655                 ast_log(LOG_ERROR, "Unable to lock column list.  Load failed.\n");
656                 return 0;
657         }
658
659         load_config();
660         AST_RWLIST_UNLOCK(&odbc_tables);
661         ast_cdr_register(name, ast_module_info->description, odbc_log);
662         return 0;
663 }
664
665 static int reload(void)
666 {
667         if (AST_RWLIST_WRLOCK(&odbc_tables)) {
668                 ast_log(LOG_ERROR, "Unable to lock column list.  Reload failed.\n");
669                 return -1;
670         }
671
672         free_config();
673         load_config();
674         AST_RWLIST_UNLOCK(&odbc_tables);
675         return 0;
676 }
677
678 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Adaptive ODBC CDR backend",
679         .load = load_module,
680         .unload = unload_module,
681         .reload = reload,
682 );
683