Merge "rtp_engine.h: Remove extraneous semicolons."
[asterisk/asterisk.git] / cel / cel_pgsql.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2008
5  *
6  * Steve Murphy - adapted to CEL, from:
7  * Matthew D. Hardeman <mhardemn@papersoft.com>
8  * Adapted from the MySQL CDR logger originally by James Sharp
9  *
10  * Modified April, 2007; Dec, 2008
11  * Steve Murphy <murf@digium.com>
12
13  * Modified September 2003
14  * Matthew D. Hardeman <mhardemn@papersoft.com>
15  *
16  * See http://www.asterisk.org for more information about
17  * the Asterisk project. Please do not directly contact
18  * any of the maintainers of this project for assistance;
19  * the project provides a web site, mailing lists and IRC
20  * channels for your use.
21  *
22  * This program is free software, distributed under the terms of
23  * the GNU General Public License Version 2. See the LICENSE file
24  * at the top of the source tree.
25  */
26
27 /*! \file
28  *
29  * \brief PostgreSQL CEL logger
30  *
31  * \author Steve Murphy <murf@digium.com>
32  * PostgreSQL http://www.postgresql.org/
33  *
34  * See also
35  * \arg \ref Config_cel
36  * PostgreSQL http://www.postgresql.org/
37  * \ingroup cel_drivers
38  */
39
40 /*** MODULEINFO
41         <depend>pgsql</depend>
42         <support_level>extended</support_level>
43  ***/
44
45 #include "asterisk.h"
46
47 ASTERISK_REGISTER_FILE()
48
49 #include <libpq-fe.h>
50
51 #include "asterisk/config.h"
52 #include "asterisk/options.h"
53 #include "asterisk/channel.h"
54 #include "asterisk/cel.h"
55 #include "asterisk/module.h"
56 #include "asterisk/logger.h"
57 #include "asterisk.h"
58
59 #define DATE_FORMAT "%Y-%m-%d %T.%6q"
60
61 #define PGSQL_BACKEND_NAME "CEL PGSQL backend"
62
63 #define PGSQL_MIN_VERSION_SCHEMA 70300
64
65 static char *config = "cel_pgsql.conf";
66
67 static char *pghostname;
68 static char *pgdbname;
69 static char *pgdbuser;
70 static char *pgpassword;
71 static char *pgappname;
72 static char *pgdbport;
73 static char *table;
74 static char *schema;
75
76 static int connected = 0;
77 /* Optimization to reduce number of memory allocations */
78 static int maxsize = 512, maxsize2 = 512;
79 static int usegmtime = 0;
80
81 /*! \brief show_user_def is off by default */
82 #define CEL_SHOW_USERDEF_DEFAULT        0
83
84 /*! TRUE if we should set the eventtype field to USER_DEFINED on user events. */
85 static unsigned char cel_show_user_def;
86
87 AST_MUTEX_DEFINE_STATIC(pgsql_lock);
88
89 static PGconn   *conn = NULL;
90 static PGresult *result = NULL;
91
92 struct columns {
93         char *name;
94         char *type;
95         int len;
96         unsigned int notnull:1;
97         unsigned int hasdefault:1;
98         AST_RWLIST_ENTRY(columns) list;
99 };
100
101 static AST_RWLIST_HEAD_STATIC(psql_columns, columns);
102
103 #define LENGTHEN_BUF(size, var_sql) \
104         do { \
105                 /* Lengthen buffer, if necessary */ \
106                 if (ast_str_strlen(var_sql) + size + 1 > ast_str_size(var_sql)) { \
107                         if (ast_str_make_space(&var_sql, ((ast_str_size(var_sql) + size + 3) / 512 + 1) * 512) != 0) { \
108                                 ast_log(LOG_ERROR, "Unable to allocate sufficient memory.  Insert CEL '%s:%s' failed.\n", pghostname, table); \
109                                 ast_free(sql); \
110                                 ast_free(sql2); \
111                                 AST_RWLIST_UNLOCK(&psql_columns); \
112                                 return; \
113                         } \
114                 } \
115         } while (0)
116
117 #define LENGTHEN_BUF1(size) \
118         LENGTHEN_BUF(size, sql);
119 #define LENGTHEN_BUF2(size) \
120         LENGTHEN_BUF(size, sql2);
121
122 static void pgsql_reconnect(void)
123 {
124         struct ast_str *conn_info = ast_str_create(128);
125         if (!conn_info) {
126                 ast_log(LOG_ERROR, "Failed to allocate memory for connection string.\n");
127                 return;
128         }
129
130         if (conn) {
131                 PQfinish(conn);
132                 conn = NULL;
133         }
134
135         ast_str_set(&conn_info, 0, "host=%s port=%s dbname=%s user=%s",
136                 pghostname, pgdbport, pgdbname, pgdbuser);
137
138         if (!ast_strlen_zero(pgappname)) {
139                 ast_str_append(&conn_info, 0, " application_name=%s", pgappname);
140         }
141
142         if (!ast_strlen_zero(pgpassword)) {
143                 ast_str_append(&conn_info, 0, " password=%s", pgpassword);
144         }
145
146         conn = PQconnectdb(ast_str_buffer(conn_info));
147         ast_free(conn_info);
148 }
149
150
151 static void pgsql_log(struct ast_event *event)
152 {
153         struct ast_tm tm;
154         char timestr[128];
155         char *pgerror;
156         struct ast_cel_event_record record = {
157                 .version = AST_CEL_EVENT_RECORD_VERSION,
158         };
159
160         if (ast_cel_fill_record(event, &record)) {
161                 return;
162         }
163
164         ast_mutex_lock(&pgsql_lock);
165
166         ast_localtime(&record.event_time, &tm, usegmtime ? "GMT" : NULL);
167         ast_strftime(timestr, sizeof(timestr), DATE_FORMAT, &tm);
168
169         if ((!connected) && pghostname && pgdbuser && pgpassword && pgdbname) {
170                 pgsql_reconnect();
171                 if (PQstatus(conn) != CONNECTION_BAD) {
172                         connected = 1;
173                 } else {
174                         pgerror = PQerrorMessage(conn);
175                         ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s.  Calls will not be logged!\n", pghostname);
176                         ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
177                         PQfinish(conn);
178                         conn = NULL;
179                 }
180         }
181         if (connected) {
182                 struct columns *cur;
183                 struct ast_str *sql = ast_str_create(maxsize), *sql2 = ast_str_create(maxsize2);
184                 char buf[257], escapebuf[513];
185                 const char *value;
186                 int first = 1;
187
188                 if (!sql || !sql2) {
189                         goto ast_log_cleanup;
190                 }
191
192                 ast_str_set(&sql, 0, "INSERT INTO %s (", table);
193                 ast_str_set(&sql2, 0, " VALUES (");
194
195 #define SEP (first ? "" : ",")
196
197                 AST_RWLIST_RDLOCK(&psql_columns);
198                 AST_RWLIST_TRAVERSE(&psql_columns, cur, list) {
199                         LENGTHEN_BUF1(strlen(cur->name) + 2);
200                         ast_str_append(&sql, 0, "%s\"%s\"", SEP, cur->name);
201
202                         if (strcmp(cur->name, "eventtime") == 0) {
203                                 if (strncmp(cur->type, "int", 3) == 0) {
204                                         LENGTHEN_BUF2(13);
205                                         ast_str_append(&sql2, 0, "%s%ld", SEP, (long) record.event_time.tv_sec);
206                                 } else if (strncmp(cur->type, "float", 5) == 0) {
207                                         LENGTHEN_BUF2(31);
208                                         ast_str_append(&sql2, 0, "%s%f",
209                                                 SEP,
210                                                 (double) record.event_time.tv_sec +
211                                                 (double) record.event_time.tv_usec / 1000000.0);
212                                 } else {
213                                         /* char, hopefully */
214                                         LENGTHEN_BUF2(31);
215                                         ast_localtime(&record.event_time, &tm, usegmtime ? "GMT" : NULL);
216                                         ast_strftime(buf, sizeof(buf), DATE_FORMAT, &tm);
217                                         ast_str_append(&sql2, 0, "%s'%s'", SEP, buf);
218                                 }
219                         } else if (strcmp(cur->name, "eventtype") == 0) {
220                                 if (cur->type[0] == 'i') {
221                                         /* Get integer, no need to escape anything */
222                                         LENGTHEN_BUF2(5);
223                                         ast_str_append(&sql2, 0, "%s%d", SEP, (int) record.event_type);
224                                 } else if (strncmp(cur->type, "float", 5) == 0) {
225                                         LENGTHEN_BUF2(31);
226                                         ast_str_append(&sql2, 0, "%s%f", SEP, (double) record.event_type);
227                                 } else {
228                                         /* Char field, probably */
229                                         const char *event_name;
230
231                                         event_name = (!cel_show_user_def
232                                                 && record.event_type == AST_CEL_USER_DEFINED)
233                                                 ? record.user_defined_name : record.event_name;
234                                         LENGTHEN_BUF2(strlen(event_name) + 1);
235                                         ast_str_append(&sql2, 0, "%s'%s'", SEP, event_name);
236                                 }
237                         } else if (strcmp(cur->name, "amaflags") == 0) {
238                                 if (strncmp(cur->type, "int", 3) == 0) {
239                                         /* Integer, no need to escape anything */
240                                         LENGTHEN_BUF2(13);
241                                         ast_str_append(&sql2, 0, "%s%u", SEP, record.amaflag);
242                                 } else {
243                                         /* Although this is a char field, there are no special characters in the values for these fields */
244                                         LENGTHEN_BUF2(31);
245                                         ast_str_append(&sql2, 0, "%s'%u'", SEP, record.amaflag);
246                                 }
247                         } else {
248                                 /* Arbitrary field, could be anything */
249                                 if (strcmp(cur->name, "userdeftype") == 0) {
250                                         value = record.user_defined_name;
251                                 } else if (strcmp(cur->name, "cid_name") == 0) {
252                                         value = record.caller_id_name;
253                                 } else if (strcmp(cur->name, "cid_num") == 0) {
254                                         value = record.caller_id_num;
255                                 } else if (strcmp(cur->name, "cid_ani") == 0) {
256                                         value = record.caller_id_ani;
257                                 } else if (strcmp(cur->name, "cid_rdnis") == 0) {
258                                         value = record.caller_id_rdnis;
259                                 } else if (strcmp(cur->name, "cid_dnid") == 0) {
260                                         value = record.caller_id_dnid;
261                                 } else if (strcmp(cur->name, "exten") == 0) {
262                                         value = record.extension;
263                                 } else if (strcmp(cur->name, "context") == 0) {
264                                         value = record.context;
265                                 } else if (strcmp(cur->name, "channame") == 0) {
266                                         value = record.channel_name;
267                                 } else if (strcmp(cur->name, "appname") == 0) {
268                                         value = record.application_name;
269                                 } else if (strcmp(cur->name, "appdata") == 0) {
270                                         value = record.application_data;
271                                 } else if (strcmp(cur->name, "accountcode") == 0) {
272                                         value = record.account_code;
273                                 } else if (strcmp(cur->name, "peeraccount") == 0) {
274                                         value = record.peer_account;
275                                 } else if (strcmp(cur->name, "uniqueid") == 0) {
276                                         value = record.unique_id;
277                                 } else if (strcmp(cur->name, "linkedid") == 0) {
278                                         value = record.linked_id;
279                                 } else if (strcmp(cur->name, "userfield") == 0) {
280                                         value = record.user_field;
281                                 } else if (strcmp(cur->name, "peer") == 0) {
282                                         value = record.peer;
283                                 } else if (strcmp(cur->name, "extra") == 0) {
284                                         value = record.extra;
285                                 } else {
286                                         value = NULL;
287                                 }
288
289                                 if (value == NULL) {
290                                         ast_str_append(&sql2, 0, "%sDEFAULT", SEP);
291                                 } else if (strncmp(cur->type, "int", 3) == 0) {
292                                         long long whatever;
293                                         if (value && sscanf(value, "%30lld", &whatever) == 1) {
294                                                 LENGTHEN_BUF2(26);
295                                                 ast_str_append(&sql2, 0, "%s%lld", SEP, whatever);
296                                         } else {
297                                                 LENGTHEN_BUF2(2);
298                                                 ast_str_append(&sql2, 0, "%s0", SEP);
299                                         }
300                                 } else if (strncmp(cur->type, "float", 5) == 0) {
301                                         long double whatever;
302                                         if (value && sscanf(value, "%30Lf", &whatever) == 1) {
303                                                 LENGTHEN_BUF2(51);
304                                                 ast_str_append(&sql2, 0, "%s%30Lf", SEP, whatever);
305                                         } else {
306                                                 LENGTHEN_BUF2(2);
307                                                 ast_str_append(&sql2, 0, "%s0", SEP);
308                                         }
309                                         /* XXX Might want to handle dates, times, and other misc fields here XXX */
310                                 } else {
311                                         if (value) {
312                                                 PQescapeStringConn(conn, escapebuf, value, strlen(value), NULL);
313                                         } else {
314                                                 escapebuf[0] = '\0';
315                                         }
316                                         LENGTHEN_BUF2(strlen(escapebuf) + 3);
317                                         ast_str_append(&sql2, 0, "%s'%s'", SEP, escapebuf);
318                                 }
319                         }
320                         first = 0;
321                 }
322                 AST_RWLIST_UNLOCK(&psql_columns);
323                 LENGTHEN_BUF1(ast_str_strlen(sql2) + 2);
324                 ast_str_append(&sql, 0, ")%s)", ast_str_buffer(sql2));
325
326                 ast_debug(3, "Inserting a CEL record: [%s].\n", ast_str_buffer(sql));
327                 /* Test to be sure we're still connected... */
328                 /* If we're connected, and connection is working, good. */
329                 /* Otherwise, attempt reconnect.  If it fails... sorry... */
330                 if (PQstatus(conn) == CONNECTION_OK) {
331                         connected = 1;
332                 } else {
333                         ast_log(LOG_WARNING, "Connection was lost... attempting to reconnect.\n");
334                         PQreset(conn);
335                         if (PQstatus(conn) == CONNECTION_OK) {
336                                 ast_log(LOG_NOTICE, "Connection reestablished.\n");
337                                 connected = 1;
338                         } else {
339                                 pgerror = PQerrorMessage(conn);
340                                 ast_log(LOG_ERROR, "Unable to reconnect to database server %s. Calls will not be logged!\n", pghostname);
341                                 ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
342                                 PQfinish(conn);
343                                 conn = NULL;
344                                 connected = 0;
345                                 goto ast_log_cleanup;
346                         }
347                 }
348                 result = PQexec(conn, ast_str_buffer(sql));
349                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
350                         pgerror = PQresultErrorMessage(result);
351                         ast_log(LOG_WARNING, "Failed to insert call detail record into database!\n");
352                         ast_log(LOG_WARNING, "Reason: %s\n", pgerror);
353                         ast_log(LOG_WARNING, "Connection may have been lost... attempting to reconnect.\n");
354                         PQreset(conn);
355                         if (PQstatus(conn) == CONNECTION_OK) {
356                                 ast_log(LOG_NOTICE, "Connection reestablished.\n");
357                                 connected = 1;
358                                 PQclear(result);
359                                 result = PQexec(conn, ast_str_buffer(sql));
360                                 if (PQresultStatus(result) != PGRES_COMMAND_OK) {
361                                         pgerror = PQresultErrorMessage(result);
362                                         ast_log(LOG_ERROR, "HARD ERROR!  Attempted reconnection failed.  DROPPING CALL RECORD!\n");
363                                         ast_log(LOG_ERROR, "Reason: %s\n", pgerror);
364                                 }
365                         }
366                         PQclear(result);
367                         goto ast_log_cleanup;
368                 }
369                 PQclear(result);
370
371                 /* Next time, just allocate buffers that are that big to start with. */
372                 if (ast_str_strlen(sql) > maxsize) {
373                         maxsize = ast_str_strlen(sql);
374                 }
375                 if (ast_str_strlen(sql2) > maxsize2) {
376                         maxsize2 = ast_str_strlen(sql2);
377                 }
378
379 ast_log_cleanup:
380                 ast_free(sql);
381                 ast_free(sql2);
382         }
383
384         ast_mutex_unlock(&pgsql_lock);
385 }
386
387 static int my_unload_module(void)
388 {
389         struct columns *current;
390
391         ast_cel_backend_unregister(PGSQL_BACKEND_NAME);
392         AST_RWLIST_WRLOCK(&psql_columns);
393         if (conn) {
394                 PQfinish(conn);
395                 conn = NULL;
396         }
397         if (pghostname) {
398                 ast_free(pghostname);
399                 pghostname = NULL;
400         }
401         if (pgdbname) {
402                 ast_free(pgdbname);
403                 pgdbname = NULL;
404         }
405         if (pgdbuser) {
406                 ast_free(pgdbuser);
407                 pgdbuser = NULL;
408         }
409         if (pgpassword) {
410                 ast_free(pgpassword);
411                 pgpassword = NULL;
412         }
413         if (pgappname) {
414                 ast_free(pgappname);
415                 pgappname = NULL;
416         }
417         if (pgdbport) {
418                 ast_free(pgdbport);
419                 pgdbport = NULL;
420         }
421         if (table) {
422                 ast_free(table);
423                 table = NULL;
424         }
425         if (schema) {
426                 ast_free(schema);
427                 schema = NULL;
428         }
429         while ((current = AST_RWLIST_REMOVE_HEAD(&psql_columns, list))) {
430                 ast_free(current);
431         }
432         AST_RWLIST_UNLOCK(&psql_columns);
433         return 0;
434 }
435
436 static int unload_module(void)
437 {
438         return my_unload_module();
439 }
440
441 static int process_my_load_module(struct ast_config *cfg)
442 {
443         struct ast_variable *var;
444         char *pgerror;
445         const char *tmp;
446         PGresult *result;
447         struct columns *cur;
448
449         if (!(var = ast_variable_browse(cfg, "global"))) {
450                 ast_log(LOG_WARNING,"CEL pgsql config file missing global section.\n");
451                 return AST_MODULE_LOAD_DECLINE;
452         }
453         if (!(tmp = ast_variable_retrieve(cfg,"global","hostname"))) {
454                 ast_log(LOG_WARNING,"PostgreSQL server hostname not specified.  Assuming unix socket connection\n");
455                 tmp = "";       /* connect via UNIX-socket by default */
456         }
457         if (pghostname)
458                 ast_free(pghostname);
459         if (!(pghostname = ast_strdup(tmp))) {
460                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying host info\n");
461                 return AST_MODULE_LOAD_DECLINE;
462         }
463         if (!(tmp = ast_variable_retrieve(cfg, "global", "dbname"))) {
464                 ast_log(LOG_WARNING,"PostgreSQL database not specified.  Assuming asterisk\n");
465                 tmp = "asteriskceldb";
466         }
467         if (pgdbname)
468                 ast_free(pgdbname);
469         if (!(pgdbname = ast_strdup(tmp))) {
470                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying dbname info\n");
471                 return AST_MODULE_LOAD_DECLINE;
472         }
473         if (!(tmp = ast_variable_retrieve(cfg, "global", "user"))) {
474                 ast_log(LOG_WARNING,"PostgreSQL database user not specified.  Assuming asterisk\n");
475                 tmp = "asterisk";
476         }
477         if (pgdbuser)
478                 ast_free(pgdbuser);
479         if (!(pgdbuser = ast_strdup(tmp))) {
480                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying user info\n");
481                 return AST_MODULE_LOAD_DECLINE;
482         }
483         if (!(tmp = ast_variable_retrieve(cfg, "global", "password"))) {
484                 ast_log(LOG_WARNING, "PostgreSQL database password not specified.  Assuming blank\n");
485                 tmp = "";
486         }
487         if (pgpassword)
488                 ast_free(pgpassword);
489         if (!(pgpassword = ast_strdup(tmp))) {
490                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying password info\n");
491                 return AST_MODULE_LOAD_DECLINE;
492         }
493         if (!(tmp = ast_variable_retrieve(cfg, "global", "appname"))) {
494                 tmp = "";
495         }
496         if (pgappname) {
497                 ast_free(pgappname);
498         }
499         if (!(pgappname = ast_strdup(tmp))) {
500                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying appname info\n");
501                 return AST_MODULE_LOAD_DECLINE;
502         }
503
504         if (!(tmp = ast_variable_retrieve(cfg,"global","port"))) {
505                 ast_log(LOG_WARNING,"PostgreSQL database port not specified.  Using default 5432.\n");
506                 tmp = "5432";
507         }
508         if (pgdbport)
509                 ast_free(pgdbport);
510         if (!(pgdbport = ast_strdup(tmp))) {
511                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying port info\n");
512                 return AST_MODULE_LOAD_DECLINE;
513         }
514         if (!(tmp = ast_variable_retrieve(cfg, "global", "table"))) {
515                 ast_log(LOG_WARNING,"CEL table not specified.  Assuming cel\n");
516                 tmp = "cel";
517         }
518         if (table)
519                 ast_free(table);
520         if (!(table = ast_strdup(tmp))) {
521                 return AST_MODULE_LOAD_DECLINE;
522         }
523         cel_show_user_def = CEL_SHOW_USERDEF_DEFAULT;
524         if ((tmp = ast_variable_retrieve(cfg, "global", "show_user_defined"))) {
525                 cel_show_user_def = ast_true(tmp) ? 1 : 0;
526         }
527         if ((tmp = ast_variable_retrieve(cfg, "global", "usegmtime"))) {
528                 usegmtime = ast_true(tmp);
529         } else {
530                 usegmtime = 0;
531         }
532         if (!(tmp = ast_variable_retrieve(cfg, "global", "schema"))) {
533                 tmp = "";
534         }
535         if (schema) {
536                 ast_free(schema);
537         }
538         if (!(schema = ast_strdup(tmp))) {
539                 ast_log(LOG_WARNING,"PostgreSQL Ran out of memory copying schema info\n");
540                 return AST_MODULE_LOAD_DECLINE;
541         }
542         if (option_debug) {
543                 if (ast_strlen_zero(pghostname)) {
544                         ast_debug(3, "cel_pgsql: using default unix socket\n");
545                 } else {
546                         ast_debug(3, "cel_pgsql: got hostname of %s\n", pghostname);
547                 }
548                 ast_debug(3, "cel_pgsql: got port of %s\n", pgdbport);
549                 ast_debug(3, "cel_pgsql: got user of %s\n", pgdbuser);
550                 ast_debug(3, "cel_pgsql: got dbname of %s\n", pgdbname);
551                 ast_debug(3, "cel_pgsql: got password of %s\n", pgpassword);
552                 ast_debug(3, "cel_pgsql: got sql table name of %s\n", table);
553                 ast_debug(3, "cel_pgsql: got show_user_defined of %s\n",
554                         cel_show_user_def ? "Yes" : "No");
555         }
556
557         pgsql_reconnect();
558         if (PQstatus(conn) != CONNECTION_BAD) {
559                 char sqlcmd[768];
560                 char *fname, *ftype, *flen, *fnotnull, *fdef, *tablename, *tmp_tablename;
561                 int i, rows, version;
562
563                 ast_debug(1, "Successfully connected to PostgreSQL database.\n");
564                 connected = 1;
565
566                 version = PQserverVersion(conn);
567                 /* Remove any schema name from the table */
568                 if ((tmp_tablename = strrchr(table, '.'))) {
569                         tmp_tablename++;
570                 } else {
571                         tmp_tablename = table;
572                 }
573                 tablename = ast_alloca(strlen(tmp_tablename) * 2 + 1);
574                 PQescapeStringConn(conn, tablename, tmp_tablename, strlen(tmp_tablename), NULL);
575                 if (version >= PGSQL_MIN_VERSION_SCHEMA) {
576                         char *schemaname;
577                         int lenschema;
578                         lenschema = strlen(schema);
579                         schemaname = ast_alloca(lenschema * 2 + 1);
580                         PQescapeStringConn(conn, schemaname, schema, lenschema, NULL);
581
582                         snprintf(sqlcmd, sizeof(sqlcmd),
583                         "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod "
584                         "FROM (((pg_catalog.pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
585                                  "AND c.relname = '%s' AND n.nspname = %s%s%s) "
586                                "INNER JOIN pg_catalog.pg_attribute a ON ("
587                                    "NOT a.attisdropped) AND a.attnum > 0 AND a.attrelid = c.oid) "
588                             "INNER JOIN pg_catalog.pg_type t ON t.oid = a.atttypid) "
589                         "LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid "
590                           "AND d.adnum = a.attnum "
591                         "ORDER BY n.nspname, c.relname, attnum",
592                                 tablename,
593                                 lenschema == 0 ? "" : "'", lenschema == 0 ? "current_schema()" : schemaname, lenschema == 0 ? "" : "'");
594                 } else {
595                         snprintf(sqlcmd, sizeof(sqlcmd),
596                         "SELECT a.attname, t.typname, a.attlen, a.attnotnull, d.adsrc, a.atttypmod "
597                         "FROM pg_class c, pg_type t, pg_attribute a "
598                         "LEFT OUTER JOIN pg_attrdef d ON a.atthasdef AND d.adrelid = a.attrelid "
599                         "AND d.adnum = a.attnum WHERE c.oid = a.attrelid AND a.atttypid = t.oid "
600                         "AND (a.attnum > 0) AND c.relname = '%s' ORDER BY c.relname, attnum", tablename);
601                 }
602                 /* Query the columns */
603                 result = PQexec(conn, sqlcmd);
604                 if (PQresultStatus(result) != PGRES_TUPLES_OK) {
605                         pgerror = PQresultErrorMessage(result);
606                         ast_log(LOG_ERROR, "Failed to query database columns: %s\n", pgerror);
607                         PQclear(result);
608                         unload_module();
609                         return AST_MODULE_LOAD_DECLINE;
610                 }
611
612                 rows = PQntuples(result);
613                 for (i = 0; i < rows; i++) {
614                         fname = PQgetvalue(result, i, 0);
615                         ftype = PQgetvalue(result, i, 1);
616                         flen = PQgetvalue(result, i, 2);
617                         fnotnull = PQgetvalue(result, i, 3);
618                         fdef = PQgetvalue(result, i, 4);
619                         ast_verb(4, "Found column '%s' of type '%s'\n", fname, ftype);
620                         cur = ast_calloc(1, sizeof(*cur) + strlen(fname) + strlen(ftype) + 2);
621                         if (cur) {
622                                 sscanf(flen, "%30d", &cur->len);
623                                 cur->name = (char *)cur + sizeof(*cur);
624                                 cur->type = (char *)cur + sizeof(*cur) + strlen(fname) + 1;
625                                 strcpy(cur->name, fname);
626                                 strcpy(cur->type, ftype);
627                                 if (*fnotnull == 't') {
628                                         cur->notnull = 1;
629                                 } else {
630                                         cur->notnull = 0;
631                                 }
632                                 if (!ast_strlen_zero(fdef)) {
633                                         cur->hasdefault = 1;
634                                 } else {
635                                         cur->hasdefault = 0;
636                                 }
637                                 AST_RWLIST_INSERT_TAIL(&psql_columns, cur, list);
638                         }
639                 }
640                 PQclear(result);
641         } else {
642                 pgerror = PQerrorMessage(conn);
643                 ast_log(LOG_ERROR, "cel_pgsql: Unable to connect to database server %s.  CALLS WILL NOT BE LOGGED!!\n", pghostname);
644                 ast_log(LOG_ERROR, "cel_pgsql: Reason: %s\n", pgerror);
645                 connected = 0;
646                 PQfinish(conn);
647                 conn = NULL;
648         }
649         return AST_MODULE_LOAD_SUCCESS;
650 }
651
652 static int my_load_module(int reload)
653 {
654         struct ast_config *cfg;
655         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
656
657         if ((cfg = ast_config_load(config, config_flags)) == NULL || cfg == CONFIG_STATUS_FILEINVALID) {
658                 ast_log(LOG_WARNING, "Unable to load config for PostgreSQL CEL's: %s\n", config);
659                 return AST_MODULE_LOAD_DECLINE;
660         } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
661                 return AST_MODULE_LOAD_SUCCESS;
662         }
663
664         if (reload) {
665                 my_unload_module();
666         }
667
668         process_my_load_module(cfg);
669         ast_config_destroy(cfg);
670
671         if (ast_cel_backend_register(PGSQL_BACKEND_NAME, pgsql_log)) {
672                 ast_log(LOG_WARNING, "Unable to subscribe to CEL events for pgsql\n");
673                 return AST_MODULE_LOAD_DECLINE;
674         }
675
676         return AST_MODULE_LOAD_SUCCESS;
677 }
678
679 static int load_module(void)
680 {
681         return my_load_module(0);
682 }
683
684 static int reload(void)
685 {
686         return my_load_module(1);
687 }
688
689 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PostgreSQL CEL Backend",
690         .support_level = AST_MODULE_SUPPORT_EXTENDED,
691         .load = load_module,
692         .unload = unload_module,
693         .reload = reload,
694         .load_pri = AST_MODPRI_CDR_DRIVER,
695 );