km_res.c 11 KB

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