Ver Fonte

db_postgres: clang format of the code

Daniel-Constantin Mierla há 8 anos atrás
pai
commit
60f177bf04

+ 35 - 37
src/modules/db_postgres/db_postgres.c

@@ -14,8 +14,8 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
- * You should have received a copy of the GNU General Public License 
- * along with this program; if not, write to the Free Software 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
@@ -46,26 +46,24 @@
  * PostgreSQL database module interface
  */
 
-static kam_cmd_export_t cmds[]={
-	{"db_bind_api",     (cmd_function)db_postgres_bind_api,     0, 0, 0, 0},
-	{0,0,0,0,0,0}
+static kam_cmd_export_t cmds[] = {
+	{"db_bind_api", (cmd_function)db_postgres_bind_api, 0, 0, 0, 0},
+	{0, 0, 0, 0, 0, 0}
 };
 
 
-
 struct kam_module_exports kam_exports = {
-	"db_postgres",
-	DEFAULT_DLFLAGS, /* dlopen flags */
-	cmds,
-	0,        /*  module parameters */
-	0,        /* exported statistics */
-	0,        /* exported MI functions */
-	0,        /* exported pseudo-variables */
-	0,        /* extra processes */
-	km_postgres_mod_init, /* module initialization function */
-	0,        /* response function*/
-	0,        /* destroy function */
-	0         /* per-child init function */
+	"db_postgres", DEFAULT_DLFLAGS, /* dlopen flags */
+	cmds,							/* module functions */
+	0,								/* module parameters */
+	0,								/* exported statistics */
+	0,								/* exported MI functions */
+	0,								/* exported pseudo-variables */
+	0,								/* extra processes */
+	km_postgres_mod_init,			/* module initialization function */
+	0,								/* response function*/
+	0,								/* destroy function */
+	0								/* per-child init function */
 };
 
 
@@ -76,29 +74,29 @@ int km_postgres_mod_init(void)
 
 int db_postgres_bind_api(db_func_t *dbb)
 {
-	if(dbb==NULL)
+	if(dbb == NULL)
 		return -1;
 
 	memset(dbb, 0, sizeof(db_func_t));
 
-	dbb->use_table        = db_postgres_use_table;
-	dbb->init             = db_postgres_init;
-	dbb->init2            = db_postgres_init2;
-	dbb->close            = db_postgres_close;
-	dbb->query            = db_postgres_query;
-	dbb->fetch_result     = db_postgres_fetch_result;
-	dbb->raw_query        = db_postgres_raw_query;
-	dbb->free_result      = db_postgres_free_result;
-	dbb->insert           = db_postgres_insert;
-	dbb->insert_update    = db_postgres_insert_update;
-	dbb->delete           = db_postgres_delete; 
-	dbb->update           = db_postgres_update;
-	dbb->replace          = db_postgres_replace;
-	dbb->affected_rows    = db_postgres_affected_rows;
-	dbb->start_transaction= db_postgres_start_transaction;
-	dbb->end_transaction  = db_postgres_end_transaction;
-	dbb->abort_transaction= db_postgres_abort_transaction;
-	dbb->query_lock       = db_postgres_query_lock;
+	dbb->use_table = db_postgres_use_table;
+	dbb->init = db_postgres_init;
+	dbb->init2 = db_postgres_init2;
+	dbb->close = db_postgres_close;
+	dbb->query = db_postgres_query;
+	dbb->fetch_result = db_postgres_fetch_result;
+	dbb->raw_query = db_postgres_raw_query;
+	dbb->free_result = db_postgres_free_result;
+	dbb->insert = db_postgres_insert;
+	dbb->insert_update = db_postgres_insert_update;
+	dbb->delete = db_postgres_delete;
+	dbb->update = db_postgres_update;
+	dbb->replace = db_postgres_replace;
+	dbb->affected_rows = db_postgres_affected_rows;
+	dbb->start_transaction = db_postgres_start_transaction;
+	dbb->end_transaction = db_postgres_end_transaction;
+	dbb->abort_transaction = db_postgres_abort_transaction;
+	dbb->query_lock = db_postgres_query_lock;
 
 	return 0;
 }

Diff do ficheiro suprimidas por serem muito extensas
+ 254 - 231
src/modules/db_postgres/km_dbase.c


+ 34 - 32
src/modules/db_postgres/km_dbase.h

@@ -38,9 +38,10 @@
 /*
  * Storage for all the unique constraints found by insert_update
  */
-typedef struct db_pg_constraint_list {
-	struct db_pg_constraint_list* next;
-	struct db_pg_constraint_list* prev;
+typedef struct db_pg_constraint_list
+{
+	struct db_pg_constraint_list *next;
+	struct db_pg_constraint_list *prev;
 	str database;
 	str table;
 	str unique;
@@ -49,113 +50,114 @@ typedef struct db_pg_constraint_list {
 /*
  * Initialize database connection
  */
-db1_con_t* db_postgres_init(const str* _url);
+db1_con_t *db_postgres_init(const str *_url);
 
 /*
  * Initialize database connection - no pooling
  */
-db1_con_t* db_postgres_init2(const str* _url, db_pooling_t pooling);
+db1_con_t *db_postgres_init2(const str *_url, db_pooling_t pooling);
 
 /*
  * Close a database connection
  */
-void db_postgres_close(db1_con_t* _h);
+void db_postgres_close(db1_con_t *_h);
 
 /*
  * Return result of previous query
  */
-int db_postgres_store_result(const db1_con_t* _h, db1_res_t** _r);
+int db_postgres_store_result(const db1_con_t *_h, db1_res_t **_r);
 
 
 /*
  * Free all memory allocated by get_result
  */
-int db_postgres_free_result(db1_con_t* _h, db1_res_t* _r);
+int db_postgres_free_result(db1_con_t *_h, db1_res_t *_r);
 
 
 /*
  * Do a query
  */
-int db_postgres_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
-		const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
-		const db_key_t _o, db1_res_t** _r);
+int db_postgres_query(const db1_con_t *_h, const db_key_t *_k,
+		const db_op_t *_op, const db_val_t *_v, const db_key_t *_c,
+		const int _n, const int _nc, const db_key_t _o, db1_res_t **_r);
 
 
 /*
  * Do a query and lock rows for update
  */
-int db_postgres_query_lock(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
-		const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
-		const db_key_t _o, db1_res_t** _r);
+int db_postgres_query_lock(const db1_con_t *_h, const db_key_t *_k,
+		const db_op_t *_op, const db_val_t *_v, const db_key_t *_c,
+		const int _n, const int _nc, const db_key_t _o, db1_res_t **_r);
 
 
 /*
  * Raw SQL query
  */
-int db_postgres_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r);
+int db_postgres_raw_query(const db1_con_t *_h, const str *_s, db1_res_t **_r);
 
 
 /*
  * Insert a row into table
  */
-int db_postgres_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
-		const int _n);
+int db_postgres_insert(const db1_con_t *_h, const db_key_t *_k,
+		const db_val_t *_v, const int _n);
 
 /*
  * Insert and update ON CONFLICT
  */
-int db_postgres_insert_update(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
-		const int _n);
+int db_postgres_insert_update(const db1_con_t *_h, const db_key_t *_k,
+		const db_val_t *_v, const int _n);
 
 /*
  * Delete a row from table
  */
-int db_postgres_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
-		const db_val_t* _v, const int _n);
+int db_postgres_delete(const db1_con_t *_h, const db_key_t *_k,
+		const db_op_t *_o, const db_val_t *_v, const int _n);
 
 
 /*
  * Update a row in table
  */
-int db_postgres_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
-		const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
-		const int _un);
+int db_postgres_update(const db1_con_t *_h, const db_key_t *_k,
+		const db_op_t *_o, const db_val_t *_v, const db_key_t *_uk,
+		const db_val_t *_uv, const int _n, const int _un);
 
 /*
  * fetch rows from a result
  */
-int db_postgres_fetch_result(const db1_con_t* _h, db1_res_t** _r, const int nrows);
+int db_postgres_fetch_result(
+		const db1_con_t *_h, db1_res_t **_r, const int nrows);
 
 /*
  * number of rows affected by the last DB query/statement
  */
-int db_postgres_affected_rows(const db1_con_t* _h);
+int db_postgres_affected_rows(const db1_con_t *_h);
 
 /*
  * SQL BEGIN
  */
-int db_postgres_start_transaction(db1_con_t* _h, db_locking_t _l);
+int db_postgres_start_transaction(db1_con_t *_h, db_locking_t _l);
 
 /*
  * SQL COMMIT
  */
-int db_postgres_end_transaction(db1_con_t* _h);
+int db_postgres_end_transaction(db1_con_t *_h);
 
 /*
  * SQL ROLLBACK
  */
-int db_postgres_abort_transaction(db1_con_t* _h);
+int db_postgres_abort_transaction(db1_con_t *_h);
 
 /*
  * Store name of table that will be used by
  * subsequent database functions
  */
-int db_postgres_use_table(db1_con_t* _h, const str* _t);
+int db_postgres_use_table(db1_con_t *_h, const str *_t);
 
 /*
  * Replace a row in table (via update/insert)
  */
-int db_postgres_replace(const db1_con_t* _h, const db_key_t* _k,
-		const db_val_t* _v, const int _n, const int _un, const int _m);
+int db_postgres_replace(const db1_con_t *_h, const db_key_t *_k,
+		const db_val_t *_v, const int _n, const int _un, const int _m);
 
 #endif /* KM_DBASE_H */

+ 40 - 35
src/modules/db_postgres/km_pg_con.c

@@ -30,7 +30,7 @@
 #include "../../core/mem/mem.h"
 #include "../../core/dprint.h"
 #include "../../core/ut.h"
-#include "../../core/tls_hooks_init.h" 
+#include "../../core/tls_hooks_init.h"
 #include <string.h>
 #include <time.h>
 #include <netinet/in.h>
@@ -45,25 +45,26 @@
  * \param id database id
  * \return postgres connection structure, 0 on error
  */
