d511544f86e5f11e72cd1f13c007e1ed383a80ae
[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, *encoding = 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                         if (PQsetClientEncoding(conn, encoding)) {
114 #ifdef HAVE_PGSQL_pg_encoding_to_char
115                                 ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
116 #else
117                                 ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default.\n", encoding);
118 #endif
119                         }
120                 } else {
121                         pgerror = PQerrorMessage(conn);
122                         ast_log(LOG_ERROR, "Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
123                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
124                         PQfinish(conn);
125                         conn = NULL;
126                 }
127         }
128
129         if (connected) {
130                 struct columns *cur;
131                 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
132                 char buf[257], escapebuf[513], *value;
133                 int first = 1;
134   
135                 if (!sql || !sql2) {
136                         if (sql) {
137                                 ast_free(sql);
138                         }
139                         if (sql2) {
140                                 ast_free(sql2);
141                         }
142                         return -1;
143                 }
144
145                 ast_str_set(&sql, 0, "INSERT INTO %s (", table);
146                 ast_str_set(&sql2, 0, " VALUES (");
147
148                 AST_RWLIST_RDLOCK(&psql_columns);
149                 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
150                         /* For fields not set, simply skip them */
151                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
152                         if (strcmp(cur->name, "calldate") == 0 && !value) {
153                                 ast_cdr_getvar(cdr, "start", &value, buf, sizeof(buf), 0, 0);
154                         }
155                         if (!value) {
156                                 if (cur->notnull && !cur->hasdefault) {
157                                         /* Field is NOT NULL (but no default), must include it anyway */
158                                         LENGTHEN_BUF1(strlen(cur->name) + 2);
159                                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
160                                         LENGTHEN_BUF2(3);
161                                         ast_str_append(&sql2, 0, "%s''", first ? "" : ",");
162                                         first = 0;
163                                 }
164                                 continue;
165                         }
166
167                         LENGTHEN_BUF1(strlen(cur->name) + 2);
168                         ast_str_append(&sql, 0, "%s\"%s\"", first ? "" : ",", cur->name);
169
170                         if (strcmp(cur->name, "start") == 0 || strcmp(cur->name, "calldate") == 0) {
171                                 if (strncmp(cur->type, "int", 3) == 0) {
172                                         LENGTHEN_BUF2(13);
173                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->start.tv_sec);
174                                 } else if (strncmp(cur->type, "float", 5) == 0) {
175                                         LENGTHEN_BUF2(31);
176                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->start.tv_sec + (double)cdr->start.tv_usec / 1000000.0);
177                                 } else {
178                                         /* char, hopefully */
179                                         LENGTHEN_BUF2(31);
180                                         ast_localtime(&cdr->start, &tm, NULL);
181                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
182                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
183                                 }
184                         } else if (strcmp(cur->name, "answer") == 0) {
185                                 if (strncmp(cur->type, "int", 3) == 0) {
186                                         LENGTHEN_BUF2(13);
187                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->answer.tv_sec);
188                                 } else if (strncmp(cur->type, "float", 5) == 0) {
189                                         LENGTHEN_BUF2(31);
190                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->answer.tv_sec + (double)cdr->answer.tv_usec / 1000000.0);
191                                 } else {
192                                         /* char, hopefully */
193                                         LENGTHEN_BUF2(31);
194                                         ast_localtime(&cdr->start, &tm, NULL);
195                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
196                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
197                                 }
198                         } else if (strcmp(cur->name, "end") == 0) {
199                                 if (strncmp(cur->type, "int", 3) == 0) {
200                                         LENGTHEN_BUF2(13);
201                                         ast_str_append(&sql2, 0, "%s%ld", first ? "" : ",", (long) cdr->end.tv_sec);
202                                 } else if (strncmp(cur->type, "float", 5) == 0) {
203                                         LENGTHEN_BUF2(31);
204                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double)cdr->end.tv_sec + (double)cdr->end.tv_usec / 1000000.0);
205                                 } else {
206                                         /* char, hopefully */
207                                         LENGTHEN_BUF2(31);
208                                         ast_localtime(&cdr->end, &tm, NULL);
209                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
210                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", buf);
211                                 }
212                         } else if (strcmp(cur->name, "duration") == 0 || strcmp(cur->name, "billsec") == 0) {
213                                 if (cur->type[0] == 'i') {
214                                         /* Get integer, no need to escape anything */
215                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
216                                         LENGTHEN_BUF2(13);
217                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
218                                 } else if (strncmp(cur->type, "float", 5) == 0) {
219                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
220                                         LENGTHEN_BUF2(31);
221                                         ast_str_append(&sql2, 0, "%s%f", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
222                                 } else {
223                                         /* Char field, probably */
224                                         struct timeval *when = cur->name[0] == 'd' ? &cdr->start : &cdr->answer;
225                                         LENGTHEN_BUF2(31);
226                                         ast_str_append(&sql2, 0, "%s'%f'", first ? "" : ",", (double) (ast_tvdiff_us(cdr->end, *when) / 1000000.0));
227                                 }
228                         } else if (strcmp(cur->name, "disposition") == 0 || strcmp(cur->name, "amaflags") == 0) {
229                                 if (strncmp(cur->type, "int", 3) == 0) {
230                                         /* Integer, no need to escape anything */
231                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 1);
232                                         LENGTHEN_BUF2(13);
233                                         ast_str_append(&sql2, 0, "%s%s", first ? "" : ",", value);
234                                 } else {
235                                         /* Although this is a char field, there are no special characters in the values for these fields */
236                                         ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
237                                         LENGTHEN_BUF2(31);
238                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", value);
239                                 }
240                         } else {
241                                 /* Arbitrary field, could be anything */
242                                 ast_cdr_getvar(cdr, cur->name, &value, buf, sizeof(buf), 0, 0);
243                                 if (strncmp(cur->type, "int", 3) == 0) {
244                                         long long whatever;
245                                         if (value && sscanf(value, "%30lld", &whatever) == 1) {
246                                                 LENGTHEN_BUF2(26);
247                                                 ast_str_append(&sql2, 0, "%s%lld", first ? "" : ",", whatever);
248                                         } else {
249                                                 LENGTHEN_BUF2(2);
250                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
251                                         }
252                                 } else if (strncmp(cur->type, "float", 5) == 0) {
253                                         long double whatever;
254                                         if (value && sscanf(value, "%30Lf", &whatever) == 1) {
255                                                 LENGTHEN_BUF2(51);
256                                                 ast_str_append(&sql2, 0, "%s%30Lf", first ? "" : ",", whatever);
257                                         } else {
258                                                 LENGTHEN_BUF2(2);
259                                                 ast_str_append(&sql2, 0, "%s0", first ? "" : ",");
260                                         }
261                                 /* XXX Might want to handle dates, times, and other misc fields here XXX */
262                                 } else {
263                                         if (value)
264                                                 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
265                                         else
266                                                 escapebuf[0] = '\0';
267                                         LENGTHEN_BUF2(strlen(escapebuf) + 3);
268                                         ast_str_append(&sql2, 0, "%s'%s'", first ? "" : ",", escapebuf);
269                                 }
270                         }
271                         first = 0;
272                 }
273                 AST_RWLIST_UNLOCK(&psql_columns);
274                 LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
275                 ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
276                 ast_verb(11, "[%s]\n", ast_str_buffer(sql));
277
278                 ast_debug(2, "inserting a CDR record.\n");
279
280                 /* Test to be sure we're still connected... */
281                 /* If we're connected, and connection is working, good. */
282                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
283                 if (PQstatus(conn) == CONNECTION_OK) {
284                         connected = 1;
285                 } else {
286                         ast_log(LOG_ERROR, "Connection was lost... attempting to reconnect.\n");
287                         PQreset(conn);
288                         if (PQstatus(conn) == CONNECTION_OK) {
289                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
290                                 connected = 1;
291                         } else {
292                                 pgerror = PQerrorMessage(conn);
293                                 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
294                                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
295                                 PQfinish(conn);
296                                 conn = NULL;
297                                 connected = 0;
298                                 ast_mutex_unlock(&pgsql_lock);
299                                 ast_free(sql);
300                                 ast_free(sql2);
301                                 return -1;
302                         }
303                 }
304                 result = PQexec(conn, ast_str_buffer(sql));
305                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
306                         pgerror = PQresultErrorMessage(result);
307                         ast_log(LOG_ERROR, "Failed to insert call detail record into database!\n");
308                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
309                         ast_log(LOG_ERROR, "Connection may have been lost... attempting to reconnect.\n");
310                         PQreset(conn);
311                         if (PQstatus(conn) == CONNECTION_OK) {
312                                 ast_log(LOG_ERROR, "Connection reestablished.\n");
313                                 connected = 1;
314                                 PQclear(result);
315                                 result = PQexec(conn, ast_str_buffer(sql));
316                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
317                                         pgerror = PQresultErrorMessage(result);
318                                         ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
319                                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
320                                 }
321                         }
322                         ast_mutex_unlock(&pgsql_lock);
323                         PQclear(result);
324                         ast_free(sql);
325                         ast_free(sql2);
326                         return -1;
327                 }
328                 PQclear(result);
329                 ast_free(sql);
330                 ast_free(sql2);
331         }
332         ast_mutex_unlock(&pgsql_lock);
333         return 0;
334 }
335
336 static int unload_module(void)
337 {
338         struct columns *current;
339
340         ast_cdr_unregister(name);
341
342         PQfinish(conn);
343
344         if (pghostname) {
345                 ast_free(pghostname);
346         }
347         if (pgdbname) {
348                 ast_free(pgdbname);
349         }
350         if (pgdbuser) {
351                 ast_free(pgdbuser);
352         }
353         if (pgpassword) {
354                 ast_free(pgpassword);
355         }
356         if (pgdbport) {
357                 ast_free(pgdbport);
358         }
359         if (table) {
360                 ast_free(table);
361         }
362
363         AST_RWLIST_WRLOCK(&psql_columns);
364         while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
365                 ast_free(current);
366         }
367         AST_RWLIST_UNLOCK(&psql_columns);
368
369         return 0;
370 }
371
372 static int config_module(int reload)
373 {
374         struct ast_variable *var;
375         char *pgerror;
376         struct columns *cur;
377         PGresult *result;
378         const char *tmp;
379         struct ast_config *cfg;
380         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
381
382         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
383                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CDR's: %s\n", config);
384                 return -1;
385         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
386                 return 0;
387         }
388
389         if (!(var = ast_variable_browse(cfg, "global"))) {
390                 ast_config_destroy(cfg);
391                 return 0;
392         }
393
394         if (!(tmp = ast_variable_retrieve(cfg, "global", "hostname"))) {
395                 ast_log(LOG_WARNING, "PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
396                 tmp = "";       /* connect via UNIX-socket by default */
397         }
398
399         if (pghostname) {
400                 ast_free(pghostname);
401         }
402         if (!(pghostname = ast_strdup(tmp))) {
403                 ast_config_destroy(cfg);
404                 return -1;
405         }
406
407         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
408                 ast_log(LOG_WARNING, "PostgreSQL database not specified.  Assuming asterisk\n");
409                 tmp = "asteriskcdrdb";
410         }
411
412         if (pgdbname) {
413                 ast_free(pgdbname);
414         }
415         if (!(pgdbname = ast_strdup(tmp))) {
416                 ast_config_destroy(cfg);
417                 return -1;
418         }
419
420         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
421                 ast_log(LOG_WARNING, "PostgreSQL database user not specified.  Assuming asterisk\n");
422                 tmp = "asterisk";
423         }
424
425         if (pgdbuser) {
426                 ast_free(pgdbuser);
427         }
428         if (!(pgdbuser = ast_strdup(tmp))) {
429                 ast_config_destroy(cfg);
430                 return -1;
431         }
432
433         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
434                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
435                 tmp = "";
436         }
437
438         if (pgpassword) {
439                 ast_free(pgpassword);
440         }
441         if (!(pgpassword = ast_strdup(tmp))) {
442                 ast_config_destroy(cfg);
443                 return -1;
444         }
445
446         if (!(tmp = ast_variable_retrieve(cfg, "global", "port"))) {
447                 ast_log(LOG_WARNING, "PostgreSQL database port not specified.  Using default 5432.\n");
448                 tmp = "5432";
449         }
450
451         if (pgdbport) {
452                 ast_free(pgdbport);
453         }
454         if (!(pgdbport = ast_strdup(tmp))) {
455                 ast_config_destroy(cfg);
456                 return -1;
457         }
458
459         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
460                 ast_log(LOG_WARNING, "CDR table not specified.  Assuming cdr\n");
461                 tmp = "cdr";
462         }
463
464         if (table) {
465                 ast_free(table);
466         }
467         if (!(table = ast_strdup(tmp))) {
468                 ast_config_destroy(cfg);
469                 return -1;
470         }
471
472         if (!(tmp = ast_variable_retrieve(cfg, "global", "encoding"))) {
473                 ast_log(LOG_WARNING, "Encoding not specified.  Assuming LATIN9\n");
474                 tmp = "LATIN9";
475         }
476
477         if (encoding) {
478                 ast_free(encoding);
479         }
480         if (!(encoding = ast_strdup(tmp))) {
481                 ast_config_destroy(cfg);
482                 return -1;
483         }
484
485         if (option_debug) {
486                 if (ast_strlen_zero(pghostname)) {
487                         ast_debug(1, "using default unix socket\n");
488                 } else {
489                         ast_debug(1, "got hostname of %s\n", pghostname);
490                 }
491                 ast_debug(1, "got port of %s\n", pgdbport);
492                 ast_debug(1, "got user of %s\n", pgdbuser);
493                 ast_debug(1, "got dbname of %s\n", pgdbname);
494                 ast_debug(1, "got password of %s\n", pgpassword);
495                 ast_debug(1, "got sql table name of %s\n", table);
496         }
497
498         conn = PQsetdbLogin(pghostname, pgdbport, NULL, NULL, pgdbname, pgdbuser, pgpassword);
499         if (PQstatus(conn) != CONNECTION_BAD) {
500                 char sqlcmd[768];
501                 char *fname, *ftype, *flen, *fnotnull, *fdef;
502                 int i, rows, version;
503                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
504                 connected = 1;
505                 if (PQsetClientEncoding(conn, encoding)) {
506 #ifdef HAVE_PGSQL_pg_encoding_to_char
507                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default '%s'\n", encoding, pg_encoding_to_char(PQclientEncoding(conn)));
508 #else
509                         ast_log(LOG_WARNING, "Failed to set encoding to '%s'.  Encoding set to default.\n", encoding);
510 #endif
511                 }
512                 version = PQserverVersion(conn);
513
514                 if (version >= 70300) {
515                         char *schemaname, *tablename;
516                         if (strchr(table, '.')) {
517                                 schemaname = ast_strdupa(table);
518                                 tablename = strchr(schemaname, '.');
519                                 *tablename++ = '\0';
520                         } else {
521                                 schemaname = "";
522                                 tablename = table;
523                         }
524
525                         /* Escape special characters in schemaname */
526                         if (strchr(schemaname, '\\') || strchr(schemaname, '\'')) {
527                                 char *tmp = schemaname, *ptr;
528
529                                 ptr = schemaname = alloca(strlen(tmp) * 2 + 1);
530                                 for (; *tmp; tmp++) {
531                                         if (strchr("\\'", *tmp)) {
532                                                 *ptr++ = *tmp;
533                                         }
534                                         *ptr++ = *tmp;
535                                 }
536                                 *ptr = '\0';
537                         }
538                         /* Escape special characters in tablename */
539                         if (strchr(tablename, '\\') || strchr(tablename, '\'')) {
540                                 char *tmp = tablename, *ptr;
541
542                                 ptr = tablename = alloca(strlen(tmp) * 2 + 1);
543                                 for (; *tmp; tmp++) {
544                                         if (strchr("\\'", *tmp)) {
545                                                 *ptr++ = *tmp;
546                                         }
547                                         *ptr++ = *tmp;
548                                 }
549                                 *ptr = '\0';
550                         }
551
552                         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",
553                                 tablename,
554                                 ast_strlen_zero(schemaname) ? "" : "'", ast_strlen_zero(schemaname) ? "current_schema()" : schemaname, ast_strlen_zero(schemaname) ? "" : "'");
555                 } else {
556                         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);
557                 }
558                 /* Query the columns */
559                 result = PQexec(conn, sqlcmd);
560                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
561                         pgerror = PQresultErrorMessage(result);
562                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
563                         PQclear(result);
564                         unload_module();
565                         return AST_MODULE_LOAD_DECLINE;
566                 }
567
568                 rows = PQntuples(result);
569                 if (rows == 0) {
570                         ast_log(LOG_ERROR, "cdr_pgsql: Failed to query database columns. No columns found, does the table exist?\n");
571                         PQclear(result);
572                         unload_module();
573                         return AST_MODULE_LOAD_DECLINE;
574                 }
575
576                 for (i = 0; i < rows; i++) {
577                         fname = PQgetvalue(result, i, 0);
578                         ftype = PQgetvalue(result, i, 1);
579                         flen = PQgetvalue(result, i, 2);
580                         fnotnull = PQgetvalue(result, i, 3);
581                         fdef = PQgetvalue(result, i, 4);
582                         if (atoi(flen) == -1) {
583                                 /* For varchar columns, the maximum length is encoded in a different field */
584                                 flen = PQgetvalue(result, i, 5);
585                         }
586                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
587                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
588                         if (cur) {
589                                 sscanf(flen, "%30d", &cur->len);
590                                 cur->name = (char *)cur + sizeof(*cur);
591                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
592                                 strcpy(cur->name, fname);
593                                 strcpy(cur->type, ftype);
594                                 if (*fnotnull == 't') {
595                                         cur->notnull = 1;
596                                 } else {
597                                         cur->notnull = 0;
598                                 }
599                                 if (!ast_strlen_zero(fdef)) {
600                                         cur->hasdefault = 1;
601                                 } else {
602                                         cur->hasdefault = 0;
603                                 }
604                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
605                         }
606                 }
607                 PQclear(result);
608         } else {
609                 pgerror = PQerrorMessage(conn);
610                 ast_log(LOG_ERROR, "Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
611                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
612                 connected = 0;
613         }
614
615         ast_config_destroy(cfg);
616
617         return ast_cdr_register(name, ast_module_info->description, pgsql_log);
618 }
619
620 static int load_module(void)
621 {
622         return config_module(0) ? AST_MODULE_LOAD_DECLINE : 0;
623 }
624
625 static int reload(void)
626 {
627         return config_module(1);
628 }
629
630 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CDR Backend",
631                 .load = load_module,
632                 .unload = unload_module,
633                 .reload = reload,
634                 .load_pri = AST_MODPRI_CDR_DRIVER,
635                );