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