-struct pg_con* db_postgres_new_connection(struct db_id* id)
+struct pg_con *db_postgres_new_connection(struct db_id *id)
 {
-	struct pg_con* ptr;
+	struct pg_con *ptr;
 	char *ports;
 	int i = 0;
 	const char *keywords[10], *values[10];
 	char to[16];
 
 	LM_DBG("db_id = %p\n", id);
- 
-	if (!id) {
+
+	if(!id) {
 		LM_ERR("invalid db_id parameter value\n");
 		return 0;
 	}
 
-	ptr = (struct pg_con*)pkg_malloc(sizeof(struct pg_con));
-	if (!ptr) {
+	ptr = (struct pg_con *)pkg_malloc(sizeof(struct pg_con));
+	if(!ptr) {
 		LM_ERR("failed trying to allocated %lu bytes for connection structure."
-				"\n", (unsigned long)sizeof(struct pg_con));
+			   "\n",
+				(unsigned long)sizeof(struct pg_con));
 		return 0;
 	}
 	LM_DBG("%p=pkg_malloc(%lu)\n", ptr, (unsigned long)sizeof(struct pg_con));
@@ -71,20 +72,20 @@ struct pg_con* db_postgres_new_connection(struct db_id* id)
 	memset(ptr, 0, sizeof(struct pg_con));
 	ptr->ref = 1;
 
-	memset(keywords, 0, (sizeof(char*) * 10));
-	memset(values, 0, (sizeof(char*) * 10));
+	memset(keywords, 0, (sizeof(char *) * 10));
+	memset(values, 0, (sizeof(char *) * 10));
 	memset(to, 0, (sizeof(char) * 16));
 
-	if (id->port) {
+	if(id->port) {
 		ports = int2str(id->port, 0);
 		keywords[i] = "port";
 		values[i++] = ports;
-		LM_DBG("opening connection: postgres://xxxx:xxxx@%s:%d/%s\n", ZSW(id->host),
-			id->port, ZSW(id->database));
+		LM_DBG("opening connection: postgres://xxxx:xxxx@%s:%d/%s\n",
+				ZSW(id->host), id->port, ZSW(id->database));
 	} else {
 		ports = NULL;
-		LM_DBG("opening connection: postgres://xxxx:xxxx@%s/%s\n", ZSW(id->host),
-			ZSW(id->database));
+		LM_DBG("opening connection: postgres://xxxx:xxxx@%s/%s\n",
+				ZSW(id->host), ZSW(id->database));
 	}
 
 	keywords[i] = "host";
@@ -95,8 +96,8 @@ struct pg_con* db_postgres_new_connection(struct db_id* id)
 	values[i++] = id->username;
 	keywords[i] = "password";
 	values[i++] = id->password;
-	if (pg_timeout > 0) {
-		snprintf(to, sizeof(to)-1, "%d", pg_timeout + 3);
+	if(pg_timeout > 0) {
+		snprintf(to, sizeof(to) - 1, "%d", pg_timeout + 3);
 		keywords[i] = "connect_timeout";
 		values[i++] = to;
 	}
@@ -104,19 +105,19 @@ struct pg_con* db_postgres_new_connection(struct db_id* id)
 	keywords[i] = values[i] = NULL;
 
 	/* don't attempt to re-init openssl if done already */
-	if(tls_loaded()) PQinitSSL(0);
+	if(tls_loaded())
+		PQinitSSL(0);
 
 	ptr->con = PQconnectdbParams(keywords, values, 1);
 	LM_DBG("PQconnectdbParams(%p)\n", ptr->con);
 
-	if( (ptr->con == 0) || (PQstatus(ptr->con) != CONNECTION_OK) )
-	{
+	if((ptr->con == 0) || (PQstatus(ptr->con) != CONNECTION_OK)) {
 		LM_ERR("%s\n", PQerrorMessage(ptr->con));
 		PQfinish(ptr->con);
 		goto err;
 	}
 
-	if (PQserverVersion(ptr->con) <  90500) {
+	if(PQserverVersion(ptr->con) < 90500) {
 		LM_WARN("server version < 9.5 does not support insert_update\n");
 	}
 
@@ -125,14 +126,16 @@ struct pg_con* db_postgres_new_connection(struct db_id* id)
 	ptr->id = id;
 
 #if defined(SO_KEEPALIVE) && defined(TCP_KEEPIDLE)
-	if (pg_keepalive) {
+	if(pg_keepalive) {
 		i = 1;
-		if(setsockopt(PQsocket(ptr->con), SOL_SOCKET, SO_KEEPALIVE, &i,
-					sizeof(i))<0) {
+		if(setsockopt(
+				   PQsocket(ptr->con), SOL_SOCKET, SO_KEEPALIVE, &i, sizeof(i))
+				< 0) {
 			LM_WARN("setsockopt for keepalive failed\n");
 		}
 		if(setsockopt(PQsocket(ptr->con), IPPROTO_TCP, TCP_KEEPIDLE,
-					&pg_keepalive, sizeof(pg_keepalive))<0) {
+				   &pg_keepalive, sizeof(pg_keepalive))
+				< 0) {
 			LM_WARN("setsockopt for keepidle failed\n");
 		}
 	}
@@ -140,8 +143,8 @@ struct pg_con* db_postgres_new_connection(struct db_id* id)
 
 	return ptr;
 
- err:
-	if (ptr) {
+err:
+	if(ptr) {
 		LM_ERR("cleaning up %p=pkg_free()\n", ptr);
 		pkg_free(ptr);
 	}
@@ -153,22 +156,24 @@ struct pg_con* db_postgres_new_connection(struct db_id* id)
  * \brief Close the connection and release memory
  * \param con connection
  */
-void db_postgres_free_connection(struct pool_con* con)
+void db_postgres_free_connection(struct pool_con *con)
 {
 
-	struct pg_con * _c;
-	
-	if (!con) return;
+	struct pg_con *_c;
+
+	if(!con)
+		return;
 
-	_c = (struct pg_con*)con;
+	_c = (struct pg_con *)con;
 
-	if (_c->res) {
+	if(_c->res) {
 		LM_DBG("PQclear(%p)\n", _c->res);
 		PQclear(_c->res);
 		_c->res = 0;
 	}
-	if (_c->id) free_db_id(_c->id);
-	if (_c->con) {
+	if(_c->id)
+		free_db_id(_c->id);
+	if(_c->con) {
 		LM_DBG("PQfinish(%p)\n", _c->con);
 		PQfinish(_c->con);
 		_c->con = 0;

+ 26 - 23
src/modules/db_postgres/km_pg_con.h

@@ -37,40 +37,43 @@
 
 
 /*! Postgres specific connection data */
-struct pg_con {
-	struct db_id* id;        /*!< Connection identifier */
-	unsigned int ref;        /*!< Reference count */
-	struct pool_con* next;   /*!< Next connection in the pool */
+struct pg_con
+{
+	struct db_id *id;	  /*!< Connection identifier */
+	unsigned int ref;	  /*!< Reference count */
+	struct pool_con *next; /*!< Next connection in the pool */
 
-	int connected;      /*!< connection status */
-	char *sqlurl;		/*!< the url we are connected to, all connection memory parents from this */
-	PGconn *con;		/*!< this is the postgres connection */
-	PGresult *res;		/*!< this is the current result */
-	char**  row;		/*!< Actual row in the result */
-	time_t timestamp;	/*!< Timestamp of last query */
-	int affected_rows;	/*!< Number of rows affected by the last statement */
-	int transaction;	/*!< indicates whether a multi-query transaction is currently open */
+	int connected; /*!< connection status */
+	char *sqlurl; /*!< the url we are connected to, all connection memory parents from this */
+	PGconn *con;	   /*!< this is the postgres connection */
+	PGresult *res;	 /*!< this is the current result */
+	char **row;		   /*!< Actual row in the result */
+	time_t timestamp;  /*!< Timestamp of last query */
+	int affected_rows; /*!< Number of rows affected by the last statement */
+	int transaction; /*!< indicates whether a multi-query transaction is currently open */
 };
 
-#define CON_SQLURL(db_con)     (((struct pg_con*)((db_con)->tail))->sqlurl)
-#define CON_RESULT(db_con)     (((struct pg_con*)((db_con)->tail))->res)
-#define CON_CONNECTION(db_con) (((struct pg_con*)((db_con)->tail))->con)
-#define CON_CONNECTED(db_con)  (((struct pg_con*)((db_con)->tail))->connected)
-#define CON_ROW(db_con)	       (((struct pg_con*)((db_con)->tail))->row)
-#define CON_TIMESTAMP(db_con)  (((struct pg_con*)((db_con)->tail))->timestamp)
-#define CON_ID(db_con) 	       (((struct pg_con*)((db_con)->tail))->id)
-#define CON_AFFECTED(db_con)   (((struct pg_con*)((db_con)->tail))->affected_rows)
-#define CON_TRANSACTION(db_con) (((struct pg_con*)((db_con)->tail))->transaction)
+#define CON_SQLURL(db_con) (((struct pg_con *)((db_con)->tail))->sqlurl)
+#define CON_RESULT(db_con) (((struct pg_con *)((db_con)->tail))->res)
+#define CON_CONNECTION(db_con) (((struct pg_con *)((db_con)->tail))->con)
+#define CON_CONNECTED(db_con) (((struct pg_con *)((db_con)->tail))->connected)
+#define CON_ROW(db_con) (((struct pg_con *)((db_con)->tail))->row)
+#define CON_TIMESTAMP(db_con) (((struct pg_con *)((db_con)->tail))->timestamp)
+#define CON_ID(db_con) (((struct pg_con *)((db_con)->tail))->id)
+#define CON_AFFECTED(db_con) \
+	(((struct pg_con *)((db_con)->tail))->affected_rows)
+#define CON_TRANSACTION(db_con) \
+	(((struct pg_con *)((db_con)->tail))->transaction)
 
 /*
  * Create a new connection structure,
  * open the PostgreSQL connection and set reference count to 1
  */
-struct pg_con* db_postgres_new_connection(struct db_id* id);
+struct pg_con *db_postgres_new_connection(struct db_id *id);
 
 /*
  * Close the connection and release memory
  */
-void db_postgres_free_connection(struct pool_con* con);
+void db_postgres_free_connection(struct pool_con *con);
 
 #endif /* KM_PG_CON_H */

+ 59 - 59
src/modules/db_postgres/km_pg_type.h

@@ -27,62 +27,62 @@
  * OID definitions, copied from postgresql/catalog/pg_types.h.
  * It would be probably more correct to use the definitions from there.
  */
-#define BOOLOID			16
-#define BYTEAOID		17
-#define CHAROID			18
-#define NAMEOID			19
-#define INT8OID			20
-#define INT2OID			21
-#define INT2VECTOROID		22
-#define INT4OID			23
-#define REGPROCOID		24
-#define TEXTOID			25
-#define OIDOID			26
-#define TIDOID			27
-#define XIDOID 			28
-#define CIDOID 			29
-#define OIDVECTOROID		30
-#define POINTOID		600
-#define LSEGOID			601
-#define PATHOID			602
-#define BOXOID			603
-#define POLYGONOID		604
-#define LINEOID			628
-#define FLOAT4OID 		700
-#define FLOAT8OID 		701
-#define ABSTIMEOID		702
-#define RELTIMEOID		703
-#define TINTERVALOID		704
-#define UNKNOWNOID		705
-#define CIRCLEOID		718
-#define CASHOID 		790
-#define MACADDROID 		829
-#define INETOID 		869
-#define CIDROID 		650
-#define ACLITEMOID		1033
-#define BPCHAROID		1042
-#define VARCHAROID		1043
-#define DATEOID			1082
-#define TIMEOID			1083
-#define TIMESTAMPOID		1114
-#define TIMESTAMPTZOID		1184
-#define INTERVALOID		1186
-#define TIMETZOID		1266
-#define BITOID	 		1560
-#define VARBITOID	  	1562
-#define NUMERICOID		1700
-#define REFCURSOROID		1790
-#define REGPROCEDUREOID 	2202
-#define REGOPEROID		2203
-#define REGOPERATOROID		2204
-#define REGCLASSOID		2205
-#define REGTYPEOID		2206
-#define RECORDOID		2249
-#define CSTRINGOID		2275
-#define ANYOID			2276
-#define ANYARRAYOID		2277
-#define VOIDOID			2278
-#define TRIGGEROID		2279
-#define LANGUAGE_HANDLEROID	2280
-#define INTERNALOID		2281
-#define OPAQUEOID		2282
+#define BOOLOID 16
+#define BYTEAOID 17
+#define CHAROID 18
+#define NAMEOID 19
+#define INT8OID 20
+#define INT2OID 21
+#define INT2VECTOROID 22
+#define INT4OID 23
+#define REGPROCOID 24
+#define TEXTOID 25
+#define OIDOID 26
+#define TIDOID 27
+#define XIDOID 28
+#define CIDOID 29
+#define OIDVECTOROID 30
+#define POINTOID 600
+#define LSEGOID 601
+#define PATHOID 602
+#define BOXOID 603
+#define POLYGONOID 604
+#define LINEOID 628
+#define FLOAT4OID 700
+#define FLOAT8OID 701
+#define ABSTIMEOID 702
+#define RELTIMEOID 703
+#define TINTERVALOID 704
+#define UNKNOWNOID 705
+#define CIRCLEOID 718
+#define CASHOID 790
+#define MACADDROID 829
+#define INETOID 869
+#define CIDROID 650
+#define ACLITEMOID 1033
+#define BPCHAROID 1042
+#define VARCHAROID 1043
+#define DATEOID 1082
+#define TIMEOID 1083
+#define TIMESTAMPOID 1114
+#define TIMESTAMPTZOID 1184
+#define INTERVALOID 1186
+#define TIMETZOID 1266
+#define BITOID 1560
+#define VARBITOID 1562
+#define NUMERICOID 1700
+#define REFCURSOROID 1790
+#define REGPROCEDUREOID 2202
+#define REGOPEROID 2203
+#define REGOPERATOROID 2204
+#define REGCLASSOID 2205
+#define REGTYPEOID 2206
+#define RECORDOID 2249
+#define CSTRINGOID 2275
+#define ANYOID 2276
+#define ANYARRAYOID 2277
+#define VOIDOID 2278
+#define TRIGGEROID 2279
+#define LANGUAGE_HANDLEROID 2280
+#define INTERNALOID 2281
+#define OPAQUEOID 2282

+ 50 - 44
src/modules/db_postgres/km_res.c

@@ -46,19 +46,19 @@
  * \param _r result set
  * \return 0 on success, negative on error
  */
-int db_postgres_convert_result(const db1_con_t* _h, db1_res_t* _r)
+int db_postgres_convert_result(const db1_con_t *_h, db1_res_t *_r)
 {
-	if (!_h || !_r)  {
+	if(!_h || !_r) {
 		LM_ERR("invalid parameter value\n");
 		return -1;
 	}
 
-	if (db_postgres_get_columns(_h, _r) < 0) {
+	if(db_postgres_get_columns(_h, _r) < 0) {
 		LM_ERR("failed to get column names\n");
 		return -2;
 	}
 
-	if (db_postgres_convert_rows(_h, _r) < 0) {
+	if(db_postgres_convert_rows(_h, _r) < 0) {
 		LM_ERR("failed to convert rows\n");
 		db_free_columns(_r);
 		return -3;
@@ -73,11 +73,11 @@ int db_postgres_convert_result(const db1_con_t* _h, db1_res_t* _r)
  * \param _r result set
  * \return 0 on success, negative on error
  */
-int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r)
+int db_postgres_get_columns(const db1_con_t *_h, db1_res_t *_r)
 {
 	int col, datatype;
 
-	if (!_h || !_r)  {
+	if(!_h || !_r) {
 		LM_ERR("invalid parameter value\n");
 		return -1;
 	}
@@ -88,14 +88,14 @@ int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r)
 	/* Get the number of columns (fields) in each row of the query result. */
 	RES_COL_N(_r) = PQnfields(CON_RESULT(_h));
 
-	if (!RES_COL_N(_r)) {
+	if(!RES_COL_N(_r)) {
 		LM_DBG("no columns returned from the query\n");
 		return -2;
 	} else {
 		LM_DBG("%d columns returned from the query\n", RES_COL_N(_r));
 	}
 
-	if (db_allocate_columns(_r, RES_COL_N(_r)) != 0) {
+	if(db_allocate_columns(_r, RES_COL_N(_r)) != 0) {
 		LM_ERR("could not allocate columns\n");
 		return -3;
 	}
@@ -103,14 +103,14 @@ int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r)
 	/* For each column both the name and the OID number of the data type are saved. */
 	for(col = 0; col < RES_COL_N(_r); col++) {
 
-		RES_NAMES(_r)[col] = (str*)pkg_malloc(sizeof(str));
-		if (! RES_NAMES(_r)[col]) {
+		RES_NAMES(_r)[col] = (str *)pkg_malloc(sizeof(str));
+		if(!RES_NAMES(_r)[col]) {
 			LM_ERR("no private memory left\n");
 			db_free_columns(_r);
 			return -4;
 		}
-		LM_DBG("allocate %d bytes for RES_NAMES[%d] at %p\n", (unsigned int) sizeof(str), col,
-				RES_NAMES(_r)[col]);
+		LM_DBG("allocate %d bytes for RES_NAMES[%d] at %p\n",
+				(unsigned int)sizeof(str), col, RES_NAMES(_r)[col]);
 
 		/* The pointer that is here returned is part of the result structure. */
 		RES_NAMES(_r)[col]->s = PQfname(CON_RESULT(_h), col);
@@ -120,32 +120,31 @@ int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r)
 				RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s);
 
 		/* get the datatype of the column */
-		switch(datatype = PQftype(CON_RESULT(_h),col))
-		{
+		switch(datatype = PQftype(CON_RESULT(_h), col)) {
 			case INT2OID:
 			case INT4OID:
 				LM_DBG("use DB1_INT result type\n");
 				RES_TYPES(_r)[col] = DB1_INT;
-			break;
+				break;
 
 			case INT8OID:
 				LM_DBG("use DB1_BIGINT result type\n");
 				RES_TYPES(_r)[col] = DB1_BIGINT;
-			break;
+				break;
 
 			case FLOAT4OID:
 			case FLOAT8OID:
 			case NUMERICOID:
 				LM_DBG("use DB1_DOUBLE result type\n");
 				RES_TYPES(_r)[col] = DB1_DOUBLE;
-			break;
+				break;
 
 			case DATEOID:
 			case TIMESTAMPOID:
 			case TIMESTAMPTZOID:
 				LM_DBG("use DB1_DATETIME result type\n");
 				RES_TYPES(_r)[col] = DB1_DATETIME;
-			break;
+				break;
 
 			case BOOLOID:
 			case CHAROID:
@@ -154,26 +153,27 @@ int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r)
 			case BPCHAROID:
 				LM_DBG("use DB1_STRING result type\n");
 				RES_TYPES(_r)[col] = DB1_STRING;
-			break;
+				break;
 
 			case TEXTOID:
 			case BYTEAOID:
 				LM_DBG("use DB1_BLOB result type\n");
 				RES_TYPES(_r)[col] = DB1_BLOB;
-			break;
+				break;
 
 			case BITOID:
 			case VARBITOID:
 				LM_DBG("use DB1_BITMAP result type\n");
 				RES_TYPES(_r)[col] = DB1_BITMAP;
-			break;
+				break;
 
 			default:
 				LM_WARN("unhandled data type column (%.*s) type id (%d), "
-						"use DB1_STRING as default\n", RES_NAMES(_r)[col]->len,
-						RES_NAMES(_r)[col]->s, datatype);
+						"use DB1_STRING as default\n",
+						RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s,
+						datatype);
 				RES_TYPES(_r)[col] = DB1_STRING;
-			break;
+				break;
 		}
 	}
 	return 0;
@@ -186,38 +186,40 @@ int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r)
  * \param _r result set
  * \return 0 on success, negative on error
  */
-int db_postgres_convert_rows(const db1_con_t* _h, db1_res_t* _r)
+int db_postgres_convert_rows(const db1_con_t *_h, db1_res_t *_r)
 {
 	char **row_buf, *s;
 	int row, col, len;
 
-	if (!_h || !_r)  {
+	if(!_h || !_r) {
 		LM_ERR("invalid parameter\n");
 		return -1;
 	}
 
-	if (!RES_ROW_N(_r)) {
+	if(!RES_ROW_N(_r)) {
 		LM_DBG("no rows returned from the query\n");
 		RES_ROWS(_r) = 0;
 		return 0;
 	}
 	/*Allocate an array of pointers per column to holds the string representation */
 	len = sizeof(char *) * RES_COL_N(_r);
-	row_buf = (char**)pkg_malloc(len);
-	if (!row_buf) {
+	row_buf = (char **)pkg_malloc(len);
+	if(!row_buf) {
 		LM_ERR("no private memory left\n");
 		return -1;
 	}
-	LM_DBG("allocate for %d columns %d bytes in row buffer at %p\n", RES_COL_N(_r), len, row_buf);
+	LM_DBG("allocate for %d columns %d bytes in row buffer at %p\n",
+			RES_COL_N(_r), len, row_buf);
 
-	if (db_allocate_rows(_r) < 0) {
+	if(db_allocate_rows(_r) < 0) {
 		LM_ERR("could not allocate rows\n");
 		LM_DBG("freeing row buffer at %p\n", row_buf);
 		pkg_free(row_buf);
 		return -2;
 	}
 
-	for(row = RES_LAST_ROW(_r); row < (RES_LAST_ROW(_r) + RES_ROW_N(_r)); row++) {
+	for(row = RES_LAST_ROW(_r); row < (RES_LAST_ROW(_r) + RES_ROW_N(_r));
+			row++) {
 		/* reset row buf content */
 		memset(row_buf, 0, len);
 		for(col = 0; col < RES_COL_N(_r); col++) {
@@ -235,16 +237,19 @@ int db_postgres_convert_rows(const db1_con_t* _h, db1_res_t* _r)
 			 * This differs from the mysql behaviour, that further processing
 			 * steps expect. So we need to simulate this here unfortunally.
 			 */
-			if (PQgetisnull(CON_RESULT(_h), row, col) == 0) {
+			if(PQgetisnull(CON_RESULT(_h), row, col) == 0) {
 				row_buf[col] = s;
-				LM_DBG("[%d][%d] Column[%.*s]=[%s]\n",
-					row, col, RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s, row_buf[col]);
+				LM_DBG("[%d][%d] Column[%.*s]=[%s]\n", row, col,
+						RES_NAMES(_r)[col]->len, RES_NAMES(_r)[col]->s,
+						row_buf[col]);
 			}
 		}
 
 		/* ASSERT: row_buf contains an entire row in strings */
-		if(db_postgres_convert_row(_h, _r, &(RES_ROWS(_r)[row - RES_LAST_ROW(_r)]), row_buf)<0){
-			LM_ERR("failed to convert row #%d\n",  row);
+		if(db_postgres_convert_row(
+				   _h, _r, &(RES_ROWS(_r)[row - RES_LAST_ROW(_r)]), row_buf)
+				< 0) {
+			LM_ERR("failed to convert row #%d\n", row);
 			RES_ROW_N(_r) = row - RES_LAST_ROW(_r);
 			LM_DBG("freeing row buffer at %p\n", row_buf);
 			pkg_free(row_buf);
@@ -268,17 +273,17 @@ int db_postgres_convert_rows(const db1_con_t* _h, db1_res_t* _r)
  * \param row_buf row buffer
  * \return 0 on success, negative on error
  */
-int db_postgres_convert_row(const db1_con_t* _h, db1_res_t* _r, db_row_t* _row,
-		char **row_buf)
+int db_postgres_convert_row(
+		const db1_con_t *_h, db1_res_t *_r, db_row_t *_row, char **row_buf)
 {
 	int col, col_len;
 
-	if (!_h || !_r || !_row)  {
+	if(!_h || !_r || !_row) {
 		LM_ERR("invalid parameter value\n");
 		return -1;
 	}
 
-	if (db_allocate_row(_r, _row) != 0) {
+	if(db_allocate_row(_r, _row) != 0) {
 		LM_ERR("could not allocate row\n");
 		return -2;
 	}
@@ -286,14 +291,15 @@ int db_postgres_convert_row(const db1_con_t* _h, db1_res_t* _r, db_row_t* _row,
 	/* For each column in the row */
 	for(col = 0; col < ROW_N(_row); col++) {
 		/* because it can contain NULL */
-		if (!row_buf[col]) {
+		if(!row_buf[col]) {
 			col_len = 0;
 		} else {
 			col_len = strlen(row_buf[col]);
 		}
 		/* Convert the string representation into the value representation */
-		if (db_postgres_str2val(RES_TYPES(_r)[col], &(ROW_VALUES(_row)[col]),
-		row_buf[col], col_len) < 0) {
+		if(db_postgres_str2val(RES_TYPES(_r)[col], &(ROW_VALUES(_row)[col]),
+				   row_buf[col], col_len)
+				< 0) {
 			LM_ERR("failed to convert value\n");
 			LM_DBG("free row at %p\n", _row);
 			db_free_row(_row);

+ 5 - 5
src/modules/db_postgres/km_res.h

@@ -30,13 +30,13 @@
 
 #include "../../lib/srdb1/db_row.h"
 
-int db_postgres_convert_result(const db1_con_t* _h, db1_res_t* _r);
+int db_postgres_convert_result(const db1_con_t *_h, db1_res_t *_r);
 
-int db_postgres_convert_row(const db1_con_t* _h, db1_res_t* _res, db_row_t* _r,
-	char **row_buf);
+int db_postgres_convert_row(
+		const db1_con_t *_h, db1_res_t *_res, db_row_t *_r, char **row_buf);
 
-int db_postgres_get_columns(const db1_con_t* _h, db1_res_t* _r);
+int db_postgres_get_columns(const db1_con_t *_h, db1_res_t *_r);
 
-int db_postgres_convert_rows(const db1_con_t* _h, db1_res_t* _r);
+int db_postgres_convert_rows(const db1_con_t *_h, db1_res_t *_r);
 
 #endif

+ 86 - 86
src/modules/db_postgres/km_val.c

@@ -47,34 +47,34 @@
  * \param _l string length
  * \return 0 on success, negative on error
  */
-int db_postgres_str2val(const db_type_t _t, db_val_t* _v, const char* _s,
-		const int _l)
+int db_postgres_str2val(
+		const db_type_t _t, db_val_t *_v, const char *_s, const int _l)
 {
 	/* use common function for non BLOB, NULL setting and input
 	 * parameter checking */
-	if ( _t != DB1_BLOB || _s == NULL || _v == NULL) {
+	if(_t != DB1_BLOB || _s == NULL || _v == NULL) {
 		return db_str2val(_t, _v, _s, _l, 1);
 	} else {
-		char * tmp_s = NULL;
+		char *tmp_s = NULL;
 		LM_DBG("converting BLOB [%.*s]\n", _l, _s);
 		/*
 		 * The string is stored in new allocated memory, which we could
 		 * not free later thus we need to copy it to some new memory here.
 		 */
-		tmp_s = (char*)PQunescapeBytea((unsigned char*)_s,
-					(size_t*)(void*)&(VAL_BLOB(_v).len));
-		if(tmp_s==NULL) {
+		tmp_s = (char *)PQunescapeBytea(
+				(unsigned char *)_s, (size_t *)(void *)&(VAL_BLOB(_v).len));
+		if(tmp_s == NULL) {
 			LM_ERR("PQunescapeBytea failed\n");
 			return -7;
 		}
 		VAL_BLOB(_v).s = pkg_malloc(VAL_BLOB(_v).len + 1);
-		if (VAL_BLOB(_v).s == NULL) {
+		if(VAL_BLOB(_v).s == NULL) {
 			LM_ERR("no private memory left\n");
 			PQfreemem(tmp_s);
 			return -8;
 		}
-		LM_DBG("allocate %d+1 bytes memory for BLOB at %p",
-				VAL_BLOB(_v).len, VAL_BLOB(_v).s);
+		LM_DBG("allocate %d+1 bytes memory for BLOB at %p", VAL_BLOB(_v).len,
+				VAL_BLOB(_v).s);
 		memcpy(VAL_BLOB(_v).s, tmp_s, VAL_BLOB(_v).len);
 		PQfreemem(tmp_s);
 
@@ -84,7 +84,6 @@ int db_postgres_str2val(const db_type_t _t, db_val_t* _v, const char* _s,
 
 		LM_DBG("got blob len %d\n", _l);
 		return 0;
-
 	}
 }
 
@@ -99,99 +98,100 @@ int db_postgres_str2val(const db_type_t _t, db_val_t* _v, const char* _s,
  * \param _len target string length
  * \return 0 on success, negative on error
  */
-int db_postgres_val2str(const db1_con_t* _con, const db_val_t* _v, char* _s, int* _len)
+int db_postgres_val2str(
+		const db1_con_t *_con, const db_val_t *_v, char *_s, int *_len)
 {
 	int l, ret, tmp;
 	int pgret;
 	char *tmp_s;
 	size_t tmp_len;
-	char* old_s;
+	char *old_s;
 
 	tmp = db_val2str(_con, _v, _s, _len);
-	if (tmp < 1)
+	if(tmp < 1)
 		return tmp;
 
 	switch(VAL_TYPE(_v)) {
-	case DB1_STRING:
-		l = strlen(VAL_STRING(_v));
-		if (*_len < (l * 2 + 3)) {
-			LM_ERR("destination buffer too short for string\n");
-			return -6;
-		} else {
-			old_s = _s;
-			*_s++ = '\'';
-			ret = PQescapeStringConn(CON_CONNECTION(_con), _s, VAL_STRING(_v),
-					l, &pgret);
-			if(pgret!=0)
-			{
-				LM_ERR("PQescapeStringConn failed\n");
+		case DB1_STRING:
+			l = strlen(VAL_STRING(_v));
+			if(*_len < (l * 2 + 3)) {
+				LM_ERR("destination buffer too short for string\n");
 				return -6;
+			} else {
+				old_s = _s;
+				*_s++ = '\'';
+				ret = PQescapeStringConn(
+						CON_CONNECTION(_con), _s, VAL_STRING(_v), l, &pgret);
+				if(pgret != 0) {
+					LM_ERR("PQescapeStringConn failed\n");
+					return -6;
+				}
+				LM_DBG("PQescapeStringConn: in: %d chars,"
+					   " out: %d chars\n",
+						l, ret);
+				_s += ret;
+				*_s++ = '\'';
+				*_s = '\0'; /* FIXME */
+				*_len = _s - old_s;
+				return 0;
 			}
-			LM_DBG("PQescapeStringConn: in: %d chars,"
-				" out: %d chars\n", l, ret);
-			_s += ret;
-			*_s++ = '\'';
-			*_s = '\0'; /* FIXME */
-			*_len = _s - old_s;
-			return 0;
-		}
-		break;
+			break;
 
-	case DB1_STR:
-		l = VAL_STR(_v).len;
-		if (*_len < (l * 2 + 3)) {
-			LM_ERR("destination buffer too short for str\n");
-			return -7;
-		} else {
-			old_s = _s;
-			*_s++ = '\'';
-			ret = PQescapeStringConn(CON_CONNECTION(_con), _s, VAL_STRING(_v),
-					l, &pgret);
-			if(pgret!=0)
-			{
-				LM_ERR("PQescapeStringConn failed \n");
+		case DB1_STR:
+			l = VAL_STR(_v).len;
+			if(*_len < (l * 2 + 3)) {
+				LM_ERR("destination buffer too short for str\n");
 				return -7;
+			} else {
+				old_s = _s;
+				*_s++ = '\'';
+				ret = PQescapeStringConn(
+						CON_CONNECTION(_con), _s, VAL_STRING(_v), l, &pgret);
+				if(pgret != 0) {
+					LM_ERR("PQescapeStringConn failed \n");
+					return -7;
+				}
+				LM_DBG("PQescapeStringConn: in: %d chars, out: %d chars\n", l,
+						ret);
+				_s += ret;
+				*_s++ = '\'';
+				*_s = '\0'; /* FIXME */
+				*_len = _s - old_s;
+				return 0;
 			}
-	        LM_DBG("PQescapeStringConn: in: %d chars, out: %d chars\n", l, ret);
-			_s += ret;
-			*_s++ = '\'';
-			*_s = '\0'; /* FIXME */
-			*_len = _s - old_s;
-			return 0;
-		}
-		break;
+			break;
 
-	case DB1_BLOB:
-		l = VAL_BLOB(_v).len;
-		/* this estimation is not always correct, thus we need to check later again */
-		if (*_len < (l * 2 + 3)) {
-			LM_ERR("destination buffer too short for blob\n");
-			return -9;
-		} else {
-			*_s++ = '\'';
-			tmp_s = (char*)PQescapeByteaConn(CON_CONNECTION(_con), (unsigned char*)VAL_STRING(_v),
-					(size_t)l, (size_t*)&tmp_len);
-			if(tmp_s==NULL)
-			{
-				LM_ERR("PQescapeByteaConn failed\n");
+		case DB1_BLOB:
+			l = VAL_BLOB(_v).len;
+			/* this estimation is not always correct, thus we need to check later again */
+			if(*_len < (l * 2 + 3)) {
+				LM_ERR("destination buffer too short for blob\n");
 				return -9;
+			} else {
+				*_s++ = '\'';
+				tmp_s = (char *)PQescapeByteaConn(CON_CONNECTION(_con),
+						(unsigned char *)VAL_STRING(_v), (size_t)l,
+						(size_t *)&tmp_len);
+				if(tmp_s == NULL) {
+					LM_ERR("PQescapeByteaConn failed\n");
+					return -9;
+				}
+				if(tmp_len > *_len) {
+					LM_ERR("escaped result too long\n");
+					return -9;
+				}
+				memcpy(_s, tmp_s, tmp_len);
+				PQfreemem(tmp_s);
+				tmp_len = strlen(_s);
+				*(_s + tmp_len) = '\'';
+				*(_s + tmp_len + 1) = '\0';
+				*_len = tmp_len + 2;
+				return 0;
 			}
-			if (tmp_len > *_len) {
-				LM_ERR("escaped result too long\n");
-				return -9;
-			}
-			memcpy(_s, tmp_s, tmp_len);
-			PQfreemem(tmp_s);
-			tmp_len = strlen(_s);
-			*(_s + tmp_len) = '\'';
-			*(_s + tmp_len + 1) = '\0';
-			*_len = tmp_len + 2;
-			return 0;
-		}
-		break;
+			break;
 
-	default:
-		LM_DBG("unknown data type\n");
-		return -10;
+		default:
+			LM_DBG("unknown data type\n");
+			return -10;
 	}
 }

+ 4 - 2
src/modules/db_postgres/km_val.h

@@ -27,8 +27,10 @@
 #ifndef KM_VAL_H
 #define KM_VAL_H
 
-int db_postgres_str2val(const db_type_t _t, db_val_t* _v, const char* _s, const int _l);
+int db_postgres_str2val(
+		const db_type_t _t, db_val_t *_v, const char *_s, const int _l);
 
-int db_postgres_val2str(const db1_con_t* _con, const db_val_t* _v, char* _s, int* _len);
+int db_postgres_val2str(
+		const db1_con_t *_con, const db_val_t *_v, char *_s, int *_len);
 
 #endif

+ 223 - 188
src/modules/db_postgres/pg_cmd.c

@@ -50,8 +50,8 @@
  */
 static int server_query_no = 0;
 
-static int upload_cmd(db_cmd_t* cmd);
-static void free_pg_params(struct pg_params* cmd);
+static int upload_cmd(db_cmd_t *cmd);
+static void free_pg_params(struct pg_params *cmd);
 
 
 /** Destroys a pg_cmd structure.
@@ -59,13 +59,16 @@ static void free_pg_params(struct pg_params* cmd);
  * @param cmd A pointer to generic db_cmd command being freed.
  * @param payload A pointer to pg_cmd structure to be freed.
  */
-static void pg_cmd_free(db_cmd_t* cmd, struct pg_cmd* payload)
+static void pg_cmd_free(db_cmd_t *cmd, struct pg_cmd *payload)
 {
 	db_drv_free(&payload->gen);
-	if (payload->sql_cmd.s) pkg_free(payload->sql_cmd.s);
+	if(payload->sql_cmd.s)
+		pkg_free(payload->sql_cmd.s);
 	free_pg_params(&payload->params);
-	if (payload->name) pkg_free(payload->name);
-	if (payload->types) PQclear(payload->types);
+	if(payload->name)
+		pkg_free(payload->name);
+	if(payload->types)
+		PQclear(payload->types);
 	pkg_free(payload);
 }
 
@@ -80,17 +83,17 @@ static void pg_cmd_free(db_cmd_t* cmd, struct pg_cmd* payload)
  * @return A string allocated using pkg_malloc containing the name or NULL on
  *         error.
  */
-static int gen_cmd_name(db_cmd_t* cmd)
+static int gen_cmd_name(db_cmd_t *cmd)
 {
-	struct pg_cmd* pcmd;
-	char* c;
+	struct pg_cmd *pcmd;
+	char *c;
 	int len;
 
 	pcmd = DB_GET_PAYLOAD(cmd);
 	c = int2str(server_query_no, &len);
 
 	pcmd->name = pkg_malloc(len + 1);
-	if (pcmd->name == NULL) {
+	if(pcmd->name == NULL) {
 		ERR("postgres: No memory left\n");
 		return -1;
 	}
@@ -110,33 +113,33 @@ static int gen_cmd_name(db_cmd_t* cmd)
  * @retval 0 on success.
  * @retval A negative number on error.
  */
-static int create_pg_params(db_cmd_t* cmd)
+static int create_pg_params(db_cmd_t *cmd)
 {
 	int num;
-	struct pg_cmd* pcmd;
+	struct pg_cmd *pcmd;
 
 	pcmd = DB_GET_PAYLOAD(cmd);
 
 	num = cmd->match_count + cmd->vals_count;
 
-	if (num == 0) return 0;
-	pcmd->params.val = (const char**)pkg_malloc(sizeof(const char*) * num);
-	pcmd->params.len = (int*)pkg_malloc(sizeof(int) * num);
-	pcmd->params.fmt = (int*)pkg_malloc(sizeof(int) * num);
-	
-	if (!pcmd->params.val || 
-		!pcmd->params.len || !pcmd->params.fmt) {
+	if(num == 0)
+		return 0;
+	pcmd->params.val = (const char **)pkg_malloc(sizeof(const char *) * num);
+	pcmd->params.len = (int *)pkg_malloc(sizeof(int) * num);
+	pcmd->params.fmt = (int *)pkg_malloc(sizeof(int) * num);
+
+	if(!pcmd->params.val || !pcmd->params.len || !pcmd->params.fmt) {
 		ERR("postgres: No memory left\n");
 		goto error;
 	}
-	
-	memset(pcmd->params.val, '\0', sizeof(const char*) * num);
+
+	memset(pcmd->params.val, '\0', sizeof(const char *) * num);
 	memset(pcmd->params.len, '\0', sizeof(int) * num);
 	memset(pcmd->params.fmt, '\0', sizeof(int) * num);
 	pcmd->params.n = num;
 	return 0;
 
- error:
+error:
 	free_pg_params(&pcmd->params);
 	return -1;
 }
@@ -147,17 +150,21 @@ static int create_pg_params(db_cmd_t* cmd)
  * the arrays of Oids, values, lengths, and formats supplied
  * to PostgreSQL client API functions like PQexecParams.
  */
-static void free_pg_params(struct pg_params* params)
+static void free_pg_params(struct pg_params *params)
 {
-	if (params == NULL) return;
+	if(params == NULL)
+		return;
 
-	if (params->val) pkg_free(params->val);
-    params->val = NULL;
+	if(params->val)
+		pkg_free(params->val);
+	params->val = NULL;
 
-	if (params->len) pkg_free(params->len);
+	if(params->len)
+		pkg_free(params->len);
 	params->len = NULL;
 
-	if (params->fmt) pkg_free(params->fmt);
+	if(params->fmt)
+		pkg_free(params->fmt);
 	params->fmt = NULL;
 }
 
@@ -172,24 +179,27 @@ static void free_pg_params(struct pg_params* params)
  * @todo Store oid and length as part of pg_fld, instead of the arrays used
  *       as parameters to PQ functions
  */
-static int check_types(db_cmd_t* cmd) 
-{ 
-	struct pg_con* pcon;
-	
+static int check_types(db_cmd_t *cmd)
+{
+	struct pg_con *pcon;
+
 	/* FIXME: The function should take the connection as one of parameters */
 	pcon = DB_GET_PAYLOAD(cmd->ctx->con[db_payload_idx]);
 
-	if (pg_check_fld2pg(cmd->match, pcon->oid)) return -1;
-	if (pg_check_fld2pg(cmd->vals, pcon->oid)) return -1;
-	if (pg_check_pg2fld(cmd->result, pcon->oid)) return -1;
+	if(pg_check_fld2pg(cmd->match, pcon->oid))
+		return -1;
+	if(pg_check_fld2pg(cmd->vals, pcon->oid))
+		return -1;
+	if(pg_check_pg2fld(cmd->result, pcon->oid))
+		return -1;
 	return 0;
 }
 
 
-static int get_types(db_cmd_t* cmd)
+static int get_types(db_cmd_t *cmd)
 {
-	struct pg_cmd* pcmd;
-	struct pg_con* pcon;
+	struct pg_cmd *pcmd;
+	struct pg_con *pcon;
 	int i, n;
 	pg_type_t *types;
 
@@ -199,14 +209,15 @@ static int get_types(db_cmd_t* cmd)
 
 	types = pcon->oid;
 	pcmd->types = PQdescribePrepared(pcon->con, pcmd->name);
-	
-	if (PQresultStatus(pcmd->types) != PGRES_COMMAND_OK) {
-		ERR("postgres: Error while obtaining description of prepared statement\n");
+
+	if(PQresultStatus(pcmd->types) != PGRES_COMMAND_OK) {
+		ERR("postgres: Error while obtaining description of prepared "
+			"statement\n");
 		return -1;
 	}
 	/* adapted from check_result() in db_mysql */
 	n = PQnfields(pcmd->types);
-	if (cmd->result == NULL) {
+	if(cmd->result == NULL) {
 		/* The result set parameter of db_cmd function was empty, that
 		 * means the command is select * and we have to create the array
 		 * of result fields in the cmd structure manually.
@@ -215,10 +226,11 @@ static int get_types(db_cmd_t* cmd)
 		cmd->result_count = n;
 		for(i = 0; i < cmd->result_count; i++) {
 			struct pg_fld *f;
-			if (pg_fld(cmd->result + i, cmd->table.s) < 0) goto error;
+			if(pg_fld(cmd->result + i, cmd->table.s) < 0)
+				goto error;
 			f = DB_GET_PAYLOAD(cmd->result + i);
-			f->name = pkg_malloc(strlen(PQfname(pcmd->types, i))+1);
-			if (f->name == NULL) {
+			f->name = pkg_malloc(strlen(PQfname(pcmd->types, i)) + 1);
+			if(f->name == NULL) {
 				ERR("postgres: Out of private memory\n");
 				goto error;
 			}
@@ -226,8 +238,9 @@ static int get_types(db_cmd_t* cmd)
 			cmd->result[i].name = f->name;
 		}
 	} else {
-		if (cmd->result_count != n) {
-			BUG("postgres: Number of fields in PQresult does not match number of parameters in DB API\n");
+		if(cmd->result_count != n) {
+			BUG("postgres: Number of fields in PQresult does not match number "
+				"of parameters in DB API\n");
 			goto error;
 		}
 	}
@@ -239,33 +252,37 @@ static int get_types(db_cmd_t* cmd)
 	 */
 	for(i = 0; i < cmd->result_count; i++) {
 		Oid type = PQftype(pcmd->types, i);
-		if (cmd->result[i].type != DB_NONE) continue;
+		if(cmd->result[i].type != DB_NONE)
+			continue;
 
-		if ((type == types[PG_INT2].oid) || (type == types[PG_INT4].oid) || (type == types[PG_INT8].oid))
+		if((type == types[PG_INT2].oid) || (type == types[PG_INT4].oid)
+				|| (type == types[PG_INT8].oid))
 			cmd->result[i].type = DB_INT;
 
-		else if (type == types[PG_FLOAT4].oid)
+		else if(type == types[PG_FLOAT4].oid)
 			cmd->result[i].type = DB_FLOAT;
 
-		else if (type == types[PG_FLOAT8].oid)
+		else if(type == types[PG_FLOAT8].oid)
 			cmd->result[i].type = DB_DOUBLE;
 
-		else if ((type == types[PG_TIMESTAMP].oid) || (type == types[PG_TIMESTAMPTZ].oid))
+		else if((type == types[PG_TIMESTAMP].oid)
+				|| (type == types[PG_TIMESTAMPTZ].oid))
 			cmd->result[i].type = DB_DATETIME;
 
-		else if ((type == types[PG_VARCHAR].oid) || (type == types[PG_CHAR].oid) || (type == types[PG_TEXT].oid))
+		else if((type == types[PG_VARCHAR].oid) || (type == types[PG_CHAR].oid)
+				|| (type == types[PG_TEXT].oid))
 			cmd->result[i].type = DB_STR;
 
-		else if ((type == types[PG_BIT].oid) || (type == types[PG_VARBIT].oid))
+		else if((type == types[PG_BIT].oid) || (type == types[PG_VARBIT].oid))
 			cmd->result[i].type = DB_BITMAP;
 
-		else if (type == types[PG_BYTE].oid)
+		else if(type == types[PG_BYTE].oid)
 			cmd->result[i].type = DB_BLOB;
 
-		else
-		{
-			ERR("postgres: Unsupported PostgreSQL column type: %d, table: %s, column: %s\n",
-				type, cmd->table.s, PQfname(pcmd->types, i));
+		else {
+			ERR("postgres: Unsupported PostgreSQL column type: %d, table: %s, "
+				"column: %s\n",
+					type, cmd->table.s, PQfname(pcmd->types, i));
 			goto error;
 		}
 	}
@@ -275,82 +292,94 @@ error:
 }
 
 
-int pg_cmd(db_cmd_t* cmd)
+int pg_cmd(db_cmd_t *cmd)
 {
-	struct pg_cmd* pcmd;
- 
-	pcmd = (struct pg_cmd*)pkg_malloc(sizeof(struct pg_cmd));
-	if (pcmd == NULL) {
+	struct pg_cmd *pcmd;
+
+	pcmd = (struct pg_cmd *)pkg_malloc(sizeof(struct pg_cmd));
+	if(pcmd == NULL) {
 		ERR("postgres: No memory left\n");
 		goto error;
 	}
 	memset(pcmd, '\0', sizeof(struct pg_cmd));
-	if (db_drv_init(&pcmd->gen, pg_cmd_free) < 0) goto error;
+	if(db_drv_init(&pcmd->gen, pg_cmd_free) < 0)
+		goto error;
 
 	switch(cmd->type) {
-	case DB_PUT:
-		if (build_insert_sql(&pcmd->sql_cmd, cmd) < 0) goto error;
-		break;
-		
-	case DB_DEL:
-		if (build_delete_sql(&pcmd->sql_cmd, cmd) < 0) goto error;
-		break;
-
-	case DB_GET:
-		if (build_select_sql(&pcmd->sql_cmd, cmd) < 0) goto error;
-		break;
-
-	case DB_UPD:
-		if (build_update_sql(&pcmd->sql_cmd, cmd) < 0) goto error;
-		break;
-		
-	case DB_SQL:
-		pcmd->sql_cmd.s = (char*)pkg_malloc(cmd->table.len + 1);
-		if (pcmd->sql_cmd.s == NULL) {
-			ERR("postgres: Out of private memory\n");
-			goto error;
-		}
-		memcpy(pcmd->sql_cmd.s,cmd->table.s, cmd->table.len);
-		pcmd->sql_cmd.s[cmd->table.len] = '\0';
-		pcmd->sql_cmd.len = cmd->table.len;
-        break;
+		case DB_PUT:
+			if(build_insert_sql(&pcmd->sql_cmd, cmd) < 0)
+				goto error;
+			break;
+
+		case DB_DEL:
+			if(build_delete_sql(&pcmd->sql_cmd, cmd) < 0)
+				goto error;
+			break;
+
+		case DB_GET:
+			if(build_select_sql(&pcmd->sql_cmd, cmd) < 0)
+				goto error;
+			break;
+
+		case DB_UPD:
+			if(build_update_sql(&pcmd->sql_cmd, cmd) < 0)
+				goto error;
+			break;
+
+		case DB_SQL:
+			pcmd->sql_cmd.s = (char *)pkg_malloc(cmd->table.len + 1);
+			if(pcmd->sql_cmd.s == NULL) {
+				ERR("postgres: Out of private memory\n");
+				goto error;
+			}
+			memcpy(pcmd->sql_cmd.s, cmd->table.s, cmd->table.len);
+			pcmd->sql_cmd.s[cmd->table.len] = '\0';
+			pcmd->sql_cmd.len = cmd->table.len;
+			break;
 	}
 
 	DB_SET_PAYLOAD(cmd, pcmd);
 
 	/* Create parameter arrays for PostgreSQL API functions */
-	if (create_pg_params(cmd) < 0) goto error;	
+	if(create_pg_params(cmd) < 0)
+		goto error;
 
 	/* Generate a unique name for the command on the server */
-	if (gen_cmd_name(cmd) != 0) goto error; 
+	if(gen_cmd_name(cmd) != 0)
+		goto error;
 
 	/* Upload the command to the server */
-	if (upload_cmd(cmd) != 0) goto error;
+	if(upload_cmd(cmd) != 0)
+		goto error;
 
 	/* Obtain the description of the uploaded command, this includes
 	 * information about result and parameter fields */
-	if (get_types(cmd) != 0) goto error;
+	if(get_types(cmd) != 0)
+		goto error;
 
 	/* Update fields based on the information retrieved from the */
-	if (pg_resolve_param_oids(cmd->vals, cmd->match,
-							  cmd->vals_count, cmd->match_count,
-							  pcmd->types)) 
+	if(pg_resolve_param_oids(cmd->vals, cmd->match, cmd->vals_count,
+			   cmd->match_count, pcmd->types))
 		goto error;
-	if (pg_resolve_result_oids(cmd->result, cmd->result_count, pcmd->types)) 
+	if(pg_resolve_result_oids(cmd->result, cmd->result_count, pcmd->types))
 		goto error;
 
-	if (check_types(cmd)) goto error;
+	if(check_types(cmd))
+		goto error;
 
 	return 0;
 
- error:
-	if (pcmd) {
+error:
+	if(pcmd) {
 		DB_SET_PAYLOAD(cmd, NULL);
 		free_pg_params(&pcmd->params);
 
-		if (pcmd->types) PQclear(pcmd->types);
-		if (pcmd->name) pkg_free(pcmd->name);
-		if (pcmd->sql_cmd.s) pkg_free(pcmd->sql_cmd.s);
+		if(pcmd->types)
+			PQclear(pcmd->types);
+		if(pcmd->name)
+			pkg_free(pcmd->name);
+		if(pcmd->sql_cmd.s)
+			pkg_free(pcmd->sql_cmd.s);
 
 		db_drv_free(&pcmd->gen);
 		pkg_free(pcmd);
@@ -359,13 +388,13 @@ int pg_cmd(db_cmd_t* cmd)
 }
 
 
-int pg_getopt(db_cmd_t* cmd, char* optname, va_list ap)
+int pg_getopt(db_cmd_t *cmd, char *optname, va_list ap)
 {
-	long long* id;
+	long long *id;
 
-	if (!strcasecmp("last_id", optname)) {
-		id = va_arg(ap, long long*);
-		if (id == NULL) {
+	if(!strcasecmp("last_id", optname)) {
+		id = va_arg(ap, long long *);
+		if(id == NULL) {
 			BUG("postgres: NULL pointer passed to 'last_id' option\n");
 			goto error;
 		}
@@ -375,12 +404,12 @@ int pg_getopt(db_cmd_t* cmd, char* optname, va_list ap)
 	}
 	return 0;
 
- error:
+error:
 	return -1;
 }
 
 
-int pg_setopt(db_cmd_t* cmd, char* optname, va_list ap)
+int pg_setopt(db_cmd_t *cmd, char *optname, va_list ap)
 {
 	return 1;
 }
@@ -393,11 +422,11 @@ int pg_setopt(db_cmd_t* cmd, char* optname, va_list ap)
  * @retval 0 on success.
  * @retval A negative number on error.
  */
-static int upload_cmd(db_cmd_t* cmd)
+static int upload_cmd(db_cmd_t *cmd)
 {
-	struct pg_cmd* pcmd;
-	struct pg_con* pcon;
-	PGresult* res;
+	struct pg_cmd *pcmd;
+	struct pg_con *pcon;
+	PGresult *res;
 	int st;
 
 	pcmd = DB_GET_PAYLOAD(cmd);
@@ -405,16 +434,17 @@ static int upload_cmd(db_cmd_t* cmd)
 	pcon = DB_GET_PAYLOAD(cmd->ctx->con[db_payload_idx]);
 
 	DBG("postgres: Uploading command '%s': '%s'\n", pcmd->name,
-		pcmd->sql_cmd.s);
+			pcmd->sql_cmd.s);
+
+	res = PQprepare(pcon->con, pcmd->name, pcmd->sql_cmd.s,
+			(cmd->match_count + cmd->vals_count), NULL);
 
-	res = PQprepare(pcon->con, pcmd->name, pcmd->sql_cmd.s, (cmd->match_count + cmd->vals_count), NULL);
-	
 	st = PQresultStatus(res);
 
-	if (st != PGRES_COMMAND_OK && st != PGRES_NONFATAL_ERROR &&
-		st != PGRES_TUPLES_OK) {
-		ERR("postgres: Error while uploading command to server: %d, %s", 
-			st, PQresultErrorMessage(res));
+	if(st != PGRES_COMMAND_OK && st != PGRES_NONFATAL_ERROR
+			&& st != PGRES_TUPLES_OK) {
+		ERR("postgres: Error while uploading command to server: %d, %s", st,
+				PQresultErrorMessage(res));
 		ERR("postgres: Command: '%s'\n", pcmd->sql_cmd.s);
 		PQclear(res);
 		return -1;
@@ -425,15 +455,15 @@ static int upload_cmd(db_cmd_t* cmd)
 }
 
 
-int pg_cmd_exec(db_res_t* res, db_cmd_t* cmd)
+int pg_cmd_exec(db_res_t *res, db_cmd_t *cmd)
 {
-	PGresult* tmp;
+	PGresult *tmp;
 	int i, err, stat;
-	db_con_t* con;
-	struct pg_cmd* pcmd;
-	struct pg_con* pcon;
-	struct pg_uri* puri;
-	struct pg_res* pres;
+	db_con_t *con;
+	struct pg_cmd *pcmd;
+	struct pg_con *pcon;
+	struct pg_uri *puri;
+	struct pg_res *pres;
 
 	/* First things first: retrieve connection info from the currently active
 	 * connection and also mysql payload from the database command
@@ -446,87 +476,88 @@ int pg_cmd_exec(db_res_t* res, db_cmd_t* cmd)
 	for(i = 0; i <= pg_retries; i++) {
 		/* Convert parameters from DB-API format to the format accepted
 		 * by PostgreSQL */
-		if (pg_fld2pg(&pcmd->params, 0, pcon->oid, cmd->match, pcon->flags) != 0) 
+		if(pg_fld2pg(&pcmd->params, 0, pcon->oid, cmd->match, pcon->flags) != 0)
+			return 1;
+
+		if(pg_fld2pg(&pcmd->params, cmd->match_count, pcon->oid, cmd->vals,
+				   pcon->flags)
+				!= 0)
 			return 1;
 
-		if (pg_fld2pg(&pcmd->params, cmd->match_count,
-					  pcon->oid, cmd->vals, pcon->flags) != 0) return 1;
-		
 		/* Execute the statement */
-		tmp = PQexecPrepared(pcon->con, pcmd->name,
-							 pcmd->params.n,
-							 pcmd->params.val, pcmd->params.len,
-							 pcmd->params.fmt, 1);
-		if (!tmp) {
+		tmp = PQexecPrepared(pcon->con, pcmd->name, pcmd->params.n,
+				pcmd->params.val, pcmd->params.len, pcmd->params.fmt, 1);
+		if(!tmp) {
 			ERR("postgres: PQexecPrepared returned no result\n");
 			continue;
 		}
 
 		switch(PQresultStatus(tmp)) {
-		case PGRES_COMMAND_OK:
-		case PGRES_NONFATAL_ERROR:
-		case PGRES_TUPLES_OK:
-			if (res) {
-				pres = DB_GET_PAYLOAD(res);
-				pres->res = tmp;
-				pres->rows = PQntuples(tmp);
-			} else {
-				PQclear(tmp);
-			}
-			return 0;
-			
-		default:
-			break;
+			case PGRES_COMMAND_OK:
+			case PGRES_NONFATAL_ERROR:
+			case PGRES_TUPLES_OK:
+				if(res) {
+					pres = DB_GET_PAYLOAD(res);
+					pres->res = tmp;
+					pres->rows = PQntuples(tmp);
+				} else {
+					PQclear(tmp);
+				}
+				return 0;
+
+			default:
+				break;
 		}
-		ERR("postgres: Command on server %s failed: %s: %s\n", 
-			puri->host, PQresStatus(PQresultStatus(tmp)), 
-			PQresultErrorMessage(tmp));
+		ERR("postgres: Command on server %s failed: %s: %s\n", puri->host,
+				PQresStatus(PQresultStatus(tmp)), PQresultErrorMessage(tmp));
 		PQclear(tmp);
 
 		/* Command failed, first of all determine the status of the connection
 		 * to server */
-		if (PQstatus(pcon->con) != CONNECTION_OK) {
-			INFO("postgres: Connection to server %s disconnected, attempting reconnect\n", 
-				 puri->host);
+		if(PQstatus(pcon->con) != CONNECTION_OK) {
+			INFO("postgres: Connection to server %s disconnected, attempting "
+				 "reconnect\n",
+					puri->host);
 			pg_con_disconnect(con);
-			if (pg_con_connect(con)) {
-				INFO("postgres: Failed to reconnect server %s, giving up\n", 
-					 puri->host);
+			if(pg_con_connect(con)) {
+				INFO("postgres: Failed to reconnect server %s, giving up\n",
+						puri->host);
 				return -1;
 			}
-			INFO("postgres: Successfully reconnected server on %s\n", 
-				 puri->host);
+			INFO("postgres: Successfully reconnected server on %s\n",
+					puri->host);
 		}
 
 		/* Connection is either connected or has been successfully reconnected, 
 		 * now figure out if the prepared command on the server still exist
 		 */
 		tmp = PQdescribePrepared(pcon->con, pcmd->name);
-		if (tmp == NULL) {
+		if(tmp == NULL) {
 			ERR("postgres: PQdescribePrepared returned no result\n");
-		    continue;
+			continue;
 		}
 		stat = PQresultStatus(tmp);
 		PQclear(tmp);
-		switch (stat) {
-		case PGRES_COMMAND_OK:
-		case PGRES_NONFATAL_ERROR:
-		case PGRES_TUPLES_OK:
-			INFO("postgres: Command %s on server %s still exists, reusing\n",
-				 pcmd->name, puri->host);
-			/* Command is there, retry */
-			continue;
-		default:
-			break;
+		switch(stat) {
+			case PGRES_COMMAND_OK:
+			case PGRES_NONFATAL_ERROR:
+			case PGRES_TUPLES_OK:
+				INFO("postgres: Command %s on server %s still exists, "
+					 "reusing\n",
+						pcmd->name, puri->host);
+				/* Command is there, retry */
+				continue;
+			default:
+				break;
 		}
 
 		/* Upload again */
 		INFO("postgres: Command %s on server %s missing, uploading\n",
-			 pcmd->name, puri->host);
+				pcmd->name, puri->host);
 		err = upload_cmd(cmd);
-		if (err < 0) {
+		if(err < 0) {
 			continue;
-		} else if (err > 0) {
+		} else if(err > 0) {
 			/* DB API error, this is a serious problem such
 			 * as memory allocation failure, bail out
 			 */
@@ -535,34 +566,38 @@ int pg_cmd_exec(db_res_t* res, db_cmd_t* cmd)
 	}
 
 	INFO("postgres: Failed to execute command %s on server %s, giving up\n",
-		 pcmd->name, puri->host);
+			pcmd->name, puri->host);
 	return -1;
 }
 
 
-int pg_cmd_first(db_res_t* res)
+int pg_cmd_first(db_res_t *res)
 {
-	struct pg_res* pres;
+	struct pg_res *pres;
 
 	pres = DB_GET_PAYLOAD(res);
 
-	if (pres->rows <= 0) return 1; /* Empty table */
+	if(pres->rows <= 0)
+		return 1; /* Empty table */
 	pres->row = 0;
 	return pg_cmd_next(res);
 }
 
 
-int pg_cmd_next(db_res_t* res)
+int pg_cmd_next(db_res_t *res)
 {
-	struct pg_res* pres;
-	struct pg_con* pcon;
+	struct pg_res *pres;
+	struct pg_con *pcon;
 
 	pres = DB_GET_PAYLOAD(res);
 	pcon = DB_GET_PAYLOAD(res->cmd->ctx->con[db_payload_idx]);
 
-	if (pres->row >= pres->rows) return 1;
+	if(pres->row >= pres->rows)
+		return 1;
 
-	if (pg_pg2fld(res->cmd->result, pres->res, pres->row, pcon->oid, pcon->flags)) return -1;
+	if(pg_pg2fld(
+			   res->cmd->result, pres->res, pres->row, pcon->oid, pcon->flags))
+		return -1;
 	res->cur_rec->fld = res->cmd->result;
 	pres->row++;
 	return 0;

+ 15 - 13
src/modules/db_postgres/pg_cmd.h

@@ -44,11 +44,12 @@
 #include <stdarg.h>
 #include <libpq-fe.h>
 
-struct pg_params {
+struct pg_params
+{
 	int n;
-	const char** val;
-	int* len;
-	int* fmt;
+	const char **val;
+	int *len;
+	int *fmt;
 };
 
 
@@ -56,13 +57,14 @@ struct pg_params {
  * This data structure extends the generic data structure db_cmd in the
  * database API with data specific to the postgresql driver.
  */
-struct pg_cmd {
+struct pg_cmd
+{
 	db_drv_t gen; /**< Generic part of the data structure (must be first */
-	char* name;   /**< Name of the prepared query on the server */
+	char *name;   /**< Name of the prepared query on the server */
 	str sql_cmd;  /**< Database command represented in SQL language */
 
 	struct pg_params params;
-	PGresult* types;
+	PGresult *types;
 };
 
 
@@ -73,7 +75,7 @@ struct pg_cmd {
  * @param cmd A generic db_cmd structure to which the newly created pg_cmd
  *            structure will be attached.
  */
-int pg_cmd(db_cmd_t* cmd);
+int pg_cmd(db_cmd_t *cmd);
 
 
 /** The main execution function in postgres SER driver.
@@ -89,7 +91,7 @@ int pg_cmd(db_cmd_t* cmd);
  * @retval A negative number if the database server failed to execute command
  * @retval A positive number if there was an error on client side (SER)
  */
-int pg_cmd_exec(db_res_t* res, db_cmd_t* cmd);
+int pg_cmd_exec(db_res_t *res, db_cmd_t *cmd);
 
 
 /** Retrieves the first record from a result set received from PostgreSQL server.
@@ -103,7 +105,7 @@ int pg_cmd_exec(db_res_t* res, db_cmd_t* cmd);
  * @retval 1 If the result is empty.
  * @retval A negative number on error.
  */
-int pg_cmd_first(db_res_t* res);
+int pg_cmd_first(db_res_t *res);
 
 
 /** Retrieves the next record from a result set received from PostgreSQL server.
@@ -117,7 +119,7 @@ int pg_cmd_first(db_res_t* res);
  * @retval 1 If there are no more records in the result.
  * @retval A negative number on error.
  */
-int pg_cmd_next(db_res_t* res);
+int pg_cmd_next(db_res_t *res);
 
 
 /** Retrieves the value of an db_cmd option.
@@ -130,7 +132,7 @@ int pg_cmd_next(db_res_t* res);
  * @retval A positive number of the option is not supported/implemented.
  * @retval A negative number on error.
  */
-int pg_getopt(db_cmd_t* cmd, char* optname, va_list ap);
+int pg_getopt(db_cmd_t *cmd, char *optname, va_list ap);
 
 
 /** Sets the value of an db_cmd option.
@@ -143,6 +145,6 @@ int pg_getopt(db_cmd_t* cmd, char* optname, va_list ap);
  * @retval A positive number of the option is not supported/implemented.
  * @retval A negative number on error.
  */
-int pg_setopt(db_cmd_t* cmd, char* optname, va_list ap);
+int pg_setopt(db_cmd_t *cmd, char *optname, va_list ap);
 
 #endif /* _PG_CMD_H */

+ 86 - 72
src/modules/db_postgres/pg_con.c

@@ -49,7 +49,7 @@
 /* Override the default notice processor to output the messages
  * using SER's output subsystem.
  */
-static void notice_processor(void* arg, const char* message)
+static void notice_processor(void *arg, const char *message)
 {
 	LOG(L_NOTICE, "postgres: %s\n", message);
 }
@@ -67,38 +67,40 @@ static void notice_processor(void* arg, const char* message)
  * @retval 1 If the server stores timestamps as 8-byte integers.
  * @retval A negative number on error.
  */
-static int timestamp_format(PGconn* con)
+static int timestamp_format(PGconn *con)
 {
 	unsigned long long offset;
-	PGresult* res = 0;
-	char* val;
+	PGresult *res = 0;
+	char *val;
 	str sql;
 
-	if (build_timestamp_format_sql(&sql) != 0) {
-		ERR("postgres: Error while building SQL query to obtain timestamp format\n");
+	if(build_timestamp_format_sql(&sql) != 0) {
+		ERR("postgres: Error while building SQL query to obtain timestamp "
+			"format\n");
 		return -1;
 	}
 	res = PQexecParams(con, sql.s, 0, 0, 0, 0, 0, 1);
 	pkg_free(sql.s);
 
-	if (PQfformat(res, 0) != 1) {
+	if(PQfformat(res, 0) != 1) {
 		ERR("postgres: Binary format expected but server sent text\n");
 		goto error;
 	}
 
-	if (PQntuples(res) != 1) {
-		ERR("postgres: Only one column expected, %d received\n", PQntuples(res));
+	if(PQntuples(res) != 1) {
+		ERR("postgres: Only one column expected, %d received\n",
+				PQntuples(res));
 		goto error;
 	}
 
-	if (PQnfields(res) != 1) {
+	if(PQnfields(res) != 1) {
 		ERR("postgres: Only one row expected, %d received\n", PQnfields(res));
 		goto error;
 	}
 
 	val = PQgetvalue(res, 0, 0);
-	offset = ((unsigned long long)ntohl(((unsigned int*)val)[0]) << 32)
-		+ ntohl(((unsigned int*)val)[1]);
+	offset = ((unsigned long long)ntohl(((unsigned int *)val)[0]) << 32)
+			 + ntohl(((unsigned int *)val)[1]);
 
 	PQclear(res);
 
@@ -110,15 +112,15 @@ static int timestamp_format(PGconn* con)
 	 * when the memory location occupied by the variable is read as unsigned
 	 * long long.
 	 */
-	if (offset == 1000000) {
-	        DBG("postgres: Server uses int8 format for timestamps.\n");
+	if(offset == 1000000) {
+		DBG("postgres: Server uses int8 format for timestamps.\n");
 		return 1;
 	} else {
 		DBG("postgres: Server uses double format for timestamps.\n");
 		return 0;
 	}
 
- error:
+error:
 	PQclear(res);
 	return -1;
 }
@@ -135,24 +137,28 @@ static int timestamp_format(PGconn* con)
  * @retval 0 If executed successfully.
  * @retval A negative number on error.
  */
-static int get_oids(db_con_t* con)
+static int get_oids(db_con_t *con)
 {
-	struct pg_con* pcon;
-	PGresult* res = NULL;
+	struct pg_con *pcon;
+	PGresult *res = NULL;
 	str sql;
 
 	pcon = DB_GET_PAYLOAD(con);
-	if (build_select_oid_sql(&sql) < 0) goto error;
+	if(build_select_oid_sql(&sql) < 0)
+		goto error;
 	res = PQexec(pcon->con, sql.s);
 	pkg_free(sql.s);
-	if (res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK) goto error;
+	if(res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK)
+		goto error;
 	pcon->oid = pg_new_oid_table(res);
 	PQclear(res);
-	if (pcon->oid == NULL) goto error;
+	if(pcon->oid == NULL)
+		goto error;
 	return 0;
 
- error:
-	if (res) PQclear(res);
+error:
+	if(res)
+		PQclear(res);
 	return -1;
 }
 
@@ -163,54 +169,58 @@ static int get_oids(db_con_t* con)
  * @param con A generic db_con connection structure.
  * @param payload PostgreSQL specific payload to be freed.
  */
-static void pg_con_free(db_con_t* con, struct pg_con* payload)
+static void pg_con_free(db_con_t *con, struct pg_con *payload)
 {
-	if (!payload) return;
+	if(!payload)
+		return;
 
 	/* Delete the structure only if there are no more references
 	 * to it in the connection pool
 	 */
-	if (db_pool_remove((db_pool_entry_t*)payload) == 0) return;
+	if(db_pool_remove((db_pool_entry_t *)payload) == 0)
+		return;
 
 	db_pool_entry_free(&payload->gen);
 	pg_destroy_oid_table(payload->oid);
-	if (payload->con) PQfinish(payload->con);
+	if(payload->con)
+		PQfinish(payload->con);
 	pkg_free(payload);
 }
 
 
-int pg_con(db_con_t* con)
+int pg_con(db_con_t *con)
 {
-	struct pg_con* pcon;
+	struct pg_con *pcon;
 
 	/* First try to lookup the connection in the connection pool and
 	 * re-use it if a match is found
 	 */
-	pcon = (struct pg_con*)db_pool_get(con->uri);
-	if (pcon) {
+	pcon = (struct pg_con *)db_pool_get(con->uri);
+	if(pcon) {
 		DBG("postgres: Connection to %.*s:%.*s found in connection pool\n",
-			con->uri->scheme.len, ZSW(con->uri->scheme.s),
-			con->uri->body.len, ZSW(con->uri->body.s));
+				con->uri->scheme.len, ZSW(con->uri->scheme.s),
+				con->uri->body.len, ZSW(con->uri->body.s));
 		goto found;
 	}
 
-	pcon = (struct pg_con*)pkg_malloc(sizeof(struct pg_con));
-	if (!pcon) {
+	pcon = (struct pg_con *)pkg_malloc(sizeof(struct pg_con));
+	if(!pcon) {
 		LOG(L_ERR, "postgres: No memory left\n");
 		goto error;
 	}
 	memset(pcon, '\0', sizeof(struct pg_con));
-	if (db_pool_entry_init(&pcon->gen, pg_con_free, con->uri) < 0) goto error;
+	if(db_pool_entry_init(&pcon->gen, pg_con_free, con->uri) < 0)
+		goto error;
 
 	DBG("postgres: Preparing new connection to: %.*s:%.*s\n",
-		con->uri->scheme.len, ZSW(con->uri->scheme.s),
-		con->uri->body.len, ZSW(con->uri->body.s));
+			con->uri->scheme.len, ZSW(con->uri->scheme.s), con->uri->body.len,
+			ZSW(con->uri->body.s));
 
 	/* Put the newly created postgres connection into the pool */
-	db_pool_put((struct db_pool_entry*)pcon);
+	db_pool_put((struct db_pool_entry *)pcon);
 	DBG("postgres: Connection stored in connection pool\n");
 
- found:
+found:
 	/* Attach driver payload to the db_con structure and set connect and
 	 * disconnect functions
 	 */
@@ -219,8 +229,8 @@ int pg_con(db_con_t* con)
 	con->disconnect = pg_con_disconnect;
 	return 0;
 
- error:
-	if (pcon) {
+error:
+	if(pcon) {
 		db_pool_entry_free(&pcon->gen);
 		pkg_free(pcon);
 	}
@@ -228,11 +238,11 @@ int pg_con(db_con_t* con)
 }
 
 
-int pg_con_connect(db_con_t* con)
+int pg_con_connect(db_con_t *con)
 {
-	struct pg_con* pcon;
-	struct pg_uri* puri;
-	char* port_str;
+	struct pg_con *pcon;
+	struct pg_uri *puri;
+	char *port_str;
 	int ret, i = 0;
 	const char *keywords[10], *values[10];
 	char to[16];
@@ -241,13 +251,13 @@ int pg_con_connect(db_con_t* con)
 	puri = DB_GET_PAYLOAD(con->uri);
 
 	/* Do not reconnect already connected connections */
-	if (pcon->flags & PG_CONNECTED) return 0;
+	if(pcon->flags & PG_CONNECTED)
+		return 0;
 
-	DBG("postgres: Connecting to %.*s:%.*s\n",
-		con->uri->scheme.len, ZSW(con->uri->scheme.s),
-		con->uri->body.len, ZSW(con->uri->body.s));
+	DBG("postgres: Connecting to %.*s:%.*s\n", con->uri->scheme.len,
+			ZSW(con->uri->scheme.s), con->uri->body.len, ZSW(con->uri->body.s));
 
-	if (puri->port > 0) {
+	if(puri->port > 0) {
 		port_str = int2str(puri->port, 0);
 		keywords[i] = "port";
 		values[i++] = port_str;
@@ -255,7 +265,7 @@ int pg_con_connect(db_con_t* con)
 		port_str = NULL;
 	}
 
-	if (pcon->con) {
+	if(pcon->con) {
 		PQfinish(pcon->con);
 		pcon->con = NULL;
 	}
@@ -268,8 +278,8 @@ int pg_con_connect(db_con_t* con)
 	values[i++] = puri->username;
 	keywords[i] = "password";
 	values[i++] = puri->password;
-	if (pg_timeout > 0) {
-		snprintf(to, sizeof(to)-1, "%d", pg_timeout + 3);
+	if(pg_timeout > 0) {
+		snprintf(to, sizeof(to) - 1, "%d", pg_timeout + 3);
 		keywords[i] = "connect_timeout";
 		values[i++] = to;
 	}
@@ -278,12 +288,12 @@ int pg_con_connect(db_con_t* con)
 
 	pcon->con = PQconnectdbParams(keywords, values, 1);
 
-	if (pcon->con == NULL) {
+	if(pcon->con == NULL) {
 		ERR("postgres: PQconnectdbParams ran out of memory\n");
 		goto error;
 	}
 
-	if (PQstatus(pcon->con) != CONNECTION_OK) {
+	if(PQstatus(pcon->con) != CONNECTION_OK) {
 		ERR("postgres: %s\n", PQerrorMessage(pcon->con));
 		goto error;
 	}
@@ -293,56 +303,60 @@ int pg_con_connect(db_con_t* con)
 
 #ifdef HAVE_PGSERVERVERSION
 	DBG("postgres: Connected. Protocol version=%d, Server version=%d\n",
-	    PQprotocolVersion(pcon->con), PQserverVersion(pcon->con));
+			PQprotocolVersion(pcon->con), PQserverVersion(pcon->con));
 #else
 	DBG("postgres: Connected. Protocol version=%d, Server version=%d\n",
-	    PQprotocolVersion(pcon->con), 0 );
+			PQprotocolVersion(pcon->con), 0);
 #endif
 
 #if defined(SO_KEEPALIVE) && defined(TCP_KEEPIDLE)
-	if (pg_keepalive) {
+	if(pg_keepalive) {
 		i = 1;
-		if(setsockopt(PQsocket(pcon->con), SOL_SOCKET, SO_KEEPALIVE, &i,
-				sizeof(i))<0) {
+		if(setsockopt(
+				   PQsocket(pcon->con), SOL_SOCKET, SO_KEEPALIVE, &i, sizeof(i))
+				< 0) {
 			LM_WARN("failed to set socket option keepalive\n");
 		}
 		if(setsockopt(PQsocket(pcon->con), IPPROTO_TCP, TCP_KEEPIDLE,
-				&pg_keepalive, sizeof(pg_keepalive))<0) {
+				   &pg_keepalive, sizeof(pg_keepalive))
+				< 0) {
 			LM_WARN("failed to set socket option keepidle\n");
 		}
 	}
 #endif
 
 	ret = timestamp_format(pcon->con);
-	if (ret == 1 || ret == -1) {
+	if(ret == 1 || ret == -1) {
 		/* Assume INT8 representation if detection fails */
 		pcon->flags |= PG_INT8_TIMESTAMP;
 	} else {
 		pcon->flags &= ~PG_INT8_TIMESTAMP;
 	}
 
-	if (get_oids(con) < 0) goto error;
+	if(get_oids(con) < 0)
+		goto error;
 
 	pcon->flags |= PG_CONNECTED;
 	return 0;
 
- error:
-	if (pcon->con) PQfinish(pcon->con);
+error:
+	if(pcon->con)
+		PQfinish(pcon->con);
 	pcon->con = NULL;
 	return -1;
 }
 
 
-void pg_con_disconnect(db_con_t* con)
+void pg_con_disconnect(db_con_t *con)
 {
-	struct pg_con* pcon;
+	struct pg_con *pcon;
 
 	pcon = DB_GET_PAYLOAD(con);
-	if ((pcon->flags & PG_CONNECTED) == 0) return;
+	if((pcon->flags & PG_CONNECTED) == 0)
+		return;
 
-	DBG("postgres: Disconnecting from %.*s:%.*s\n",
-		con->uri->scheme.len, ZSW(con->uri->scheme.s),
-		con->uri->body.len, ZSW(con->uri->body.s));
+	DBG("postgres: Disconnecting from %.*s:%.*s\n", con->uri->scheme.len,
+			ZSW(con->uri->scheme.s), con->uri->body.len, ZSW(con->uri->body.s));
 
 	PQfinish(pcon->con);
 	pcon->con = NULL;

+ 15 - 11
src/modules/db_postgres/pg_con.h

@@ -45,9 +45,12 @@
 /** 
  * Per-connection flags for PostgreSQL connections.
  */
-enum pg_con_flags {
-	PG_CONNECTED      = (1 << 0), /**< The connection has been connected successfully */
-	PG_INT8_TIMESTAMP = (1 << 1)  /**< The server uses 8-byte integer format for timestamps */
+enum pg_con_flags
+{
+	PG_CONNECTED =
+			(1 << 0), /**< The connection has been connected successfully */
+	PG_INT8_TIMESTAMP =
+			(1 << 1) /**< The server uses 8-byte integer format for timestamps */
 };
 
 
@@ -56,11 +59,12 @@ enum pg_con_flags {
  * PostgreSQL specific data, such as PostgreSQL connection handle, connection
  * flags, and an array with data types supported by the server.
  */
-typedef struct pg_con {
-	db_pool_entry_t gen;  /**< Generic part of the structure */
-	PGconn* con;          /**< Postgres connection handle */
-	unsigned int flags;   /**< Flags (currently only binary data format) */
-	pg_type_t* oid;       /**< Data types and their Oids obtained from the server */
+typedef struct pg_con
+{
+	db_pool_entry_t gen; /**< Generic part of the structure */
+	PGconn *con;		 /**< Postgres connection handle */
+	unsigned int flags;  /**< Flags (currently only binary data format) */
+	pg_type_t *oid; /**< Data types and their Oids obtained from the server */
 } pg_con_t;
 
 
@@ -72,7 +76,7 @@ typedef struct pg_con {
  * @retval 0 on success
  * @retval A negative number on error
  */
-int pg_con(db_con_t* con);
+int pg_con(db_con_t *con);
 
 
 /** Establish a new connection to server.  
@@ -84,14 +88,14 @@ int pg_con(db_con_t* con);
  * @retval 0 on success.
  * @retval A negative number on error.
  */
-int pg_con_connect(db_con_t* con);
+int pg_con_connect(db_con_t *con);
 
 
 /** Disconnected from PostgreSQL server.
  * Disconnects a previously connected connection to PostgreSQL server.
  * @param con A structure representing the connection to be disconnected.
  */
-void pg_con_disconnect(db_con_t* con);
+void pg_con_disconnect(db_con_t *con);
 
 /** @} */
 

Diff do ficheiro suprimidas por serem muito extensas
+ 428 - 347
src/modules/db_postgres/pg_fld.c


+ 24 - 22
src/modules/db_postgres/pg_fld.h

@@ -40,27 +40,29 @@
 #include "../../lib/srdb2/db_fld.h"
 #include <libpq-fe.h>
 
-struct pg_fld {
+struct pg_fld
+{
 	db_drv_t gen;
 
-	char* name;
+	char *name;
 	/**
 	 * A union of varius data types from db_fld, postgres expects binary
 	 * data in network byte order so we use these variables as temporary
 	 * buffer to store values after the conversion.
 	 */
-	union {
-		int          int4[2]; /**< Integer value in network byte order */
-		short        int2[4];
-		float        flt;     /**< Float value in network byte order */
-		double       dbl;     /**< Double value in network byte order */
-		time_t       time;    /**< Unix timestamp in network byte order */
-		unsigned int bitmap;  /**< Bitmap value in network byte order */ 
-		long long    int8;    /**< 8-byte integer value in network byte order */
-		char         byte[8];
+	union
+	{
+		int int4[2]; /**< Integer value in network byte order */
+		short int2[4];
+		float flt;			 /**< Float value in network byte order */
+		double dbl;			 /**< Double value in network byte order */
+		time_t time;		 /**< Unix timestamp in network byte order */
+		unsigned int bitmap; /**< Bitmap value in network byte order */
+		long long int8;		 /**< 8-byte integer value in network byte order */
+		char byte[8];
 	} v;
 	char buf[INT2STR_MAX_LEN]; /**< Buffer for int2str conversions */
-	Oid oid;                   /**< Type of the field on the server */
+	Oid oid;				   /**< Type of the field on the server */
 };
 
 
@@ -71,12 +73,12 @@ struct pg_fld {
  * @param table Name of the table on the server.
  * @return 0 on success, negative number on error.
  */
-int pg_fld(db_fld_t* fld, char* table);
+int pg_fld(db_fld_t *fld, char *table);
 
-int pg_resolve_param_oids(db_fld_t* vals, db_fld_t* match, 
-						  int n1, int n2, PGresult* res);
+int pg_resolve_param_oids(
+		db_fld_t *vals, db_fld_t *match, int n1, int n2, PGresult *res);
 
-int pg_resolve_result_oids(db_fld_t* fld, int n, PGresult* res);
+int pg_resolve_result_oids(db_fld_t *fld, int n, PGresult *res);
 
 
 /** Converts arrays of db_fld fields to PostgreSQL parameters.
@@ -94,8 +96,8 @@ int pg_resolve_result_oids(db_fld_t* fld, int n, PGresult* res);
  * @todo Support for DB_NONE in pg_pg2fld and pg_check_pg2fld
  * @todo local->UTC conversion (also check the SQL command in ser-oob)
  */
-int pg_fld2pg(struct pg_params* dst, int off, pg_type_t* types, 
-			  db_fld_t* src, unsigned int flags);
+int pg_fld2pg(struct pg_params *dst, int off, pg_type_t *types, db_fld_t *src,
+		unsigned int flags);
 
 
 /** Converts fields from result in PGresult format into SER format.
@@ -112,8 +114,8 @@ int pg_fld2pg(struct pg_params* dst, int off, pg_type_t* types,
  * @retval A negative number on error.
  * @todo UTC->local conversion
  */
-int pg_pg2fld(db_fld_t* dst, PGresult* src, int row, pg_type_t* types, 
-			  unsigned int flags);
+int pg_pg2fld(db_fld_t *dst, PGresult *src, int row, pg_type_t *types,
+		unsigned int flags);
 
 
 /** Checks if all db_fld fields have types compatible with corresponding field 
@@ -125,7 +127,7 @@ int pg_pg2fld(db_fld_t* dst, PGresult* src, int row, pg_type_t* types,
  * @retval 0 on success
  * @retval A negative number on error.
  */
-int pg_check_fld2pg(db_fld_t* fld, pg_type_t* types);
+int pg_check_fld2pg(db_fld_t *fld, pg_type_t *types);
 
 /** Checks if all db_fld fields have types compatible with corresponding field 
  * types on the server.
@@ -136,7 +138,7 @@ int pg_check_fld2pg(db_fld_t* fld, pg_type_t* types);
  * @retval 0 on success
  * @retval A negative number on error.
  */
-int pg_check_pg2fld(db_fld_t* fld, pg_type_t* types);
+int pg_check_pg2fld(db_fld_t *fld, pg_type_t *types);
 
 
 #endif /* _PG_FLD_H */

+ 167 - 184
src/modules/db_postgres/pg_mod.c

@@ -1,4 +1,4 @@
-/* 
+/*
  * PostgreSQL Database Driver for Kamailio
  *
  * Portions Copyright (C) 2001-2003 FhG FOKUS
@@ -23,10 +23,10 @@
  */
 
 /** \addtogroup postgres
- * @{ 
+ * @{
  */
 
-/** \file 
+/** \file
  * Postgres module interface.
  */
 
@@ -50,8 +50,9 @@ MODULE_VERSION
 static int pg_mod_init(void);
 static void pg_mod_destroy(void);
 
-int pg_connect_timeout = 0;  /* Default is unlimited */
-int pg_retries = 2;  /* How many times should the module try re-execute failed commands.
+int pg_connect_timeout = 0; /* Default is unlimited */
+int pg_retries =
+		2; /* How many times should the module try re-execute failed commands.
 					  * 0 disables reconnecting */
 
 int pg_lockset = 4;
@@ -62,19 +63,19 @@ int pg_keepalive = 0;
  * Postgres module interface
  */
 static cmd_export_t cmds[] = {
-	{"db_ctx",    (cmd_function)NULL, 0, 0, 0},
-	{"db_con",    (cmd_function)pg_con, 0, 0, 0},
-	{"db_uri",    (cmd_function)pg_uri, 0, 0, 0},
-	{"db_cmd",    (cmd_function)pg_cmd, 0, 0, 0},
-	{"db_put",    (cmd_function)pg_cmd_exec, 0, 0, 0},
-	{"db_del",    (cmd_function)pg_cmd_exec, 0, 0, 0},
-	{"db_get",    (cmd_function)pg_cmd_exec, 0, 0, 0},
-	{"db_upd",    (cmd_function)pg_cmd_exec, 0, 0, 0},
-	{"db_sql",    (cmd_function)pg_cmd_exec, 0, 0, 0},
-	{"db_res",    (cmd_function)pg_res, 0, 0, 0},
-	{"db_fld",    (cmd_function)pg_fld, 0, 0, 0},
-	{"db_first",  (cmd_function)pg_cmd_first, 0, 0, 0},
-	{"db_next",   (cmd_function)pg_cmd_next, 0, 0, 0},
+	{"db_ctx", (cmd_function)NULL, 0, 0, 0},
+	{"db_con", (cmd_function)pg_con, 0, 0, 0},
+	{"db_uri", (cmd_function)pg_uri, 0, 0, 0},
+	{"db_cmd", (cmd_function)pg_cmd, 0, 0, 0},
+	{"db_put", (cmd_function)pg_cmd_exec, 0, 0, 0},
+	{"db_del", (cmd_function)pg_cmd_exec, 0, 0, 0},
+	{"db_get", (cmd_function)pg_cmd_exec, 0, 0, 0},
+	{"db_upd", (cmd_function)pg_cmd_exec, 0, 0, 0},
+	{"db_sql", (cmd_function)pg_cmd_exec, 0, 0, 0},
+	{"db_res", (cmd_function)pg_res, 0, 0, 0},
+	{"db_fld", (cmd_function)pg_fld, 0, 0, 0},
+	{"db_first", (cmd_function)pg_cmd_first, 0, 0, 0},
+	{"db_next", (cmd_function)pg_cmd_next, 0, 0, 0},
 	{"db_setopt", (cmd_function)pg_setopt, 0, 0, 0},
 	{"db_getopt", (cmd_function)pg_getopt, 0, 0, 0},
 	{"db_bind_api", (cmd_function)db_postgres_bind_api, 0, 0, 0},
@@ -86,24 +87,22 @@ static cmd_export_t cmds[] = {
  * Exported parameters
  */
 static param_export_t params[] = {
-	{"retries",         PARAM_INT, &pg_retries },
-	{"lockset",         PARAM_INT, &pg_lockset },
-	{"timeout",         PARAM_INT, &pg_timeout },
-	{"tcp_keepalive",   PARAM_INT, &pg_keepalive },
+	{"retries", PARAM_INT, &pg_retries},
+	{"lockset", PARAM_INT, &pg_lockset},
+	{"timeout", PARAM_INT, &pg_timeout},
+	{"tcp_keepalive", PARAM_INT, &pg_keepalive},
 	{0, 0, 0}
 };
 
 
 struct module_exports exports = {
-	"db_postgres",
-	cmds,
-	0,            /* RPC method */
-	params,       /* module parameters */
-	pg_mod_init,  /* module initialization function */
-	0,            /* response function*/
-	pg_mod_destroy,  /* destroy function */
-	0,            /* oncancel function */
-	0             /* per-child init function */
+	"db_postgres", cmds, 0, /* RPC method */
+	params,					/* module parameters */
+	pg_mod_init,			/* module initialization function */
+	0,						/* response function*/
+	pg_mod_destroy,			/* destroy function */
+	0,						/* oncancel function */
+	0						/* per-child init function */
 };
 
 /*
@@ -132,118 +131,95 @@ CREATE TABLE test (
 int pg_test(void)
 {
 	int i, row;
-	db_ctx_t* db;
-	db_cmd_t* put, *del, *get;
-	db_res_t* result;
-	db_rec_t* rec;
-	char* times;
-
-	db_fld_t int_vals[] = {
-		{.name = "col_bool",        .type = DB_INT},
-		{.name = "col_int8",        .type = DB_INT},
-		{.name = "col_int4",        .type = DB_INT},
-		{.name = "col_inet",        .type = DB_INT},
-		{.name = "col_timestamp",   .type = DB_INT},
-		{.name = "col_timestamptz", .type = DB_INT},
-		{.name = "col_bit",         .type = DB_INT},
-		{.name = "col_varbit",      .type = DB_INT},
-		{.name = NULL}
-	};
-
-	db_fld_t datetime_vals[] = {
-		{.name = "col_int8",        .type = DB_INT},
-		{.name = "col_int4",        .type = DB_INT},
-		{.name = "col_timestamp",   .type = DB_INT},
-		{.name = "col_timestamptz", .type = DB_INT},
-		{.name = NULL}
-	};
-
-
-	db_fld_t bitmap_vals[] = {
-		{.name = "col_int8",      .type = DB_INT},
-		{.name = "col_int4",      .type = DB_INT},
-		{.name = "col_bit",       .type = DB_INT},
-		{.name = "col_varbit",    .type = DB_INT},
-		{.name = NULL}
-	};
-
-	db_fld_t float_vals[] = {
-		{.name = "col_float4", .type = DB_FLOAT},
-		{.name = "col_float8", .type = DB_FLOAT},
-		{.name = NULL}
-	};
+	db_ctx_t *db;
+	db_cmd_t *put, *del, *get;
+	db_res_t *result;
+	db_rec_t *rec;
+	char *times;
+
+	db_fld_t int_vals[] = {{.name = "col_bool", .type = DB_INT},
+			{.name = "col_int8", .type = DB_INT},
+			{.name = "col_int4", .type = DB_INT},
+			{.name = "col_inet", .type = DB_INT},
+			{.name = "col_timestamp", .type = DB_INT},
+			{.name = "col_timestamptz", .type = DB_INT},
+			{.name = "col_bit", .type = DB_INT},
+			{.name = "col_varbit", .type = DB_INT}, {.name = NULL}};
+
+	db_fld_t datetime_vals[] = {{.name = "col_int8", .type = DB_INT},
+			{.name = "col_int4", .type = DB_INT},
+			{.name = "col_timestamp", .type = DB_INT},
+			{.name = "col_timestamptz", .type = DB_INT}, {.name = NULL}};
+
+
+	db_fld_t bitmap_vals[] = {{.name = "col_int8", .type = DB_INT},
+			{.name = "col_int4", .type = DB_INT},
+			{.name = "col_bit", .type = DB_INT},
+			{.name = "col_varbit", .type = DB_INT}, {.name = NULL}};
+
+	db_fld_t float_vals[] = {{.name = "col_float4", .type = DB_FLOAT},
+			{.name = "col_float8", .type = DB_FLOAT}, {.name = NULL}};
 
 	db_fld_t double_vals[] = {
-		{.name = "col_float8", .type = DB_DOUBLE},
-		{.name = NULL}
-	};
-
-	db_fld_t str_vals[] = {
-		{.name = "col_varchar", .type = DB_STR},
-		{.name = "col_bytea",   .type = DB_STR},
-		{.name = "col_text",    .type = DB_STR},
-		{.name = "col_bpchar",  .type = DB_STR},
-		{.name = "col_char",    .type = DB_STR},
-		{.name = NULL}
-	};
-
-	db_fld_t cstr_vals[] = {
-		{.name = "col_varchar", .type = DB_CSTR},
-		{.name = "col_bytea",   .type = DB_CSTR},
-		{.name = "col_text",    .type = DB_CSTR},
-		{.name = "col_bpchar",  .type = DB_CSTR},
-		{.name = "col_char",    .type = DB_CSTR},
-		{.name = NULL}
-	};
+			{.name = "col_float8", .type = DB_DOUBLE}, {.name = NULL}};
+
+	db_fld_t str_vals[] = {{.name = "col_varchar", .type = DB_STR},
+			{.name = "col_bytea", .type = DB_STR},
+			{.name = "col_text", .type = DB_STR},
+			{.name = "col_bpchar", .type = DB_STR},
+			{.name = "col_char", .type = DB_STR}, {.name = NULL}};
+
+	db_fld_t cstr_vals[] = {{.name = "col_varchar", .type = DB_CSTR},
+			{.name = "col_bytea", .type = DB_CSTR},
+			{.name = "col_text", .type = DB_CSTR},
+			{.name = "col_bpchar", .type = DB_CSTR},
+			{.name = "col_char", .type = DB_CSTR}, {.name = NULL}};
 
 	db_fld_t blob_vals[] = {
-		{.name = "col_bytea",   .type = DB_BLOB},
-		{.name = NULL}
-	};
-
-
-	db_fld_t res[] = {
-		{.name = "col_bool",        .type = DB_INT},
-		{.name = "col_bytea",       .type = DB_BLOB},
-		{.name = "col_char",        .type = DB_STR},
-		{.name = "col_int8",        .type = DB_INT},
-		{.name = "col_int4",        .type = DB_INT},
-		{.name = "col_int2",        .type = DB_INT},
-		{.name = "col_text",        .type = DB_STR},
-		{.name = "col_float4",      .type = DB_FLOAT},
-		{.name = "col_float8",      .type = DB_DOUBLE},
-		{.name = "col_inet",        .type = DB_INT},
-		{.name = "col_bpchar",      .type = DB_STR},
-		{.name = "col_varchar",     .type = DB_STR},
-		{.name = "col_timestamp",   .type = DB_DATETIME},
-		{.name = "col_timestamptz", .type = DB_DATETIME},
-		{.name = "col_bit",         .type = DB_BITMAP},
-		{.name = "col_varbit",      .type = DB_BITMAP},
-		{.name = NULL}
-	};
+			{.name = "col_bytea", .type = DB_BLOB}, {.name = NULL}};
+
+
+	db_fld_t res[] = {{.name = "col_bool", .type = DB_INT},
+			{.name = "col_bytea", .type = DB_BLOB},
+			{.name = "col_char", .type = DB_STR},
+			{.name = "col_int8", .type = DB_INT},
+			{.name = "col_int4", .type = DB_INT},
+			{.name = "col_int2", .type = DB_INT},
+			{.name = "col_text", .type = DB_STR},
+			{.name = "col_float4", .type = DB_FLOAT},
+			{.name = "col_float8", .type = DB_DOUBLE},
+			{.name = "col_inet", .type = DB_INT},
+			{.name = "col_bpchar", .type = DB_STR},
+			{.name = "col_varchar", .type = DB_STR},
+			{.name = "col_timestamp", .type = DB_DATETIME},
+			{.name = "col_timestamptz", .type = DB_DATETIME},
+			{.name = "col_bit", .type = DB_BITMAP},
+			{.name = "col_varbit", .type = DB_BITMAP}, {.name = NULL}};
 
 
 	db = db_ctx("postgres");
-	if (db == NULL) {
+	if(db == NULL) {
 		ERR("Error while initializing database layer\n");
 		goto error;
 	}
-	if (db_add_db(db, "postgres://janakj:heslo@localhost/ser") < 0) goto error;
-	if (db_connect(db) < 0) goto error;
-	
+	if(db_add_db(db, "postgres://janakj:heslo@localhost/ser") < 0)
+		goto error;
+	if(db_connect(db) < 0)
+		goto error;
+
 	del = db_cmd(DB_DEL, db, "test", NULL, NULL, NULL);
-	if (del == NULL) {
+	if(del == NULL) {
 		ERR("Error while building delete * query\n");
 		goto error;
 	}
 
-    put = db_cmd(DB_PUT, db, "test", NULL, NULL, int_vals);
-	if (put == NULL) {
+	put = db_cmd(DB_PUT, db, "test", NULL, NULL, int_vals);
+	if(put == NULL) {
 		ERR("Error while building test query\n");
 		goto error;
 	}
 
-	if (db_exec(NULL, del)) {
+	if(db_exec(NULL, del)) {
 		ERR("Error while deleting rows from test table\n");
 		goto error;
 	}
@@ -257,7 +233,7 @@ int pg_test(void)
 	put->vals[6].v.int4 = 0xffffffff;
 	put->vals[7].v.int4 = 0xffffffff;
 
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -271,7 +247,7 @@ int pg_test(void)
 	put->vals[6].v.int4 = 0;
 	put->vals[7].v.int4 = 0;
 
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -279,7 +255,7 @@ int pg_test(void)
 	db_cmd_free(put);
 
 	put = db_cmd(DB_PUT, db, "test", NULL, NULL, bitmap_vals);
-	if (put == NULL) {
+	if(put == NULL) {
 		ERR("Error while building bitmap test query\n");
 		goto error;
 	}
@@ -289,7 +265,7 @@ int pg_test(void)
 	put->vals[2].v.int4 = 0xffffffff;
 	put->vals[3].v.int4 = 0xffffffff;
 	put->vals[4].v.int4 = 0xffffffff;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -299,7 +275,7 @@ int pg_test(void)
 	put->vals[2].v.int4 = 0;
 	put->vals[3].v.int4 = 0;
 	put->vals[4].v.int4 = 0;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -307,21 +283,21 @@ int pg_test(void)
 	db_cmd_free(put);
 
 	put = db_cmd(DB_PUT, db, "test", NULL, NULL, float_vals);
-	if (put == NULL) {
+	if(put == NULL) {
 		ERR("Error while building float test query\n");
 		goto error;
 	}
 
 	put->vals[0].v.flt = FLT_MAX;
 	put->vals[1].v.flt = FLT_MAX;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
 
 	put->vals[0].v.flt = FLT_MIN;
 	put->vals[1].v.flt = FLT_MIN;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -329,19 +305,19 @@ int pg_test(void)
 	db_cmd_free(put);
 
 	put = db_cmd(DB_PUT, db, "test", NULL, NULL, double_vals);
-	if (put == NULL) {
+	if(put == NULL) {
 		ERR("Error while building double test query\n");
 		goto error;
 	}
 
 	put->vals[0].v.dbl = DBL_MAX;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
 
 	put->vals[0].v.dbl = DBL_MIN;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -350,7 +326,7 @@ int pg_test(void)
 	db_cmd_free(put);
 
 	put = db_cmd(DB_PUT, db, "test", NULL, NULL, str_vals);
-	if (put == NULL) {
+	if(put == NULL) {
 		ERR("Error while building str test query\n");
 		goto error;
 	}
@@ -365,7 +341,7 @@ int pg_test(void)
 	put->vals[3].v.lstr.len = 0;
 	put->vals[4].v.lstr.s = "";
 	put->vals[4].v.lstr.len = 0;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -380,7 +356,7 @@ int pg_test(void)
 	put->vals[3].v.lstr.len = 3;
 	put->vals[4].v.lstr.s = "a should not be there";
 	put->vals[4].v.lstr.len = 1;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -388,7 +364,7 @@ int pg_test(void)
 	db_cmd_free(put);
 
 	put = db_cmd(DB_PUT, db, "test", NULL, NULL, cstr_vals);
-	if (put == NULL) {
+	if(put == NULL) {
 		ERR("Error while building cstr test query\n");
 		goto error;
 	}
@@ -398,7 +374,7 @@ int pg_test(void)
 	put->vals[2].v.cstr = "";
 	put->vals[3].v.cstr = "";
 	put->vals[4].v.cstr = "";
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -408,7 +384,7 @@ int pg_test(void)
 	put->vals[2].v.cstr = "def";
 	put->vals[3].v.cstr = "def";
 	put->vals[4].v.cstr = "d";
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -416,14 +392,14 @@ int pg_test(void)
 	db_cmd_free(put);
 
 	put = db_cmd(DB_PUT, db, "test", NULL, NULL, blob_vals);
-	if (put == NULL) {
+	if(put == NULL) {
 		ERR("Error while building blob test query\n");
 		goto error;
 	}
 
 	put->vals[0].v.blob.s = "\0\0\0\0";
 	put->vals[0].v.blob.len = 4;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -432,7 +408,7 @@ int pg_test(void)
 	db_cmd_free(put);
 
 	put = db_cmd(DB_PUT, db, "test", NULL, NULL, datetime_vals);
-	if (put == NULL) {
+	if(put == NULL) {
 		ERR("Error while building datetime test query\n");
 		goto error;
 	}
@@ -441,7 +417,7 @@ int pg_test(void)
 	put->vals[1].v.time = 0xffffffff;
 	put->vals[2].v.time = 0xffffffff;
 	put->vals[3].v.time = 0xffffffff;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
@@ -450,24 +426,26 @@ int pg_test(void)
 	put->vals[1].v.time = 0;
 	put->vals[2].v.time = 0;
 	put->vals[3].v.time = 0;
-	if (db_exec(NULL, put)) {
+	if(db_exec(NULL, put)) {
 		ERR("Error while executing database command\n");
 		goto error;
 	}
 
-	if (put) db_cmd_free(put);
-	if (del) db_cmd_free(del);
+	if(put)
+		db_cmd_free(put);
+	if(del)
+		db_cmd_free(del);
 	put = NULL;
 	del = NULL;
 
 
 	get = db_cmd(DB_GET, db, "test", res, NULL, NULL);
-	if (get == NULL) {
+	if(get == NULL) {
 		ERR("Error while building select query\n");
 		goto error;
 	}
 
-	if (db_exec(&result, get)) {
+	if(db_exec(&result, get)) {
 		ERR("Error while executing select query\n");
 		goto error;
 	}
@@ -477,36 +455,38 @@ int pg_test(void)
 	while(rec) {
 		ERR("row: %d\n", row);
 		for(i = 0; !DB_FLD_LAST(rec->fld[i]); i++) {
-			if (rec->fld[i].flags & DB_NULL) {
+			if(rec->fld[i].flags & DB_NULL) {
 				ERR("%s: NULL\n", rec->fld[i].name);
 			} else {
 				switch(rec->fld[i].type) {
-				case DB_INT:
-				case DB_BITMAP:
-					ERR("%s: %d\n", rec->fld[i].name, rec->fld[i].v.int4);
-					break;
-					
-				case DB_DATETIME:
-					times = ctime(&rec->fld[i].v.time);
-					ERR("%s: %d:%.*s\n", rec->fld[i].name, rec->fld[i].v.time, strlen(times) - 1, times);
-					break;
-					
-				case DB_DOUBLE:
-					ERR("%s: %f\n", rec->fld[i].name, rec->fld[i].v.dbl);
-					break;
-					
-				case DB_FLOAT:
-					ERR("%s: %f\n", rec->fld[i].name, rec->fld[i].v.flt);
-					break;
-					
-				case DB_STR:
-				case DB_BLOB:
-					ERR("%s: %.*s\n", rec->fld[i].name, rec->fld[i].v.lstr.len, rec->fld[i].v.lstr.s);
-					break;
-					
-				case DB_CSTR:
-					ERR("%s: %s\n", rec->fld[i].name, rec->fld[i].v.cstr);
-					break;
+					case DB_INT:
+					case DB_BITMAP:
+						ERR("%s: %d\n", rec->fld[i].name, rec->fld[i].v.int4);
+						break;
+
+					case DB_DATETIME:
+						times = ctime(&rec->fld[i].v.time);
+						ERR("%s: %d:%.*s\n", rec->fld[i].name,
+								rec->fld[i].v.time, strlen(times) - 1, times);
+						break;
+
+					case DB_DOUBLE:
+						ERR("%s: %f\n", rec->fld[i].name, rec->fld[i].v.dbl);
+						break;
+
+					case DB_FLOAT:
+						ERR("%s: %f\n", rec->fld[i].name, rec->fld[i].v.flt);
+						break;
+
+					case DB_STR:
+					case DB_BLOB:
+						ERR("%s: %.*s\n", rec->fld[i].name,
+								rec->fld[i].v.lstr.len, rec->fld[i].v.lstr.s);
+						break;
+
+					case DB_CSTR:
+						ERR("%s: %s\n", rec->fld[i].name, rec->fld[i].v.cstr);
+						break;
 				}
 			}
 		}
@@ -522,10 +502,13 @@ int pg_test(void)
 	db_ctx_free(db);
 	return 0;
 
- error:
-	if (get) db_cmd_free(get);
-	if (put) db_cmd_free(put);
-	if (del) db_cmd_free(del);
+error:
+	if(get)
+		db_cmd_free(get);
+	if(put)
+		db_cmd_free(put);
+	if(del)
+		db_cmd_free(del);
 	db_disconnect(db);
 	db_ctx_free(db);
 	return -1;
@@ -538,7 +521,7 @@ int mod_register(char *path, int *dlflags, void *p1, void *p2)
 		LM_ERR("failed too allocate buffer");
 		return -1;
 	}
-	if(db_api_init()<0)
+	if(db_api_init() < 0)
 		return -1;
 	return 0;
 }
@@ -546,14 +529,14 @@ int mod_register(char *path, int *dlflags, void *p1, void *p2)
 static int pg_mod_init(void)
 {
 #ifdef PG_TEST
-	if (pg_test() == 0) {
+	if(pg_test() == 0) {
 		ERR("postgres: Testing successful\n");
 	} else {
 		ERR("postgres: Testing failed\n");
 	}
 	return -1;
 #endif /* PG_TEST */
-	if(pg_init_lock_set(pg_lockset)<0)
+	if(pg_init_lock_set(pg_lockset) < 0)
 		return -1;
 	return km_postgres_mod_init();
 }

+ 51 - 50
src/modules/db_postgres/pg_oid.c

@@ -39,84 +39,84 @@
 #include <string.h>
 
 /** An array of supported PostgreSQL field types. */
-static char* pg_type_id_name[] = {
-	"bool",
-	"bytea",
-	"char",
-	"int8",
-	"int2",
-	"int4",
-	"text",
-	"float4",
-	"float8",
-	"inet",
-	"bpchar",
-	"varchar",
-	"timestamp",
-	"timestamptz",
-	"bit",
-	"varbit",
+static char *pg_type_id_name[] = {
+		"bool", "bytea", "char", "int8", "int2", "int4", "text", "float4",
+		"float8", "inet", "bpchar", "varchar", "timestamp", "timestamptz",
+		"bit", "varbit",
 };
 
 
-static int get_index(char* name)
+static int get_index(char *name)
 {
 	int i;
-	
+
 	for(i = 0; i < PG_ID_MAX; i++) {
-		if (strcasecmp(name, pg_type_id_name[i]) == 0) return i; 
+		if(strcasecmp(name, pg_type_id_name[i]) == 0)
+			return i;
 	}
 	return -1;
 }
 
 
-pg_type_t* pg_new_oid_table(PGresult* res)
- {
-	pg_type_t* table = NULL;
+pg_type_t *pg_new_oid_table(PGresult *res)
+{
+	pg_type_t *table = NULL;
 	int row, n = 0, end, idx, fields;
 	str s;
-	
-	if (res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK) goto error;
+
+	if(res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK)
+		goto error;
 
 	n = PQntuples(res);
-	if (n <= 0) goto error;
+	if(n <= 0)
+		goto error;
 	fields = PQnfields(res);
-	if (fields != 2) goto error;
+	if(fields != 2)
+		goto error;
 
-	table = (pg_type_t*)malloc(sizeof(pg_type_t) * (n + 1));
-	if (table == NULL) goto error;
+	table = (pg_type_t *)malloc(sizeof(pg_type_t) * (n + 1));
+	if(table == NULL)
+		goto error;
 	memset(table, '\0', sizeof(pg_type_t) * (n + 1));
-	
+
 	end = n - 1;
 	for(row = 0; row < n; row++) {
 
 		/* Get name */
 		s.s = PQgetvalue(res, row, 0);
-		if (s.s == NULL) goto error;
+		if(s.s == NULL)
+			goto error;
 
 		/* Find index where the record is to be stored */
 		idx = get_index(s.s);
-		if (idx == -1) idx = end--;
+		if(idx == -1)
+			idx = end--;
 
 		/* Store the name */
 		table[idx].name = strdup(s.s);
-		if (table[idx].name == NULL) goto error;
+		if(table[idx].name == NULL)
+			goto error;
 
 		/* Oid */
 		s.s = PQgetvalue(res, row, 1);
-		if (s.s == NULL) goto error;
+		if(s.s == NULL)
+			goto error;
 		s.len = strlen(s.s);
-		if (str2int(&s, &table[idx].oid) < 0) goto error;
+		if(str2int(&s, &table[idx].oid) < 0)
+			goto error;
 
-		DBG("postgres: Type %s maps to Oid %d\n", table[idx].name, table[idx].oid);
+		DBG("postgres: Type %s maps to Oid %d\n", table[idx].name,
+				table[idx].oid);
 	}
 	return table;
-	
- error:
-	ERR("postgres: Error while obtaining field/data type description from server\n");
-	if (table) {
+
+error:
+	ERR("postgres: Error while obtaining field/data type description from "
+		"server\n");
+	if(table) {
 		for(idx = 0; idx < n; idx++) {
-			if (table[idx].name) free(table[idx].name);
+			if(table[idx].name)
+				free(table[idx].name);
 		}
 		free(table);
 	}
@@ -124,10 +124,10 @@ pg_type_t* pg_new_oid_table(PGresult* res)
 }
 
 
-void pg_destroy_oid_table(pg_type_t* table)
+void pg_destroy_oid_table(pg_type_t *table)
 {
 	int i;
-	if (table) {
+	if(table) {
 		for(i = 0; table[i].name; i++) {
 			free(table[i].name);
 		}
@@ -136,19 +136,20 @@ void pg_destroy_oid_table(pg_type_t* table)
 }
 
 
-int pg_name2oid(Oid* oid, pg_type_t* table, const char* name)
+int pg_name2oid(Oid *oid, pg_type_t *table, const char *name)
 {
 	int i;
 
-	if (!oid || !table) {
+	if(!oid || !table) {
 		BUG("postgres: Invalid parameters to pg_name2oid\n");
 		return -1;
 	}
 
-	if (name == NULL || name[0] == '\0') return 1;
+	if(name == NULL || name[0] == '\0')
+		return 1;
 
 	for(i = 0; table[i].name; i++) {
-		if (strcasecmp(table[i].name, name) == 0) {
+		if(strcasecmp(table[i].name, name) == 0) {
 			*oid = table[i].oid;
 			return 0;
 		}
@@ -157,17 +158,17 @@ int pg_name2oid(Oid* oid, pg_type_t* table, const char* name)
 }
 
 
-int pg_oid2name(const char** name, pg_type_t* table, Oid oid)
+int pg_oid2name(const char **name, pg_type_t *table, Oid oid)
 {
 	int i;
 
-	if (!table || !name) {
+	if(!table || !name) {
 		BUG("postgres: Invalid parameters to pg_oid2name\n");
 		return -1;
 	}
 
 	for(i = 0; table[i].name; i++) {
-		if (oid == table[i].oid) {
+		if(oid == table[i].oid) {
 			*name = table[i].name;
 			return 0;
 		}

+ 26 - 24
src/modules/db_postgres/pg_oid.h

@@ -40,9 +40,10 @@
  * This structure is used to map field names or data type names to their
  * Oids/field types.
  */
-typedef struct pg_type {
-	Oid oid;    /**< PostgreSQL Oid (object identifier) */
-	char* name; /**< Field name */
+typedef struct pg_type
+{
+	Oid oid;	/**< PostgreSQL Oid (object identifier) */
+	char *name; /**< Field name */
 } pg_type_t;
 
 
@@ -58,24 +59,25 @@ typedef struct pg_type {
  * different Oids for various data types so we have to have one array that
  * maps symbolic names below to Oids per connection/server.
  */
-enum pg_type_id {
-	PG_BOOL = 0,    /**< Boolean, true/false */
-	PG_BYTE,        /**< Binary data */
-	PG_CHAR,        /**< Single character */
-	PG_INT8,        /**< Integer with 8-byte storage */
-	PG_INT2,        /**< Integer with 2-byte storage */
-	PG_INT4,        /**< Integer with 4-byte storage */
-	PG_TEXT,        /**< Variable-length string, no limit specified */
-	PG_FLOAT4,      /**< Single-precision floating point number, 4-byte storage */
-	PG_FLOAT8,      /**< Double-precision floating point number, 8-byte storage */
-	PG_INET,        /**< IP address/netmask, host address */
-	PG_BPCHAR,      /**< Blank-padded string, fixed storage length */
-	PG_VARCHAR,     /**< Non-blank padded string, variable storage length */
-	PG_TIMESTAMP,   /**< Date and time */
+enum pg_type_id
+{
+	PG_BOOL = 0,  /**< Boolean, true/false */
+	PG_BYTE,	  /**< Binary data */
+	PG_CHAR,	  /**< Single character */
+	PG_INT8,	  /**< Integer with 8-byte storage */
+	PG_INT2,	  /**< Integer with 2-byte storage */
+	PG_INT4,	  /**< Integer with 4-byte storage */
+	PG_TEXT,	  /**< Variable-length string, no limit specified */
+	PG_FLOAT4,	/**< Single-precision floating point number, 4-byte storage */
+	PG_FLOAT8,	/**< Double-precision floating point number, 8-byte storage */
+	PG_INET,	  /**< IP address/netmask, host address */
+	PG_BPCHAR,	/**< Blank-padded string, fixed storage length */
+	PG_VARCHAR,   /**< Non-blank padded string, variable storage length */
+	PG_TIMESTAMP, /**< Date and time */
 	PG_TIMESTAMPTZ, /**< Date and time with time zone */
-	PG_BIT,         /**< Fixed-length bit string */
-	PG_VARBIT,      /**< Variable-length bit string */
-	PG_ID_MAX       /**< Bumper, this must be the last element of the enum */
+	PG_BIT,			/**< Fixed-length bit string */
+	PG_VARBIT,		/**< Variable-length bit string */
+	PG_ID_MAX		/**< Bumper, this must be the last element of the enum */
 };
 
 
@@ -87,13 +89,13 @@ enum pg_type_id {
  * @retval A pointer to the resulting array.
  * @retval NULL on error.
  */
-pg_type_t* pg_new_oid_table(PGresult* res);
+pg_type_t *pg_new_oid_table(PGresult *res);
 
 
 /** Frees all memory used by the table
  * @param table A pointer to table to be freed
  */
-void pg_destroy_oid_table(pg_type_t* table);
+void pg_destroy_oid_table(pg_type_t *table);
 
 
 /** Maps a field type name to Oid.
@@ -104,7 +106,7 @@ void pg_destroy_oid_table(pg_type_t* table);
  * @retval 1 if the type name is unknown
  * @retval -1 on error.
  */
-int pg_name2oid(Oid* oid, pg_type_t* table, const char* name);
+int pg_name2oid(Oid *oid, pg_type_t *table, const char *name);
 
 
 /** Maps a field type name to Oid.
@@ -115,7 +117,7 @@ int pg_name2oid(Oid* oid, pg_type_t* table, const char* name);
  * @retval 1 if the type name is unknown
  * @retval -1 on error.
  */
-int pg_oid2name(const char** name, pg_type_t* table, Oid oid);
+int pg_oid2name(const char **name, pg_type_t *table, Oid oid);
 
 /** @} */
 

+ 12 - 10
src/modules/db_postgres/pg_res.c

@@ -38,29 +38,31 @@
 #include "../../lib/srdb2/db_gen.h"
 
 
-static void pg_res_free(db_res_t* res, struct pg_res* payload)
+static void pg_res_free(db_res_t *res, struct pg_res *payload)
 {
 	db_drv_free(&payload->gen);
-	if (payload->res) PQclear(payload->res);
+	if(payload->res)
+		PQclear(payload->res);
 	pkg_free(payload);
 }
 
 
-int pg_res(db_res_t* res)
+int pg_res(db_res_t *res)
 {
-	struct pg_res* pres;
+	struct pg_res *pres;
 
-	pres = (struct pg_res*)pkg_malloc(sizeof(struct pg_res));
-	if (pres == NULL) {
+	pres = (struct pg_res *)pkg_malloc(sizeof(struct pg_res));
+	if(pres == NULL) {
 		ERR("postgres: No memory left\n");
 		return -1;
 	}
-	if (db_drv_init(&pres->gen, pg_res_free) < 0) goto error;
+	if(db_drv_init(&pres->gen, pg_res_free) < 0)
+		goto error;
 	DB_SET_PAYLOAD(res, pres);
 	return 0;
-	
- error:
-	if (pres) {
+
+error:
+	if(pres) {
 		db_drv_free(&pres->gen);
 		pkg_free(pres);
 	}

+ 5 - 4
src/modules/db_postgres/pg_res.h

@@ -39,13 +39,14 @@
 
 #include <libpq-fe.h>
 
-struct pg_res {
+struct pg_res
+{
 	db_drv_t gen;
-	PGresult* res;
-    int row, rows;
+	PGresult *res;
+	int row, rows;
 };
 
-int pg_res(db_res_t* res);
+int pg_res(db_res_t *res);
 
 /** @} */
 

+ 172 - 120
src/modules/db_postgres/pg_sql.c

@@ -42,7 +42,8 @@
 #include <string.h>
 
 
-enum {
+enum
+{
 	STR_DELETE,
 	STR_INSERT,
 	STR_UPDATE,
@@ -68,40 +69,30 @@ enum {
 };
 
 
-static str strings[] = {
-	STR_STATIC_INIT("delete from "),
-	STR_STATIC_INIT("insert into "),
-	STR_STATIC_INIT("update "),
-	STR_STATIC_INIT("select "),
-	STR_STATIC_INIT("replace "),
-	STR_STATIC_INIT(" set "),
-	STR_STATIC_INIT(" where "),
-	STR_STATIC_INIT(" is "),
-	STR_STATIC_INIT(" and "),
-	STR_STATIC_INIT(" or "),
-	STR_STATIC_INIT("?"),
-	STR_STATIC_INIT("="),
-	STR_STATIC_INIT("!="),
-	STR_STATIC_INIT("<"),
-	STR_STATIC_INIT(">"),
-	STR_STATIC_INIT("<="),
-	STR_STATIC_INIT(">="),
-	STR_STATIC_INIT(") values ("),
-	STR_STATIC_INIT(" from "),
-	STR_STATIC_INIT("select typname,pg_type.oid from pg_type"),
-	STR_STATIC_INIT("select timestamp '2000-01-01 00:00:00' + time '00:00:01'"), 
-	STR_STATIC_INIT("\0")
-};
+static str strings[] = {STR_STATIC_INIT("delete from "),
+		STR_STATIC_INIT("insert into "), STR_STATIC_INIT("update "),
+		STR_STATIC_INIT("select "), STR_STATIC_INIT("replace "),
+		STR_STATIC_INIT(" set "), STR_STATIC_INIT(" where "),
+		STR_STATIC_INIT(" is "), STR_STATIC_INIT(" and "),
+		STR_STATIC_INIT(" or "), STR_STATIC_INIT("?"), STR_STATIC_INIT("="),
+		STR_STATIC_INIT("!="), STR_STATIC_INIT("<"), STR_STATIC_INIT(">"),
+		STR_STATIC_INIT("<="), STR_STATIC_INIT(">="),
+		STR_STATIC_INIT(") values ("), STR_STATIC_INIT(" from "),
+		STR_STATIC_INIT("select typname,pg_type.oid from pg_type"),
+		STR_STATIC_INIT(
+				"select timestamp '2000-01-01 00:00:00' + time '00:00:01'"),
+		STR_STATIC_INIT("\0")};
 
 
 /**
  * Reallocatable string buffer.
  */
-struct string_buffer {
-	char *s;			/**< allocated memory itself */
-	int   len;			/**< used memory */
-	int   size;			/**< total size of allocated memory */
-	int   increment;	/**< increment when realloc is necessary */ 
+struct string_buffer
+{
+	char *s;	   /**< allocated memory itself */
+	int len;	   /**< used memory */
+	int size;	  /**< total size of allocated memory */
+	int increment; /**< increment when realloc is necessary */
 };
 
 
@@ -120,16 +111,17 @@ static inline int sb_add(struct string_buffer *sb, str *nstr)
 	int asize;
 	char *newp;
 
-	if (rsize > sb->size) {
+	if(rsize > sb->size) {
 		asize = rsize - sb->size;
-		new_size = sb->size + (asize / sb->increment
-						+ (asize % sb->increment > 0)) * sb->increment;
+		new_size = sb->size
+				   + (asize / sb->increment + (asize % sb->increment > 0))
+							 * sb->increment;
 		newp = pkg_malloc(new_size);
-		if (!newp) {
+		if(!newp) {
 			ERR("postgres: No memory left\n");
 			return -1;
 		}
-		if (sb->s) {
+		if(sb->s) {
 			memcpy(newp, sb->s, sb->len);
 			pkg_free(sb->s);
 		}
@@ -152,7 +144,7 @@ static inline int sb_add(struct string_buffer *sb, str *nstr)
  * @param s   A zero terminated string.
  * @return Pointer to the str structure.
  */
-static inline str* set_str(str *str, const char *s)
+static inline str *set_str(str *str, const char *s)
 {
 	str->s = (char *)s;
 	str->len = strlen(s);
@@ -166,11 +158,11 @@ static inline str* set_str(str *str, const char *s)
  * @param i Number of the parameter
  * @retval A pointer to static string with the marker
  */
-static str* get_marker(unsigned int i)
+static str *get_marker(unsigned int i)
 {
 	static char buf[INT2STR_MAX_LEN + 1];
 	static str res;
-	const char* c;
+	const char *c;
 
 	buf[0] = '$';
 	res.s = buf;
@@ -182,238 +174,298 @@ static str* get_marker(unsigned int i)
 }
 
 
-int build_update_sql(str* sql_cmd, db_cmd_t* cmd)
+int build_update_sql(str *sql_cmd, db_cmd_t *cmd)
 {
-	struct string_buffer sql_buf = {.s = NULL, .len = 0, 
-							  .size = 0, .increment = 128};
-	db_fld_t* fld;
+	struct string_buffer sql_buf = {
+			.s = NULL, .len = 0, .size = 0, .increment = 128};
+	db_fld_t *fld;
 	int i, rv = 0;
 	str tmpstr;
 
 	rv = sb_add(&sql_buf, &strings[STR_UPDATE]); /* "UPDATE " */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\""));
-	rv |= sb_add(&sql_buf, &cmd->table);		 /* table name */
+	rv |= sb_add(&sql_buf, &cmd->table); /* table name */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\""));
-	rv |= sb_add(&sql_buf, &strings[STR_SET]);	 /* " SET " */
+	rv |= sb_add(&sql_buf, &strings[STR_SET]); /* " SET " */
 
 	/* column name-value pairs */
-	for(i = 0, fld = cmd->vals; !DB_FLD_EMPTY(fld) && !DB_FLD_LAST(fld[i]); i++) {
+	for(i = 0, fld = cmd->vals; !DB_FLD_EMPTY(fld) && !DB_FLD_LAST(fld[i]);
+			i++) {
 		rv |= sb_add(&sql_buf, set_str(&tmpstr, fld[i].name));
 		rv |= sb_add(&sql_buf, set_str(&tmpstr, "="));
 		rv |= sb_add(&sql_buf, &strings[STR_ESC]);
-		if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
+		if(!DB_FLD_LAST(fld[i + 1]))
+			rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
 	}
-	if (rv) goto error;
+	if(rv)
+		goto error;
 
-	if (!DB_FLD_EMPTY(cmd->match)) {
+	if(!DB_FLD_EMPTY(cmd->match)) {
 		rv |= sb_add(&sql_buf, &strings[STR_WHERE]);
 
 		for(i = 0, fld = cmd->match; !DB_FLD_LAST(fld[i]); i++) {
 			rv |= sb_add(&sql_buf, set_str(&tmpstr, fld[i].name));
 
 			switch(fld[i].op) {
-			case DB_EQ:  rv |= sb_add(&sql_buf, &strings[STR_OP_EQ]);  break;
-			case DB_NE:  rv |= sb_add(&sql_buf, &strings[STR_OP_NE]);  break;
-			case DB_LT:  rv |= sb_add(&sql_buf, &strings[STR_OP_LT]);  break;
-			case DB_GT:  rv |= sb_add(&sql_buf, &strings[STR_OP_GT]);  break;
-			case DB_LEQ: rv |= sb_add(&sql_buf, &strings[STR_OP_LEQ]); break;
-			case DB_GEQ: rv |= sb_add(&sql_buf, &strings[STR_OP_GEQ]); break;
+				case DB_EQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_EQ]);
+					break;
+				case DB_NE:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_NE]);
+					break;
+				case DB_LT:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_LT]);
+					break;
+				case DB_GT:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_GT]);
+					break;
+				case DB_LEQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_LEQ]);
+					break;
+				case DB_GEQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_GEQ]);
+					break;
 			}
-			
+
 			rv |= sb_add(&sql_buf, get_marker(i + 1));
-			if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, &strings[STR_AND]);
+			if(!DB_FLD_LAST(fld[i + 1]))
+				rv |= sb_add(&sql_buf, &strings[STR_AND]);
 		}
 	}
 	rv |= sb_add(&sql_buf, &strings[STR_ZT]);
-	if (rv) goto error;
+	if(rv)
+		goto error;
 
 	sql_cmd->s = sql_buf.s;
 	sql_cmd->len = sql_buf.len;
 	return 0;
 
 error:
-	if (sql_buf.s) pkg_free(sql_buf.s);
+	if(sql_buf.s)
+		pkg_free(sql_buf.s);
 	return -1;
 }
 
 
-int build_insert_sql(str* sql_cmd, db_cmd_t* cmd)
+int build_insert_sql(str *sql_cmd, db_cmd_t *cmd)
 {
-	struct string_buffer sql_buf = {.s = NULL, .len = 0, 
-									.size = 0, .increment = 128};
-	db_fld_t* fld;
+	struct string_buffer sql_buf = {
+			.s = NULL, .len = 0, .size = 0, .increment = 128};
+	db_fld_t *fld;
 	int i, rv = 0;
 	str tmpstr;
 
 	rv = sb_add(&sql_buf, &strings[STR_INSERT]); /* "INSERT INTO " */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\""));
-	rv |= sb_add(&sql_buf, &cmd->table);		 /* table name */
+	rv |= sb_add(&sql_buf, &cmd->table); /* table name */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\" ("));
 
 	/* column names */
-	for(i = 0, fld = cmd->vals; !DB_FLD_EMPTY(fld) && !DB_FLD_LAST(fld[i]); i++) {
+	for(i = 0, fld = cmd->vals; !DB_FLD_EMPTY(fld) && !DB_FLD_LAST(fld[i]);
+			i++) {
 		rv |= sb_add(&sql_buf, set_str(&tmpstr, fld[i].name));
-		if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
+		if(!DB_FLD_LAST(fld[i + 1]))
+			rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
 	}
-	if (rv) goto error;
+	if(rv)
+		goto error;
 
 	rv |= sb_add(&sql_buf, &strings[STR_VALUES]);
 
-	for(i = 0, fld = cmd->vals; !DB_FLD_EMPTY(fld) && !DB_FLD_LAST(fld[i]); i++) {
+	for(i = 0, fld = cmd->vals; !DB_FLD_EMPTY(fld) && !DB_FLD_LAST(fld[i]);
+			i++) {
 		rv |= sb_add(&sql_buf, get_marker(i + 1));
-		if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
+		if(!DB_FLD_LAST(fld[i + 1]))
+			rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
 	}
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, ")"));
 	rv |= sb_add(&sql_buf, &strings[STR_ZT]);
-	if (rv) goto error;
-				 
+	if(rv)
+		goto error;
+
 	sql_cmd->s = sql_buf.s;
 	sql_cmd->len = sql_buf.len;
 	return 0;
 
 error:
-	if (sql_buf.s) pkg_free(sql_buf.s);
+	if(sql_buf.s)
+		pkg_free(sql_buf.s);
 	return -1;
 }
 
 
-int build_delete_sql(str* sql_cmd, db_cmd_t* cmd)
+int build_delete_sql(str *sql_cmd, db_cmd_t *cmd)
 {
-	struct string_buffer sql_buf = {.s = NULL, .len = 0, 
-									.size = 0, .increment = 128};
-	db_fld_t* fld;
+	struct string_buffer sql_buf = {
+			.s = NULL, .len = 0, .size = 0, .increment = 128};
+	db_fld_t *fld;
 	int i, rv = 0;
 	str tmpstr;
 
 	rv = sb_add(&sql_buf, &strings[STR_DELETE]); /* "DELETE FROM " */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\""));
-	rv |= sb_add(&sql_buf, &cmd->table);		 /* table name */
+	rv |= sb_add(&sql_buf, &cmd->table); /* table name */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\""));
 
-	if (!DB_FLD_EMPTY(cmd->match)) {
+	if(!DB_FLD_EMPTY(cmd->match)) {
 		rv |= sb_add(&sql_buf, &strings[STR_WHERE]);
 
 		for(i = 0, fld = cmd->match; !DB_FLD_LAST(fld[i]); i++) {
 			rv |= sb_add(&sql_buf, set_str(&tmpstr, fld[i].name));
 
 			switch(fld[i].op) {
-			case DB_EQ:  rv |= sb_add(&sql_buf, &strings[STR_OP_EQ]);  break;
-			case DB_NE:  rv |= sb_add(&sql_buf, &strings[STR_OP_NE]);  break;
-			case DB_LT:  rv |= sb_add(&sql_buf, &strings[STR_OP_LT]);  break;
-			case DB_GT:  rv |= sb_add(&sql_buf, &strings[STR_OP_GT]);  break;
-			case DB_LEQ: rv |= sb_add(&sql_buf, &strings[STR_OP_LEQ]); break;
-			case DB_GEQ: rv |= sb_add(&sql_buf, &strings[STR_OP_GEQ]); break;
+				case DB_EQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_EQ]);
+					break;
+				case DB_NE:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_NE]);
+					break;
+				case DB_LT:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_LT]);
+					break;
+				case DB_GT:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_GT]);
+					break;
+				case DB_LEQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_LEQ]);
+					break;
+				case DB_GEQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_GEQ]);
+					break;
 			}
-			
+
 			rv |= sb_add(&sql_buf, get_marker(i + 1));
-			if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, &strings[STR_AND]);
+			if(!DB_FLD_LAST(fld[i + 1]))
+				rv |= sb_add(&sql_buf, &strings[STR_AND]);
 		}
 	}
 	rv |= sb_add(&sql_buf, &strings[STR_ZT]);
-	if (rv) goto error;
+	if(rv)
+		goto error;
 
 	sql_cmd->s = sql_buf.s;
 	sql_cmd->len = sql_buf.len;
 	return 0;
 
 error:
-	if (sql_buf.s) pkg_free(sql_buf.s);
+	if(sql_buf.s)
+		pkg_free(sql_buf.s);
 	return -1;
 }
 
 
-int build_select_sql(str* sql_cmd, db_cmd_t* cmd)
+int build_select_sql(str *sql_cmd, db_cmd_t *cmd)
 {
-	struct string_buffer sql_buf = {.s = NULL, .len = 0, 
-									.size = 0, .increment = 128};
-	db_fld_t* fld;
+	struct string_buffer sql_buf = {
+			.s = NULL, .len = 0, .size = 0, .increment = 128};
+	db_fld_t *fld;
 	int i, rv = 0;
 	str tmpstr;
 
 	rv = sb_add(&sql_buf, &strings[STR_SELECT]); /* "SELECT " */
 
-	if (DB_FLD_EMPTY(cmd->result)) {
+	if(DB_FLD_EMPTY(cmd->result)) {
 		rv |= sb_add(&sql_buf, set_str(&tmpstr, "*"));
 	} else {
 		for(i = 0, fld = cmd->result; !DB_FLD_LAST(fld[i]); i++) {
 			rv |= sb_add(&sql_buf, set_str(&tmpstr, fld[i].name));
-			if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
+			if(!DB_FLD_LAST(fld[i + 1]))
+				rv |= sb_add(&sql_buf, set_str(&tmpstr, ","));
 		}
 	}
 
-	rv |= sb_add(&sql_buf, &strings[STR_FROM]);  /* " FROM " */
+	rv |= sb_add(&sql_buf, &strings[STR_FROM]); /* " FROM " */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\""));
-	rv |= sb_add(&sql_buf, &cmd->table);		 /* table name */
+	rv |= sb_add(&sql_buf, &cmd->table); /* table name */
 	rv |= sb_add(&sql_buf, set_str(&tmpstr, "\""));
 
-	if (!DB_FLD_EMPTY(cmd->match)) {
+	if(!DB_FLD_EMPTY(cmd->match)) {
 		rv |= sb_add(&sql_buf, &strings[STR_WHERE]);
 
 		for(i = 0, fld = cmd->match; !DB_FLD_LAST(fld[i]); i++) {
 			rv |= sb_add(&sql_buf, set_str(&tmpstr, fld[i].name));
 
 			switch(fld[i].op) {
-			case DB_EQ:  rv |= sb_add(&sql_buf, &strings[STR_OP_EQ]);  break;
-			case DB_NE:  rv |= sb_add(&sql_buf, &strings[STR_OP_NE]);  break;
-			case DB_LT:  rv |= sb_add(&sql_buf, &strings[STR_OP_LT]);  break;
-			case DB_GT:  rv |= sb_add(&sql_buf, &strings[STR_OP_GT]);  break;
-			case DB_LEQ: rv |= sb_add(&sql_buf, &strings[STR_OP_LEQ]); break;
-			case DB_GEQ: rv |= sb_add(&sql_buf, &strings[STR_OP_GEQ]); break;
+				case DB_EQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_EQ]);
+					break;
+				case DB_NE:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_NE]);
+					break;
+				case DB_LT:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_LT]);
+					break;
+				case DB_GT:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_GT]);
+					break;
+				case DB_LEQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_LEQ]);
+					break;
+				case DB_GEQ:
+					rv |= sb_add(&sql_buf, &strings[STR_OP_GEQ]);
+					break;
 			}
-			
+
 			rv |= sb_add(&sql_buf, get_marker(i + 1));
-			if (!DB_FLD_LAST(fld[i + 1])) rv |= sb_add(&sql_buf, &strings[STR_AND]);
+			if(!DB_FLD_LAST(fld[i + 1]))
+				rv |= sb_add(&sql_buf, &strings[STR_AND]);
 		}
 	}
 	rv |= sb_add(&sql_buf, &strings[STR_ZT]);
-	if (rv) goto error;
+	if(rv)
+		goto error;
 
 	sql_cmd->s = sql_buf.s;
 	sql_cmd->len = sql_buf.len;
 	return 0;
 
 error:
-	if (sql_buf.s) pkg_free(sql_buf.s);
+	if(sql_buf.s)
+		pkg_free(sql_buf.s);
 	return -1;
 }
 
 
-int build_select_oid_sql(str* sql_cmd)
+int build_select_oid_sql(str *sql_cmd)
 {
-	struct string_buffer sql_buf = {.s = NULL, .len = 0, 
-									.size = 0, .increment = 128};
+	struct string_buffer sql_buf = {
+			.s = NULL, .len = 0, .size = 0, .increment = 128};
 	int rv = 0;
-	
+
 	rv = sb_add(&sql_buf, &strings[STR_OID]);
 	rv |= sb_add(&sql_buf, &strings[STR_ZT]);
-	if (rv) goto error;
+	if(rv)
+		goto error;
 
 	sql_cmd->s = sql_buf.s;
 	sql_cmd->len = sql_buf.len;
 	return 0;
 
- error:
-	if (sql_buf.s) pkg_free(sql_buf.s);
+error:
+	if(sql_buf.s)
+		pkg_free(sql_buf.s);
 	return -1;
 }
 
 
-int build_timestamp_format_sql(str* sql_cmd)
+int build_timestamp_format_sql(str *sql_cmd)
 {
-	struct string_buffer sql_buf = {.s = NULL, .len = 0, 
-									.size = 0, .increment = 128};
+	struct string_buffer sql_buf = {
+			.s = NULL, .len = 0, .size = 0, .increment = 128};
 	int rv = 0;
-	
+
 	rv = sb_add(&sql_buf, &strings[STR_TIMESTAMP]);
 	rv |= sb_add(&sql_buf, &strings[STR_ZT]);
-	if (rv) goto error;
+	if(rv)
+		goto error;
 
 	sql_cmd->s = sql_buf.s;
 	sql_cmd->len = sql_buf.len;
 	return 0;
 
- error:
-	if (sql_buf.s) pkg_free(sql_buf.s);
+error:
+	if(sql_buf.s)
+		pkg_free(sql_buf.s);
 	return -1;
 }
 

+ 6 - 6
src/modules/db_postgres/pg_sql.h

@@ -49,7 +49,7 @@
  * @param cmd The command whose data will be used to generate the query.
  * @return 0 on success, negative number on error
  */
-int build_update_sql(str* sql_cmd, db_cmd_t* cmd);
+int build_update_sql(str *sql_cmd, db_cmd_t *cmd);
 
 
 /** Builds an INSERT SQL statement.
@@ -62,7 +62,7 @@ int build_update_sql(str* sql_cmd, db_cmd_t* cmd);
  * @param cmd The command whose data will be used to generate the query.
  * @return 0 on success, negative number on error
  */
-int build_insert_sql(str* sql_cmd, db_cmd_t* cmd);
+int build_insert_sql(str *sql_cmd, db_cmd_t *cmd);
 
 
 /** Builds a DELETE SQL statement.
@@ -76,7 +76,7 @@ int build_insert_sql(str* sql_cmd, db_cmd_t* cmd);
  * @param cmd The command whose data will be used to generate the query.
  * @return 0 on success, negative number on error
  */
-int build_delete_sql(str* sql_cmd, db_cmd_t* cmd);
+int build_delete_sql(str *sql_cmd, db_cmd_t *cmd);
 
 
 /** Builds a SELECT SQL statement.
@@ -90,14 +90,14 @@ int build_delete_sql(str* sql_cmd, db_cmd_t* cmd);
  * @param cmd The command whose data will be used to generate the query.
  * @return 0 on success, negative number on error
  */
-int build_select_sql(str* sql_cmd, db_cmd_t* cmd);
+int build_select_sql(str *sql_cmd, db_cmd_t *cmd);
 
 
 /* Builds SQL query used to obtain the list of supported field types.
  * This function builds a special SQL query that is used to obtain the list
  * of supported field type from the server's system catalogs.
  */
-int build_select_oid_sql(str* sql_cmd);
+int build_select_oid_sql(str *sql_cmd);
 
 
 /** Builds the SQL query used to determine the format of timestamp fields.
@@ -105,7 +105,7 @@ int build_select_oid_sql(str* sql_cmd);
  * immediately after establishing a connection to determine the format of
  * timestamp fields used on the server.
  */
-int build_timestamp_format_sql(str* sql_cmd);
+int build_timestamp_format_sql(str *sql_cmd);
 
 /** @} */
 

+ 173 - 138
src/modules/db_postgres/pg_uri.c

@@ -46,36 +46,43 @@
  * return 0 if match, 1 if not 
  */
 #define cmpstr(s1, s2, f) \
-	((s1)!=(s2)) && ((s1)==0 || (s2)==0 || (f)((s1), (s2))!=0)
+	((s1) != (s2)) && ((s1) == 0 || (s2) == 0 || (f)((s1), (s2)) != 0)
 
 
 /** Compare two connection URIs */
-static unsigned char pg_uri_cmp(db_uri_t* uri1, db_uri_t* uri2)
+static unsigned char pg_uri_cmp(db_uri_t *uri1, db_uri_t *uri2)
 {
-	struct pg_uri* puri1, *puri2;
+	struct pg_uri *puri1, *puri2;
 
-	if (!uri1 || !uri2) return 0;
+	if(!uri1 || !uri2)
+		return 0;
 
 	puri1 = DB_GET_PAYLOAD(uri1);
 	puri2 = DB_GET_PAYLOAD(uri2);
-	if (puri1->port != puri2->port) return 0;
-
-	if (cmpstr(puri1->username, puri2->username, strcmp)) return 0;
-	if (cmpstr(puri1->password, puri2->password, strcmp)) return 0;
-	if (cmpstr(puri1->host, puri2->host, strcasecmp)) return 0;
-	if (cmpstr(puri1->database, puri2->database, strcmp)) return 0;
+	if(puri1->port != puri2->port)
+		return 0;
+
+	if(cmpstr(puri1->username, puri2->username, strcmp))
+		return 0;
+	if(cmpstr(puri1->password, puri2->password, strcmp))
+		return 0;
+	if(cmpstr(puri1->host, puri2->host, strcasecmp))
+		return 0;
+	if(cmpstr(puri1->database, puri2->database, strcmp))
+		return 0;
 	return 1;
 }
 
 
 /** Duplicate a string
  */
-static int dupl_string(char** dst, const char* begin, const char* end)
+static int dupl_string(char **dst, const char *begin, const char *end)
 {
-	if (*dst) pkg_free(*dst);
+	if(*dst)
+		pkg_free(*dst);
 
 	*dst = pkg_malloc(end - begin + 1);
-	if ((*dst) == NULL) {
+	if((*dst) == NULL) {
 		return -1;
 	}
 
@@ -90,160 +97,181 @@ static int dupl_string(char** dst, const char* begin, const char* end)
  *
  * Returns 0 if parsing was successful and -1 otherwise
  */
-static int parse_postgres_uri(struct pg_uri* res, str* uri)
+static int parse_postgres_uri(struct pg_uri *res, str *uri)
 {
 #define SHORTEST_DB_URL "//a/b"
 #define SHORTEST_DB_URL_LEN (sizeof(SHORTEST_DB_URL) - 1)
 
-	enum state {
-		ST_SLASH1,     /* First slash */
-		ST_SLASH2,     /* Second slash */
-		ST_USER_HOST,  /* Username or hostname */
-		ST_PASS_PORT,  /* Password or port part */
-		ST_HOST,       /* Hostname part */
-		ST_PORT,       /* Port part */
-		ST_DB          /* Database part */
+	enum state
+	{
+		ST_SLASH1,	/* First slash */
+		ST_SLASH2,	/* Second slash */
+		ST_USER_HOST, /* Username or hostname */
+		ST_PASS_PORT, /* Password or port part */
+		ST_HOST,	  /* Hostname part */
+		ST_PORT,	  /* Port part */
+		ST_DB		  /* Database part */
 	};
 
 	enum state st;
-	int  i;
-	const char* begin;
-	char* prev_token;
+	int i;
+	const char *begin;
+	char *prev_token;
 
 	prev_token = 0;
 
-	if (!res || !uri) {
+	if(!res || !uri) {
 		goto err;
 	}
-	
-	if (uri->len < SHORTEST_DB_URL_LEN) {
+
+	if(uri->len < SHORTEST_DB_URL_LEN) {
 		goto err;
 	}
-	
+
 	st = ST_SLASH1;
 	begin = uri->s;
 
 	for(i = 0; i < uri->len; i++) {
 		switch(st) {
-		case ST_SLASH1:
-			switch(uri->s[i]) {
-			case '/':
-				st = ST_SLASH2;
+			case ST_SLASH1:
+				switch(uri->s[i]) {
+					case '/':
+						st = ST_SLASH2;
+						break;
+
+					default:
+						goto err;
+				}
 				break;
 
-			default:
-				goto err;
-			}
-			break;
+			case ST_SLASH2:
+				switch(uri->s[i]) {
+					case '/':
+						st = ST_USER_HOST;
+						begin = uri->s + i + 1;
+						break;
 
-		case ST_SLASH2:
-			switch(uri->s[i]) {
-			case '/':
-				st = ST_USER_HOST;
-				begin = uri->s + i + 1;
+					default:
+						goto err;
+				}
 				break;
-				
-			default:
-				goto err;
-			}
-			break;
-
-		case ST_USER_HOST:
-			switch(uri->s[i]) {
-			case '@':
-				st = ST_HOST;
-				if (dupl_string(&res->username, begin, uri->s + i) < 0) goto err;
-				begin = uri->s + i + 1;
+
+			case ST_USER_HOST:
+				switch(uri->s[i]) {
+					case '@':
+						st = ST_HOST;
+						if(dupl_string(&res->username, begin, uri->s + i) < 0)
+							goto err;
+						begin = uri->s + i + 1;
+						break;
+
+					case ':':
+						st = ST_PASS_PORT;
+						if(dupl_string(&prev_token, begin, uri->s + i) < 0)
+							goto err;
+						begin = uri->s + i + 1;
+						break;
+
+					case '/':
+						if(memchr(uri->s + i + 1, '/', uri->len - i - 1)
+								!= NULL)
+							break;
+						if(dupl_string(&res->host, begin, uri->s + i) < 0)
+							goto err;
+						if(dupl_string(&res->database, uri->s + i + 1,
+								   uri->s + uri->len)
+								< 0)
+							goto err;
+						return 0;
+				}
 				break;
 
-			case ':':
-				st = ST_PASS_PORT;
-				if (dupl_string(&prev_token, begin, uri->s + i) < 0) goto err;
-				begin = uri->s + i + 1;
+			case ST_PASS_PORT:
+				switch(uri->s[i]) {
+					case '@':
+						st = ST_HOST;
+						res->username = prev_token;
+						if(dupl_string(&res->password, begin, uri->s + i) < 0)
+							goto err;
+						begin = uri->s + i + 1;
+						break;
+
+					case '/':
+						if(memchr(uri->s + i + 1, '/', uri->len - i - 1)
+								!= NULL)
+							break;
+						res->host = prev_token;
+						res->port = str2s(begin, uri->s + i - begin, 0);
+						if(dupl_string(&res->database, uri->s + i + 1,
+								   uri->s + uri->len)
+								< 0)
+							goto err;
+						return 0;
+				}
 				break;
 
-			case '/':
-				if (memchr(uri->s + i + 1, '/', uri->len - i - 1) != NULL)
-					break;
-				if (dupl_string(&res->host, begin, uri->s + i) < 0) goto err;
-				if (dupl_string(&res->database, uri->s + i + 1, uri->s + uri->len) < 0) 
-					goto err;
-				return 0;
-			}
-			break;
-
-		case ST_PASS_PORT:
-			switch(uri->s[i]) {
-			case '@':
-				st = ST_HOST;
-				res->username = prev_token;
-				if (dupl_string(&res->password, begin, uri->s + i) < 0) goto err;
-				begin = uri->s + i + 1;
+			case ST_HOST:
+				switch(uri->s[i]) {
+					case ':':
+						st = ST_PORT;
+						if(dupl_string(&res->host, begin, uri->s + i) < 0)
+							goto err;
+						begin = uri->s + i + 1;
+						break;
+
+					case '/':
+						if(memchr(uri->s + i + 1, '/', uri->len - i - 1)
+								!= NULL)
+							break;
+						if(dupl_string(&res->host, begin, uri->s + i) < 0)
+							goto err;
+						if(dupl_string(&res->database, uri->s + i + 1,
+								   uri->s + uri->len)
+								< 0)
+							goto err;
+						return 0;
+				}
 				break;
 
-			case '/':
-				if (memchr(uri->s + i + 1, '/', uri->len - i - 1) != NULL)
-					break;
-				res->host = prev_token;
-				res->port = str2s(begin, uri->s + i - begin, 0);
-				if (dupl_string(&res->database, uri->s + i + 1, uri->s + uri->len) < 0) 
-					goto err;
-				return 0;
-			}
-			break;
-
-		case ST_HOST:
-			switch(uri->s[i]) {
-			case ':':
-				st = ST_PORT;
-				if (dupl_string(&res->host, begin, uri->s + i) < 0) goto err;
-				begin = uri->s + i + 1;
+			case ST_PORT:
+				switch(uri->s[i]) {
+					case '/':
+						res->port = str2s(begin, uri->s + i - begin, 0);
+						if(dupl_string(&res->database, uri->s + i + 1,
+								   uri->s + uri->len)
+								< 0)
+							goto err;
+						return 0;
+				}
 				break;
 
-			case '/':
-				if (memchr(uri->s + i + 1, '/', uri->len - i - 1) != NULL)
-					break;
-				if (dupl_string(&res->host, begin, uri->s + i) < 0) goto err;
-				if (dupl_string(&res->database, uri->s + i + 1, uri->s + uri->len) < 0) 
-					goto err;
-				return 0;
-			}
-			break;
-
-		case ST_PORT:
-			switch(uri->s[i]) {
-			case '/':
-				res->port = str2s(begin, uri->s + i - begin, 0);
-				if (dupl_string(&res->database, uri->s + i + 1, uri->s + uri->len) < 0) 
-					goto err;
-				return 0;
-			}
-			break;
-			
-		case ST_DB:
-			break;
+			case ST_DB:
+				break;
 		}
 	}
 
-	if (st != ST_DB) goto err;
+	if(st != ST_DB)
+		goto err;
 	return 0;
 
- err:
-	if (prev_token) pkg_free(prev_token);
-	if (res == NULL) return -1;
-	if (res->username) {
+err:
+	if(prev_token)
+		pkg_free(prev_token);
+	if(res == NULL)
+		return -1;
+	if(res->username) {
 		pkg_free(res->username);
 		res->username = NULL;
 	}
-	if (res->password) {
+	if(res->password) {
 		pkg_free(res->password);
 		res->password = NULL;
 	}
-	if (res->host) {
+	if(res->host) {
 		pkg_free(res->host);
 		res->host = NULL;
 	}
-	if (res->database) {
+	if(res->database) {
 		pkg_free(res->database);
 		res->database = NULL;
 	}
@@ -251,40 +279,47 @@ static int parse_postgres_uri(struct pg_uri* res, str* uri)
 }
 
 
-
-static void pg_uri_free(db_uri_t* uri, struct pg_uri* payload)
+static void pg_uri_free(db_uri_t *uri, struct pg_uri *payload)
 {
-	if (payload == NULL) return;
+	if(payload == NULL)
+		return;
 	db_drv_free(&payload->drv);
-	if (payload->username) pkg_free(payload->username);
-	if (payload->password) pkg_free(payload->password);
-	if (payload->host) pkg_free(payload->host);
-	if (payload->database) pkg_free(payload->database);
+	if(payload->username)
+		pkg_free(payload->username);
+	if(payload->password)
+		pkg_free(payload->password);
+	if(payload->host)
+		pkg_free(payload->host);
+	if(payload->database)
+		pkg_free(payload->database);
 	pkg_free(payload);
 }
 
 
-int pg_uri(db_uri_t* uri)
+int pg_uri(db_uri_t *uri)
 {
-	struct pg_uri* puri;
+	struct pg_uri *puri;
 
-	puri = (struct pg_uri*)pkg_malloc(sizeof(struct pg_uri));
-	if (puri == NULL) {
+	puri = (struct pg_uri *)pkg_malloc(sizeof(struct pg_uri));
+	if(puri == NULL) {
 		ERR("postgres: No memory left\n");
 		goto error;
 	}
 	memset(puri, '\0', sizeof(struct pg_uri));
-	if (db_drv_init(&puri->drv, pg_uri_free) < 0) goto error;
-	if (parse_postgres_uri(puri, &uri->body) < 0) goto error;
+	if(db_drv_init(&puri->drv, pg_uri_free) < 0)
+		goto error;
+	if(parse_postgres_uri(puri, &uri->body) < 0)
+		goto error;
 
 	DB_SET_PAYLOAD(uri, puri);
 	uri->cmp = pg_uri_cmp;
 	return 0;
 
- error:
-	if (puri) {
+error:
+	if(puri) {
 		db_drv_free(&puri->drv);
-		if (puri) pkg_free(puri);
+		if(puri)
+			pkg_free(puri);
 	}
 	return -1;
 }

+ 7 - 7
src/modules/db_postgres/pg_uri.h

@@ -41,13 +41,14 @@
  * to generic db_uri structures in the database API in SER. The 
  * structure contains parsed elements of postgres:// uri.
  */
-struct pg_uri {
+struct pg_uri
+{
 	db_drv_t drv;
-	char* username;
-	char* password;
-	char* host;
+	char *username;
+	char *password;
+	char *host;
 	unsigned short port;
-	char* database;
+	char *database;
 };
 
 /** Create a new pg_uri structure and parse the URI in parameter.
@@ -57,9 +58,8 @@ struct pg_uri {
  * @retval 0 on success
  * @retval A negative number on error.
  */
-int pg_uri(db_uri_t* uri);
+int pg_uri(db_uri_t *uri);
 
 /** @} */
 
 #endif /* _PG_URI_H */
-

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff