Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00028 #include "km_pg_con.h"
00029 #include "../../mem/mem.h"
00030 #include "../../dprint.h"
00031 #include "../../ut.h"
00032 #include <string.h>
00033 #include <time.h>
00034
00035
00044 struct pg_con* db_postgres_new_connection(struct db_id* id)
00045 {
00046 struct pg_con* ptr;
00047 char *ports;
00048
00049 LM_DBG("db_id = %p\n", id);
00050
00051 if (!id) {
00052 LM_ERR("invalid db_id parameter value\n");
00053 return 0;
00054 }
00055
00056 ptr = (struct pg_con*)pkg_malloc(sizeof(struct pg_con));
00057 if (!ptr) {
00058 LM_ERR("failed trying to allocated %lu bytes for connection structure."
00059 "\n", (unsigned long)sizeof(struct pg_con));
00060 return 0;
00061 }
00062 LM_DBG("%p=pkg_malloc(%lu)\n", ptr, (unsigned long)sizeof(struct pg_con));
00063
00064 memset(ptr, 0, sizeof(struct pg_con));
00065 ptr->ref = 1;
00066
00067 if (id->port) {
00068 ports = int2str(id->port, 0);
00069 LM_DBG("opening connection: postgres://xxxx:xxxx@%s:%d/%s\n", ZSW(id->host),
00070 id->port, ZSW(id->database));
00071 } else {
00072 ports = NULL;
00073 LM_DBG("opening connection: postgres://xxxx:xxxx@%s/%s\n", ZSW(id->host),
00074 ZSW(id->database));
00075 }
00076
00077 ptr->con = PQsetdbLogin(id->host, ports, NULL, NULL, id->database, id->username, id->password);
00078 LM_DBG("PQsetdbLogin(%p)\n", ptr->con);
00079
00080 if( (ptr->con == 0) || (PQstatus(ptr->con) != CONNECTION_OK) )
00081 {
00082 LM_ERR("%s\n", PQerrorMessage(ptr->con));
00083 PQfinish(ptr->con);
00084 goto err;
00085 }
00086
00087 ptr->connected = 1;
00088 ptr->timestamp = time(0);
00089 ptr->id = id;
00090
00091 return ptr;
00092
00093 err:
00094 if (ptr) {
00095 LM_ERR("cleaning up %p=pkg_free()\n", ptr);
00096 pkg_free(ptr);
00097 }
00098 return 0;
00099 }
00100
00101
00106 void db_postgres_free_connection(struct pool_con* con)
00107 {
00108
00109 struct pg_con * _c;
00110
00111 if (!con) return;
00112
00113 _c = (struct pg_con*)con;
00114
00115 if (_c->res) {
00116 LM_DBG("PQclear(%p)\n", _c->res);
00117 PQclear(_c->res);
00118 _c->res = 0;
00119 }
00120 if (_c->id) free_db_id(_c->id);
00121 if (_c->con) {
00122 LM_DBG("PQfinish(%p)\n", _c->con);
00123 PQfinish(_c->con);
00124 _c->con = 0;
00125 }
00126 LM_DBG("pkg_free(%p)\n", _c);
00127 pkg_free(_c);
00128 }