Merged revisions 279410 via svnmerge from
[asterisk/asterisk.git] / cdr / cdr_pgsql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2003 - 2006
5  *
6  * Matthew D. Hardeman <mhardemn@papersoft.com>
7  * Adapted from the MySQL CDR logger originally by James Sharp
8  *
9  * Modified September 2003
10  * Matthew D. Hardeman <mhardemn@papersoft.com>
11  *
12  * See http://www.asterisk.org for more information about
13  * the Asterisk project. Please do not directly contact
14  * any of the maintainers of this project for assistance;
15  * the project provides a web site, mailing lists and IRC
16  * channels for your use.
17  *
18  * This program is free software, distributed under the terms of
19  * the GNU General Public License Version 2. See the LICENSE file
20  * at the top of the source tree.
21  */
22
23 /*!
24  * \file
25  * \brief PostgreSQL CDR logger
26  *
27  * \author Matthew D. Hardeman <mhardemn@papersoft.com>
28  * \extref PostgreSQL http://www.postgresql.org/
29  *
30  * See also
31  * \arg \ref Config_cdr
32  * \extref PostgreSQL http://www.postgresql.org/
33  * \ingroup cdr_drivers
34  */
35
36 /*** MODULEINFO
37         <depend>pgsql</depend>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include <libpq-fe.h>
45
46 #include "asterisk/config.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/cdr.h"
49 #include "asterisk/module.h"
50
51 #define DATE_FORMAT "'%Y-%m-%d %T'"
52
53 static const char name[] = "pgsql";
54 static const char config[] = "cdr_pgsql.conf";
55 static char *pghostname = NULL, *pgdbname = NULL, *pgdbuser = NULL, *pgpassword = NULL, *pgdbport = NULL, *table = NULL;
56 static int connected = 0;
57 static int maxsize = 512, maxsize2 = 512;
58
59 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
60
61 static PGconn   *conn = NULL;
62
63 struct columns {
64         char *name;
65         char *type;
66         int len;
67         unsigned int notnull:1;
68         unsigned int hasdefault:1;
69         AST_RWLIST_ENTRY(columns) list;
70 };
71
72 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
73
74 #define LENGTHEN_BUF1(size)                                               \
75                         do {                                                          \
76                                 /* Lengthen buffer, if necessary */                       \
77                                 if (ast_str_strlen(sql) + size + 1 > ast_str_size(sql)) { \
78                                         if (ast_str_make_space(&sql, ((ast_str_size(sql) + size + 3) / 512 + 1) * 512) != 0) {  \
79                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR failed.\n"); \
80                                                 ast_free(sql);                                    \
81                                                 ast_free(sql2);                                   \
82                                                 AST_RWLIST_UNLOCK(&psql_columns);                 \
83                                                 return -1;                                        \
84                                         }                                                     \
85                                 }                                                         \
86                         } while (0)
87
88 #define LENGTHEN_BUF2(size)                               \
89                         do {                                          \
90                                 if (ast_str_strlen(sql2) + size + 1 > ast_str_size(sql2)) {  \
91                                         if (ast_str_make_space(&sql2, ((ast_str_size(sql2) + size + 3) / 512 + 1) * 512) != 0) {        \
92                                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CDR failed.\n");      \
93                                                 ast_free(sql);                    \
94                                                 ast_free(sql2);                   \
95                                                 AST_RWLIST_UNLOCK(&psql_columns); \
96                                                 return -1;                        \
97                                         }                                     \
98                                 }                                         \
99                         } while (0)
100
101 static int pgsql_log(struct ast_cdr *cdr)
102 {
103         struct ast_tm tm;
104         char *pgerror;
105         PGresult *result;
106
107         ast_mutex_lock(&pgsql_lock);
108
109         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
110                 conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
111                 if (PQstatus(conn) != CONNECTION_BAD) {
112                         connected = 1;
113                 } else {
114                         pgerror = PQerrorMessage(conn);
115                         ast_log(LOG_ERROR, "Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
116                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
117                         PQfinish(conn);
118                         conn = NULL;
119                 }
120         }
121
122         if (connected) {
123                 struct columns *cur;
124                 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
125                 char buf[257], escapebuf[513], *value;
126                 int first = 1;
127   
128                 if (!sql || !sql2) {
129                         if (sql) {
130                                 ast_free(sql);
131                         }
132                         if (sql2) {
133                                 ast_free(sql2);
134                         }
135                         return -1;
136                 }
137
138                 ast_str_set(&sql, 0, "INSERT INTO %s (", table);
139                 ast_str_set(&sql2, 0, " VALUES (");
140
141                 AST_RWLIST_RDLOCK(&psql_columns);
142                 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
143                         /* For fields not set, simply skip them */
144                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
145                         if (strcmp(cur->name, "calldate") == 0 && !value) {
146                                 ast_cdr_getvar(cdr, "start", &value, buf, sizeof(buf), 0, 0);
147                         }
148                         if (!value) {
149                                 if (cur->notnull && !cur->hasdefault) {
150                                         /* Field is NOT NULL (but no default), must include it anyway */
151                                         LENGTHEN_BUF1(strlen(cur->name) + 2);
152                                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
153                                         LENGTHEN_BUF2(3);
154                                         ast_str_append(&sql2, 0, "%s''", first ? "" : ",");
155                                         first = 0;
156                                 }
157                                 continue;
158                         }
159
160                         LENGTHEN_BUF1(strlen(cur->name) + 2);
161                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
162
163                         if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
164                                 if (strncmp(cur->type, "int", 3) == 0) {
165                                         LENGTHEN_BUF2(13);
166                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->start.tv_sec);
167                                 } else if (strncmp(cur->type, "float", 5) == 0) {
168                                         LENGTHEN_BUF2(31);
169                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
170                                 } else {
171                                         /* char, hopefully */
172                                         LENGTHEN_BUF2(31);
173                                         ast_localtime(&cdr->start, &tm, NULL);
174                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
175                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
176                                 }
177                         } else if (strcmp(cur->name, "answer") == 0) {
178                                 if (strncmp(cur->type, "int", 3) == 0) {
179                                         LENGTHEN_BUF2(13);
180                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->answer.tv_sec);
181                                 } else if (strncmp(cur->type, "float", 5) == 0) {
182                                         LENGTHEN_BUF2(31);
183                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
184                                 } else {
185                                         /* char, hopefully */
186                                         LENGTHEN_BUF2(31);
187                                         ast_localtime(&cdr->start, &tm, NULL);
188                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
189                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
190                                 }
191                         } else if (strcmp(cur->name, "end") == 0) {
192                                 if (strncmp(cur->type, "int", 3) == 0) {
193                                         LENGTHEN_BUF2(13);
194                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->end.tv_sec);
195                                 } else if (strncmp(cur->type, "float", 5) == 0) {
196                                         LENGTHEN_BUF2(31);
197                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
198                                 } else {
199                                         /* char, hopefully */
200                                         LENGTHEN_BUF2(31);
201                                         ast_localtime(&cdr->end, &tm, NULL);
202                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
203                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
204                                 }
205                         } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
206                                 if (cur->type[0] == 'i') {
207                                         /* Get integer, no need to escape anything */
208                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
209                                         LENGTHEN_BUF2(13);
210                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
211                                 } else if (strncmp(cur->type, "float", 5) == 0) {
212                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
213                                         LENGTHEN_BUF2(31);
214                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
215                                 } else {
216                                         /* Char field, probably */
217                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
218                                         LENGTHEN_BUF2(31);
219                                         ast_str_append(&sql2, 0, "%s'%f'", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
220                                 }
221                         } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
222                                 if (strncmp(cur->type, "int", 3) == 0) {
223                                         /* Integer, no need to escape anything */
224                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 1);
225                                         LENGTHEN_BUF2(13);
226                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
227                                 } else {
228                                         /* Although this is a char field, there are no special characters in the values for these fields */
229                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
230                                         LENGTHEN_BUF2(31);
231                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", value);
232                                 }
233                         } else {
234                                 /* Arbitrary field, could be anything */
235                                 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
236                                 if (strncmp(cur->type, "int", 3) == 0) {
237                                         long long whatever;
238                                         if (value && sscanf(value, "%30lld", &whatever) == 1) {
239                                                 LENGTHEN_BUF2(26);
240                                                 ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", whatever);
241                                         } else {
242                                                 LENGTHEN_BUF2(2);
243                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
244                                         }
245                                 } else if (strncmp(cur->type, "float", 5) == 0) {
246                                         long double whatever;
247                                         if (value && sscanf(value, "%30Lf", &whatever) == 1) {
248                                                 LENGTHEN_BUF2(51);
249                                                 ast_str_append(&sql2, 0, "%s%30Lf", first ? "" : ",", whatever);
250                                         } else {
251                                                 LENGTHEN_BUF2(2);
252                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
253                                         }
254                                 /* XXX Might want to handle dates, times, and other misc fields here XXX */
255                                 } else {
256                                         if (value)
257                                                 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
258                                         else
259                                                 escapebuf[0] = '\0';
260                                         LENGTHEN_BUF2(strlen(escapebuf) + 3);
261                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", escapebuf);
262                                 }
263                         }
264                         first = 0;
265                 }
266                 AST_RWLIST_UNLOCK(&psql_columns);
267                 LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
268                 ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
269                 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
270
271                 ast_debug(2, "inserting a CDR record.\n");
272
273                 /* Test to be sure we're still connected... */
274                 /* If we're connected, and connection is working, good. */
275                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
276                 if (PQstatus(conn) == CONNECTION_OK) {
277                         connected = 1;
278                 } else {
279                         ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
280                         PQreset(conn);
281                         if (PQstatus(conn) == CONNECTION_OK) {
282                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
283                                 connected = 1;
284                         } else {
285                                 pgerror = PQerrorMessage(conn);
286                                 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
287                                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
288                                 PQfinish(conn);
289                                 conn = NULL;
290                                 connected = 0;
291                                 ast_mutex_unlock(&pgsql_lock);
292                                 ast_free(sql);
293                                 ast_free(sql2);
294                                 return -1;
295                         }
296                 }
297                 result = PQexec(conn, ast_str_buffer(sql));
298                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
299                         pgerror = PQresultErrorMessage(result);
300                         ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
301                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
302                         ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
303                         PQreset(conn);
304                         if (PQstatus(conn) == CONNECTION_OK) {
305                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
306                                 connected = 1;
307                                 PQclear(result);
308                                 result = PQexec(conn, ast_str_buffer(sql));
309                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
310                                         pgerror = PQresultErrorMessage(result);
311                                         ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
312                                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
313                                 }
314                         }
315                         ast_mutex_unlock(&pgsql_lock);
316                         PQclear(result);
317                         ast_free(sql);
318                         ast_free(sql2);
319                         return -1;
320                 }
321                 PQclear(result);
322                 ast_free(sql);
323                 ast_free(sql2);
324         }
325         ast_mutex_unlock(&pgsql_lock);
326         return 0;
327 }
328
329 static int unload_module(void)
330 {
331         struct columns *current;
332
333         ast_cdr_unregister(name);
334
335         PQfinish(conn);
336
337         if (pghostname)
338                 ast_free(pghostname);
339         if (pgdbname)
340                 ast_free(pgdbname);
341         if (pgdbuser)
342                 ast_free(pgdbuser);
343         if (pgpassword)
344                 ast_free(pgpassword);
345         if (pgdbport)
346                 ast_free(pgdbport);
347         if (table)
348                 ast_free(table);
349
350         AST_RWLIST_WRLOCK(&psql_columns);
351         while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
352                 ast_free(current);
353         }
354         AST_RWLIST_UNLOCK(&psql_columns);
355
356         return 0;
357 }
358
359 static int config_module(int reload)
360 {
361         struct ast_variable *var;
362         char *pgerror;
363         struct columns *cur;
364         PGresult *result;
365         const char *tmp;
366         struct ast_config *cfg;
367         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
368
369         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
370                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
371                 return -1;
372         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
373                 return 0;
374
375         if (!(var = ast_variable_browse(cfg, "global"))) {
376                 ast_config_destroy(cfg);
377                 return 0;
378         }
379
380         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
381                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
382                 tmp = "";       /* connect via UNIX-socket by default */
383         }
384
385         if (pghostname)
386                 ast_free(pghostname);
387         if (!(pghostname = ast_strdup(tmp))) {
388                 ast_config_destroy(cfg);
389                 return -1;
390         }
391
392         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
393                 ast_log(LOG_WARNING, "PostgreSQL database not specified.  Assuming asterisk\n");
394                 tmp = "asteriskcdrdb";
395         }
396
397         if (pgdbname)
398                 ast_free(pgdbname);
399         if (!(pgdbname = ast_strdup(tmp))) {
400                 ast_config_destroy(cfg);
401                 return -1;
402         }
403
404         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
405                 ast_log(LOG_WARNING, "PostgreSQL database user not specified.  Assuming asterisk\n");
406                 tmp = "asterisk";
407         }
408
409         if (pgdbuser)
410                 ast_free(pgdbuser);
411         if (!(pgdbuser = ast_strdup(tmp))) {
412                 ast_config_destroy(cfg);
413                 return -1;
414         }
415
416         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
417                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
418                 tmp = "";
419         }
420
421         if (pgpassword)
422                 ast_free(pgpassword);
423         if (!(pgpassword = ast_strdup(tmp))) {
424                 ast_config_destroy(cfg);
425                 return -1;
426         }
427
428         if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
429                 ast_log(LOG_WARNING, "PostgreSQL database port not specified.  Using default 5432.\n");
430                 tmp = "5432";
431         }
432
433         if (pgdbport)
434                 ast_free(pgdbport);
435         if (!(pgdbport = ast_strdup(tmp))) {
436                 ast_config_destroy(cfg);
437                 return -1;
438         }
439
440         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
441                 ast_log(LOG_WARNING, "CDR table not specified.  Assuming cdr\n");
442                 tmp = "cdr";
443         }
444
445         if (table)
446                 ast_free(table);
447         if (!(table = ast_strdup(tmp))) {
448                 ast_config_destroy(cfg);
449                 return -1;
450         }
451
452         if (option_debug) {
453                 if (ast_strlen_zero(pghostname)) {
454                         ast_debug(1, "using default unix socket\n");
455                 } else {
456                         ast_debug(1, "got hostname of %s\n", pghostname);
457                 }
458                 ast_debug(1, "got port of %s\n", pgdbport);
459                 ast_debug(1, "got user of %s\n", pgdbuser);
460                 ast_debug(1, "got dbname of %s\n", pgdbname);
461                 ast_debug(1, "got password of %s\n", pgpassword);
462                 ast_debug(1, "got sql table name of %s\n", table);
463         }
464
465         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
466         if (PQstatus(conn) != CONNECTION_BAD) {
467                 char sqlcmd[768];
468                 char *fname, *ftype, *flen, *fnotnull, *fdef;
469                 int i, rows, version;
470                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
471                 connected = 1;
472                 version = PQserverVersion(conn);
473
474                 if (version >= 70300) {
475                         char *schemaname, *tablename;
476                         if (strchr(table, '.')) {
477                                 schemaname = ast_strdupa(table);
478                                 tablename = strchr(schemaname, '.');
479                                 *tablename++ = '\0';
480                         } else {
481                                 schemaname = "";
482                                 tablename = table;
483                         }
484
485                         /* Escape special characters in schemaname */
486                         if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
487                                 char *tmp = schemaname, *ptr;
488
489                                 ptr = schemaname = alloca(strlen(tmp) * 2 + 1);
490                                 for (; *tmp; tmp++) {
491                                         if (strchr("\\'", *tmp)) {
492                                                 *ptr++ = *tmp;
493                                         }
494                                         *ptr++ = *tmp;
495                                 }
496                                 *ptr = '\0';
497                         }
498                         /* Escape special characters in tablename */
499                         if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
500                                 char *tmp = tablename, *ptr;
501
502                                 ptr = tablename = alloca(strlen(tmp) * 2 + 1);
503                                 for (; *tmp; tmp++) {
504                                         if (strchr("\\'", *tmp)) {
505                                                 *ptr++ = *tmp;
506                                         }
507                                         *ptr++ = *tmp;
508                                 }
509                                 *ptr = '\0';
510                         }
511
512                         snprintf(sqlcmd, sizeof(sqlcmd), "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM (((pg_catalog.pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND c.relname = '%s' AND n.nspname = %s%s%s) INNER JOIN pg_catalog.pg_attribute a ON (NOT a.attisdropped) AND a.attnum > 0 AND a.attrelid = c.oid) INNER JOIN pg_catalog.pg_type t ON t.oid = a.atttypid) LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum ORDER BY n.nspname, c.relname, attnum",
513                                 tablename,
514                                 ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
515                 } else {
516                         snprintf(sqlcmd, sizeof(sqlcmd), "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod FROM pg_class c, pg_type t, pg_attribute a LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid AND d.adnum = a.attnum WHERE c.oid = a.attrelid AND a.atttypid = t.oid AND (a.attnum > 0) AND c.relname = '%s' ORDER BY c.relname, attnum", table);
517                 }
518                 /* Query the columns */
519                 result = PQexec(conn, sqlcmd);
520                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
521                         pgerror = PQresultErrorMessage(result);
522                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
523                         PQclear(result);
524                         unload_module();
525                         return AST_MODULE_LOAD_DECLINE;
526                 }
527
528                 rows = PQntuples(result);
529                 if (rows == 0) {
530                         ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
531                         PQclear(result);
532                         unload_module();
533                         return AST_MODULE_LOAD_DECLINE;
534                 }
535
536                 for (i = 0; i < rows; i++) {
537                         fname = PQgetvalue(result, i, 0);
538                         ftype = PQgetvalue(result, i, 1);
539                         flen = PQgetvalue(result, i, 2);
540                         fnotnull = PQgetvalue(result, i, 3);
541                         fdef = PQgetvalue(result, i, 4);
542                         if (atoi(flen) == -1) {
543                                 /* For varchar columns, the maximum length is encoded in a different field */
544                                 flen = PQgetvalue(result, i, 5);
545                         }
546                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
547                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
548                         if (cur) {
549                                 sscanf(flen, "%30d", &cur->len);
550                                 cur->name = (char *)cur + sizeof(*cur);
551                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
552                                 strcpy(cur->name, fname);
553                                 strcpy(cur->type, ftype);
554                                 if (*fnotnull == 't') {
555                                         cur->notnull = 1;
556                                 } else {
557                                         cur->notnull = 0;
558                                 }
559                                 if (!ast_strlen_zero(fdef)) {
560                                         cur->hasdefault = 1;
561                                 } else {
562                                         cur->hasdefault = 0;
563                                 }
564                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
565                         }
566                 }
567                 PQclear(result);
568         } else {
569                 pgerror = PQerrorMessage(conn);
570                 ast_log(LOG_ERROR, "Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
571                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
572                 connected = 0;
573         }
574
575         ast_config_destroy(cfg);
576
577         return ast_cdr_register(name, ast_module_info->description, pgsql_log);
578 }
579
580 static int load_module(void)
581 {
582         return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
583 }
584
585 static int reload(void)
586 {
587         return config_module(1);
588 }
589
590 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
591                 .load = load_module,
592                 .unload = unload_module,
593                 .reload = reload,
594                 .load_pri = AST_MODPRI_CDR_DRIVER,
595                );