pg_con.c
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
00022
00023
00024
00025
00026
00027
00028
00029
00030 #include "pg_con.h"
00031 #include "../../mem/mem.h"
00032 #include "../../dprint.h"
00033 #include "../../ut.h"
00034 #include <string.h>
00035 #include <time.h>
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046 struct pg_con* db_postgres_new_connection(struct db_id* id)
00047 {
00048 struct pg_con* ptr;
00049 char *ports;
00050
00051 LM_DBG("db_id = %p\n", id);
00052
00053 if (!id) {
00054 LM_ERR("invalid db_id parameter value\n");
00055 return 0;
00056 }
00057
00058 ptr = (struct pg_con*)pkg_malloc(sizeof(struct pg_con));
00059 if (!ptr) {
00060 LM_ERR("failed trying to allocated %lu bytes for connection structure."
00061 "\n", (unsigned long)sizeof(struct pg_con));
00062 return 0;
00063 }
00064 LM_DBG("%p=pkg_malloc(%lu)\n", ptr, (unsigned long)sizeof(struct pg_con));
00065
00066 memset(ptr, 0, sizeof(struct pg_con));
00067 ptr->ref = 1;
00068
00069 if (id->port) {
00070 ports = int2str(id->port, 0);
00071 LM_DBG("opening connection: postgres://xxxx:xxxx@%s:%d/%s\n", ZSW(id->host),
00072 id->port, ZSW(id->database));
00073 } else {
00074 ports = NULL;
00075 LM_DBG("opening connection: postgres://xxxx:xxxx@%s/%s\n", ZSW(id->host),
00076 ZSW(id->database));
00077 }
00078
00079 ptr->con = PQsetdbLogin(id->host, ports, NULL, NULL, id->database, id->username, id->password);
00080 LM_DBG("PQsetdbLogin(%p)\n", ptr->con);
00081
00082 if( (ptr->con == 0) || (PQstatus(ptr->con) != CONNECTION_OK) )
00083 {
00084 LM_ERR("%s\n", PQerrorMessage(ptr->con));
00085 PQfinish(ptr->con);
00086 goto err;
00087 }
00088
00089 ptr->connected = 1;
00090 ptr->timestamp = time(0);
00091 ptr->id = id;
00092
00093 return ptr;
00094
00095 err:
00096 if (ptr) {
00097 LM_ERR("cleaning up %p=pkg_free()\n", ptr);
00098 pkg_free(ptr);
00099 }
00100 return 0;
00101 }
00102
00103
00104
00105
00106
00107
00108 void db_postgres_free_connection(struct pool_con* con)
00109 {
00110
00111 if (!con) return;
00112
00113 struct pg_con * _c;
00114 _c = (struct pg_con*)con;
00115
00116 if (_c->res) {
00117 LM_DBG("PQclear(%p)\n", _c->res);
00118 PQclear(_c->res);
00119 _c->res = 0;
00120 }
00121 if (_c->id) free_db_id(_c->id);
00122 if (_c->con) {
00123 LM_DBG("PQfinish(%p)\n", _c->con);
00124 PQfinish(_c->con);
00125 _c->con = 0;
00126 }
00127 LM_DBG("pkg_free(%p)\n", _c);
00128 pkg_free(_c);
00129 }