km_db_res.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * $Id$
  3. *
  4. * POSTGRES module, portions of this code were templated using
  5. * the mysql module, thus it's similarity.
  6. *
  7. * Copyright (C) 2003 August.Net Services, LLC
  8. * Copyright (C) 2006 Norman Brandinger
  9. * Copyright (C) 2008 1&1 Internet AG
  10. *
  11. * This file is part of openser, a free SIP server.
  12. *
  13. * openser is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 2 of the License, or
  16. * (at your option) any later version
  17. *
  18. * openser is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program; if not, write to the Free Software
  25. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  26. *
  27. * ---
  28. *
  29. * History
  30. * -------
  31. * 2003-04-06 initial code written (Greg Fausak/Andy Fullford)
  32. *
  33. * 2006-07-26 added BPCHAROID as a valid type for DB_STRING conversions
  34. * this removes the "unknown type 1042" log messages (norm)
  35. *
  36. * 2006-10-27 Added fetch support (norm)
  37. * Removed dependency on aug_* memory routines (norm)
  38. * Added connection pooling support (norm)
  39. * Standardized API routines to pg_* names (norm)
  40. *
  41. */
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #include "../../db/db_id.h"
  45. #include "../../db/db_res.h"
  46. #include "../../db/db_con.h"
  47. #include "../../dprint.h"
  48. #include "../../mem/mem.h"
  49. #include "db_res.h"
  50. #include "db_val.h"
  51. #include "pg_con.h"
  52. #include "pg_type.h"
  53. /**
  54. * Fill the result structure with data from the query
  55. */
  56. int db_postgres_convert_result(const db_con_t* _con, db_res_t* _res)
  57. {
  58. if (!_con || !_res) {
  59. LM_ERR("invalid parameter value\n");
  60. return -1;
  61. }
  62. if (db_postgres_get_columns(_con, _res) < 0) {
  63. LM_ERR("failed to get column names\n");
  64. return -2;
  65. }
  66. if (db_postgres_convert_rows(_con, _res, 0, PQntuples(CON_RESULT(_con))) < 0) {
  67. LM_ERR("failed to convert rows\n");
  68. db_free_columns(_res);
  69. return -3;
  70. }
  71. return 0;
  72. }
  73. /**
  74. * Get and convert columns from a result set
  75. */
  76. int db_postgres_get_columns(const db_con_t* _con, db_res_t* _res)
  77. {
  78. int col, datatype;
  79. if (!_con || !_res) {
  80. LM_ERR("invalid parameter value\n");
  81. return -1;
  82. }
  83. /* Get the number of rows (tuples) in the query result. */
  84. RES_NUM_ROWS(_res) = PQntuples(CON_RESULT(_con));
  85. /* Get the number of columns (fields) in each row of the query result. */
  86. RES_COL_N(_res) = PQnfields(CON_RESULT(_con));
  87. if (!RES_COL_N(_res)) {
  88. LM_DBG("no columns returned from the query\n");
  89. return -2;
  90. } else {
  91. LM_DBG("%d columns returned from the query\n", RES_COL_N(_res));
  92. }
  93. if (db_allocate_columns(_res, RES_COL_N(_res)) != 0) {
  94. LM_ERR("could not allocate columns");
  95. return -3;
  96. }
  97. /* For each column both the name and the OID number of the data type are saved. */
  98. for(col = 0; col < RES_COL_N(_res); col++) {
  99. RES_NAMES(_res)[col] = (str*)pkg_malloc(sizeof(str));
  100. if (! RES_NAMES(_res)[col]) {
  101. LM_ERR("no private memory left\n");
  102. db_free_columns(_res);
  103. return -4;
  104. }
  105. LM_DBG("allocate %d bytes for RES_NAMES[%d] at %p", sizeof(str), col,
  106. RES_NAMES(_res)[col]);
  107. /* The pointer that is here returned is part of the result structure. */
  108. RES_NAMES(_res)[col]->s = PQfname(CON_RESULT(_con), col);
  109. RES_NAMES(_res)[col]->len = strlen(PQfname(CON_RESULT(_con), col));
  110. LM_DBG("RES_NAMES(%p)[%d]=[%.*s]\n", RES_NAMES(_res)[col], col,
  111. RES_NAMES(_res)[col]->len, RES_NAMES(_res)[col]->s);
  112. /* get the datatype of the column */
  113. switch(datatype = PQftype(CON_RESULT(_con),col))
  114. {
  115. case INT2OID:
  116. case INT4OID:
  117. case INT8OID:
  118. RES_TYPES(_res)[col] = DB_INT;
  119. break;
  120. case FLOAT4OID:
  121. case FLOAT8OID:
  122. case NUMERICOID:
  123. RES_TYPES(_res)[col] = DB_DOUBLE;
  124. break;
  125. case DATEOID:
  126. case TIMESTAMPOID:
  127. case TIMESTAMPTZOID:
  128. RES_TYPES(_res)[col] = DB_DATETIME;
  129. break;
  130. case BOOLOID:
  131. case CHAROID:
  132. case VARCHAROID:
  133. case BPCHAROID:
  134. case TEXTOID:
  135. RES_TYPES(_res)[col] = DB_STRING;
  136. break;
  137. case BYTEAOID:
  138. RES_TYPES(_res)[col] = DB_BLOB;
  139. break;
  140. case BITOID:
  141. case VARBITOID:
  142. RES_TYPES(_res)[col] = DB_BITMAP;
  143. break;
  144. default:
  145. LM_WARN("unhandled data type column (%.*s) type id (%d), "
  146. "use STRING as default\n", RES_NAMES(_res)[col]->len,
  147. RES_NAMES(_res)[col]->s, datatype);
  148. RES_TYPES(_res)[col] = DB_STRING;
  149. break;
  150. }
  151. }
  152. return 0;
  153. }
  154. /**
  155. * Convert rows from PostgreSQL to db API representation
  156. */
  157. int db_postgres_convert_rows(const db_con_t* _con, db_res_t* _res, int row_start,
  158. int row_count)
  159. {
  160. int row, cols, col;
  161. char **row_buf, *s;
  162. int len, fetch_count;
  163. if (!_con || !_res) {
  164. LM_ERR("invalid parameter value\n");
  165. return -1;
  166. }
  167. if (row_count == 0) {
  168. LM_ERR("no rows requested from the query\n");
  169. return 0;
  170. }
  171. if (!RES_NUM_ROWS(_res)) {
  172. LM_DBG("no rows returned from the query\n");
  173. return 0;
  174. }
  175. if (row_start < 0) {
  176. LM_ERR("starting row (%d) cannot be less "
  177. "then zero, setting it to zero\n", row_start);
  178. row_start = 0;
  179. }
  180. if ((row_start + row_count) > RES_NUM_ROWS(_res)) {
  181. LM_ERR("starting row + row count cannot be > "
  182. "total rows. Setting row count to read remainder of result set\n");
  183. row_count = RES_NUM_ROWS(_res) - row_start;
  184. }
  185. /* Save the number of rows in the current fetch */
  186. RES_ROW_N(_res) = row_count;
  187. /* Save the number of columns in the result query */
  188. cols = RES_COL_N(_res);
  189. /*
  190. * Allocate an array of pointers one per column. It that will be used to hold
  191. * the address of the string representation of each column.
  192. */
  193. len = sizeof(char *) * cols;
  194. row_buf = (char **)pkg_malloc(len);
  195. LM_DBG("allocate for %d columns %d bytes in row buffer at %p\n", cols, len, row_buf);
  196. if (!row_buf) {
  197. LM_ERR("no private memory left\n");
  198. return -1;
  199. }
  200. memset(row_buf, 0, len);
  201. /* Allocate a row structure for each row in the current fetch. */
  202. len = sizeof(db_row_t) * row_count;
  203. RES_ROWS(_res) = (db_row_t*)pkg_malloc(len);
  204. LM_DBG("allocate %d bytes for %d rows at %p\n", len, row_count, RES_ROWS(_res));
  205. if (!RES_ROWS(_res)) {
  206. LM_ERR("no private memory left\n");
  207. return -1;
  208. }
  209. memset(RES_ROWS(_res), 0, len);
  210. fetch_count = 0;
  211. for(row = row_start; row < (row_start + row_count); row++) {
  212. for(col = 0; col < cols; col++) {
  213. /*
  214. * The row data pointer returned by PQgetvalue points to storage
  215. * that is part of the PGresult structure. One should not modify
  216. * the data it points to, and one must explicitly copy the data
  217. * into other storage if it is to be used past the lifetime of
  218. * the PGresult structure itself.
  219. */
  220. s = PQgetvalue(CON_RESULT(_con), row, col);
  221. LM_DBG("PQgetvalue(%p,%d,%d)=[%s]\n", _con, row, col, s);
  222. len = strlen(s);
  223. row_buf[col] = pkg_malloc(len+1);
  224. if (!row_buf[col]) {
  225. LM_ERR("no private memory left");
  226. return -1;
  227. }
  228. memset(row_buf[col], 0, len+1);
  229. LM_DBG("allocated %d bytes for row_buf[%d] at %p\n", len, col, row_buf[col]);
  230. strncpy(row_buf[col], s, len);
  231. LM_DBG("[%d][%d] Column[%.*s]=[%s]\n",
  232. row, col, RES_NAMES(_res)[col]->len, RES_NAMES(_res)[col]->s, row_buf[col]);
  233. }
  234. /*
  235. ** ASSERT: row_buf contains an entire row in strings
  236. */
  237. if(db_postgres_convert_row(_con,_res,&(RES_ROWS(_res)[fetch_count]),row_buf)<0){
  238. LM_ERR("failed to convert row #%d\n", row);
  239. RES_ROW_N(_res) = row - row_start;
  240. for (col=0; col<cols; col++) {
  241. LM_DBG("freeing row_buf[%d] at %p\n", col, row_buf[col]);
  242. pkg_free(row_buf[col]);
  243. }
  244. LM_DBG("freeing row buffer at %p\n", row_buf);
  245. pkg_free(row_buf);
  246. return -4;
  247. }
  248. /*
  249. * pkg_free() must be done for the above allocations now that the row
  250. * has been converted. During pg_convert_row (and subsequent pg_str2val)
  251. * processing, data types that don't need to be converted (namely STRINGS
  252. * and STR) have their addresses saved. These data types should not have
  253. * their pkg_malloc() allocations freed here because they are still
  254. * needed. However, some data types (ex: INT, DOUBLE) should have their
  255. * pkg_malloc() allocations freed because during the conversion process,
  256. * their converted values are saved in the union portion of the db_val_t
  257. * structure. BLOB will be copied during PQunescape in str2val, thus it
  258. * has to be freed here AND in pg_free_row().
  259. *
  260. * Warning: when the converted row is no longer needed, the data types
  261. * whose addresses were saved in the db_val_t structure must be freed
  262. * or a memory leak will happen. This processing should happen in the
  263. * pg_free_row() subroutine. The caller of this routine should ensure
  264. * that pg_free_rows(), pg_free_row() or pg_free_result() is eventually
  265. * called.
  266. */
  267. for (col=0; col<cols; col++) {
  268. switch (RES_TYPES(_res)[col]) {
  269. case DB_STRING:
  270. case DB_STR:
  271. break;
  272. default:
  273. LM_DBG("[%d][%d] Col[%.*s] Type[%d] "
  274. "Freeing row_buf[%p]\n", row, col,
  275. RES_NAMES(_res)[col]->len, RES_NAMES(_res)[col]->s,
  276. RES_TYPES(_res)[col], row_buf[col]);
  277. LM_DBG("freeing row_buf[%d] at %p\n", col, row_buf[col]);
  278. pkg_free(row_buf[col]);
  279. }
  280. /*
  281. * The following housekeeping may not be technically required, but it
  282. * is a good practice to NULL pointer fields that are no longer valid.
  283. * Note that DB_STRING fields have not been pkg_free(). NULLing DB_STRING
  284. * fields would normally not be good to do because a memory leak would
  285. * occur. However, the pg_convert_row() routine has saved the DB_STRING
  286. * pointer in the db_val_t structure. The db_val_t structure will
  287. * eventually be used to pkg_free() the DB_STRING storage.
  288. */
  289. row_buf[col] = (char *)NULL;
  290. }
  291. fetch_count++;
  292. }
  293. LM_DBG("freeing row buffer at %p\n", row_buf);
  294. pkg_free(row_buf);
  295. row_buf = NULL;
  296. return 0;
  297. }
  298. /**
  299. * Convert a row from the result query into db API representation
  300. */
  301. int db_postgres_convert_row(const db_con_t* _con, db_res_t* _res, db_row_t* _row,
  302. char **row_buf)
  303. {
  304. int col, len;
  305. if (!_con || !_res || !_row) {
  306. LM_ERR("invalid parameter value\n");
  307. return -1;
  308. }
  309. /*
  310. * Allocate storage to hold the data type value converted from a string
  311. * because PostgreSQL returns (most) data as strings
  312. */
  313. len = sizeof(db_val_t) * RES_COL_N(_res);
  314. ROW_VALUES(_row) = (db_val_t*)pkg_malloc(len);
  315. if (!ROW_VALUES(_row)) {
  316. LM_ERR("no private memory left\n");
  317. return -1;
  318. }
  319. LM_DBG("allocate %d bytes for row values at %p\n", sizeof(db_val_t) * RES_COL_N(_res),
  320. ROW_VALUES(_row));
  321. ROW_N(_row) = RES_COL_N(_res);
  322. memset(ROW_VALUES(_row), 0, len);
  323. /* Save the number of columns in the ROW structure */
  324. ROW_N(_row) = RES_COL_N(_res);
  325. /* For each column in the row */
  326. for(col = 0; col < ROW_N(_row); col++) {
  327. /* Convert the string representation into the value representation */
  328. if (db_postgres_str2val(RES_TYPES(_res)[col], &(ROW_VALUES(_row)[col]),
  329. row_buf[col], strlen(row_buf[col])) < 0) {
  330. LM_ERR("failed to convert value\n");
  331. LM_DBG("free row at %pn", _row);
  332. db_free_row(_row);
  333. return -3;
  334. }
  335. }
  336. return 0;
  337. }