km_dbase.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. * 2006-07-28 within pg_get_result(): added check to immediatly return of no
  28. * result set was returned added check to only execute
  29. * convert_result() if PGRES_TUPLES_OK added safety check to avoid
  30. * double pg_free_result() (norm)
  31. * 2006-08-07 Rewrote pg_get_result().
  32. * Additional debugging lines have been placed through out the code.
  33. * Added Asynchronous Command Processing (PQsendQuery/PQgetResult)
  34. * instead of PQexec. this was done in preparation of adding FETCH
  35. * support. Note that PQexec returns a result pointer while
  36. * PQsendQuery does not. The result set pointer is obtained from
  37. * a call (or multiple calls) to PQgetResult.
  38. * Removed transaction processing calls (BEGIN/COMMIT/ROLLBACK) as
  39. * they added uneeded overhead. Klaus' testing showed in excess of
  40. * 1ms gain by removing each command. In addition, Kamailio only
  41. * issues single queries and is not, at this time transaction aware.
  42. * The transaction processing routines have been left in place
  43. * should this support be needed in the future.
  44. * Updated logic in pg_query / pg_raw_query to accept a (0) result
  45. * set (_r) parameter. In this case, control is returned
  46. * immediately after submitting the query and no call to
  47. * pg_get_results() is performed. This is a requirement for
  48. * FETCH support. (norm)
  49. * 2006-10-27 Added fetch support (norm)
  50. * Removed dependency on aug_* memory routines (norm)
  51. * Added connection pooling support (norm)
  52. * Standardized API routines to pg_* names (norm)
  53. * 2006-11-01 Updated pg_insert(), pg_delete(), pg_update() and
  54. * pg_get_result() to handle failed queries. Detailed warnings
  55. * along with the text of the failed query is now displayed in the
  56. * log. Callers of these routines can now assume that a non-zero
  57. * rc indicates the query failed and that remedial action may need
  58. * to be taken. (norm)
  59. */
  60. /*! \file
  61. * \brief DB_POSTGRES :: Core
  62. * \ingroup db_postgres
  63. * Module: \ref db_postgres
  64. */
  65. /*! maximum number of columns */
  66. #define MAXCOLUMNS 512
  67. #include <string.h>
  68. #include <stdio.h>
  69. #include "../../dprint.h"
  70. #include "../../mem/mem.h"
  71. #include "../../lib/srdb1/db.h"
  72. #include "../../lib/srdb1/db_ut.h"
  73. #include "../../lib/srdb1/db_query.h"
  74. #include "km_dbase.h"
  75. #include "km_pg_con.h"
  76. #include "km_val.h"
  77. #include "km_res.h"
  78. static void db_postgres_free_query(const db1_con_t* _con);
  79. /*!
  80. * \brief Initialize database for future queries
  81. * \param _url URL of the database that should be opened
  82. * \return database connection on success, NULL on error
  83. * \note this function must be called prior to any database functions
  84. */
  85. db1_con_t *db_postgres_init(const str* _url)
  86. {
  87. return db_do_init(_url, (void*) db_postgres_new_connection);
  88. }
  89. /*!
  90. * \brief Close database when the database is no longer needed
  91. * \param _h closed connection, as returned from db_postgres_init
  92. * \note free all memory and resources
  93. */
  94. void db_postgres_close(db1_con_t* _h)
  95. {
  96. db_do_close(_h, db_postgres_free_connection);
  97. }
  98. /*!
  99. * \brief Submit_query, run a query
  100. * \param _con database connection
  101. * \param _s query string
  102. * \return 0 on success, negative on failure
  103. */
  104. static int db_postgres_submit_query(const db1_con_t* _con, const str* _s)
  105. {
  106. if(! _con || !_s || !_s->s)
  107. {
  108. LM_ERR("invalid parameter value\n");
  109. return(-1);
  110. }
  111. /* this bit of nonsense in case our connection get screwed up */
  112. switch(PQstatus(CON_CONNECTION(_con)))
  113. {
  114. case CONNECTION_OK:
  115. break;
  116. case CONNECTION_BAD:
  117. LM_DBG("connection reset\n");
  118. PQreset(CON_CONNECTION(_con));
  119. break;
  120. case CONNECTION_STARTED:
  121. case CONNECTION_MADE:
  122. case CONNECTION_AWAITING_RESPONSE:
  123. case CONNECTION_AUTH_OK:
  124. case CONNECTION_SETENV:
  125. case CONNECTION_SSL_STARTUP:
  126. case CONNECTION_NEEDED:
  127. default:
  128. LM_ERR("%p PQstatus(%s) invalid: %.*s\n", _con,
  129. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  130. return -1;
  131. }
  132. /* free any previous query that is laying about */
  133. db_postgres_free_query(_con);
  134. /* exec the query */
  135. if (PQsendQuery(CON_CONNECTION(_con), _s->s)) {
  136. LM_DBG("%p PQsendQuery(%.*s)\n", _con, _s->len, _s->s);
  137. } else {
  138. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  139. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  140. return -1;
  141. }
  142. return 0;
  143. }
  144. /*!
  145. * \brief Gets a partial result set, fetch rows from a result
  146. *
  147. * Gets a partial result set, fetch a number of rows from a database result.
  148. * This function initialize the given result structure on the first run, and
  149. * fetches the nrows number of rows. On subsequenting runs, it uses the
  150. * existing result and fetches more rows, until it reaches the end of the
  151. * result set. Because of this the result needs to be null in the first
  152. * invocation of the function. If the number of wanted rows is zero, the
  153. * function returns anything with a result of zero.
  154. * \param _con database connection
  155. * \param _res result set
  156. * \param nrows number of fetches rows
  157. * \return 0 on success, negative on failure
  158. */
  159. int db_postgres_fetch_result(const db1_con_t* _con, db1_res_t** _res, const int nrows)
  160. {
  161. int rows;
  162. PGresult *res = NULL;
  163. ExecStatusType pqresult;
  164. if (!_con || !_res || nrows < 0) {
  165. LM_ERR("invalid parameter value\n");
  166. return -1;
  167. }
  168. /* exit if the fetch count is zero */
  169. if (nrows == 0) {
  170. if (*_res)
  171. db_free_result(*_res);
  172. *_res = 0;
  173. return 0;
  174. }
  175. if (*_res == NULL) {
  176. /* Allocate a new result structure */
  177. *_res = db_new_result();
  178. /* Get the result of the previous query */
  179. while (1) {
  180. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  181. CON_RESULT(_con) = res;
  182. } else {
  183. break;
  184. }
  185. }
  186. pqresult = PQresultStatus(CON_RESULT(_con));
  187. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  188. PQresStatus(pqresult), CON_RESULT(_con));
  189. switch(pqresult) {
  190. case PGRES_COMMAND_OK:
  191. /* Successful completion of a command returning no data (such as INSERT or UPDATE). */
  192. return 0;
  193. case PGRES_TUPLES_OK:
  194. /* Successful completion of a command returning data (such as a SELECT or SHOW). */
  195. if (db_postgres_get_columns(_con, *_res) < 0) {
  196. LM_ERR("failed to get column names\n");
  197. return -2;
  198. }
  199. break;
  200. case PGRES_FATAL_ERROR:
  201. LM_ERR("%p - invalid query, execution aborted\n", _con);
  202. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  203. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  204. if (*_res)
  205. db_free_result(*_res);
  206. *_res = 0;
  207. return -3;
  208. case PGRES_EMPTY_QUERY:
  209. /* notice or warning */
  210. case PGRES_NONFATAL_ERROR:
  211. /* status for COPY command, not used */
  212. case PGRES_COPY_OUT:
  213. case PGRES_COPY_IN:
  214. /* unexpected response */
  215. case PGRES_BAD_RESPONSE:
  216. default:
  217. LM_ERR("%p - probable invalid query\n", _con);
  218. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  219. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  220. if (*_res)
  221. db_free_result(*_res);
  222. *_res = 0;
  223. return -4;
  224. }
  225. } else {
  226. if(RES_ROWS(*_res) != NULL) {
  227. db_free_rows(*_res);
  228. }
  229. RES_ROWS(*_res) = 0;
  230. RES_ROW_N(*_res) = 0;
  231. }
  232. /* Get the number of rows (tuples) in the query result. */
  233. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  234. /* determine the number of rows remaining to be processed */
  235. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  236. /* If there aren't any more rows left to process, exit */
  237. if (rows <= 0)
  238. return 0;
  239. /* if the fetch count is less than the remaining rows to process */
  240. /* set the number of rows to process (during this call) equal to the fetch count */
  241. if (nrows < rows)
  242. rows = nrows;
  243. RES_ROW_N(*_res) = rows;
  244. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  245. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  246. if (db_postgres_convert_rows(_con, *_res) < 0) {
  247. LM_ERR("failed to convert rows\n");
  248. if (*_res)
  249. db_free_result(*_res);
  250. *_res = 0;
  251. return -3;
  252. }
  253. /* update the total number of rows processed */
  254. RES_LAST_ROW(*_res) += rows;
  255. return 0;
  256. }
  257. /*!
  258. * \brief Free database and any old query results
  259. * \param _con database connection
  260. */
  261. static void db_postgres_free_query(const db1_con_t* _con)
  262. {
  263. if(CON_RESULT(_con))
  264. {
  265. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  266. PQclear(CON_RESULT(_con));
  267. CON_RESULT(_con) = 0;
  268. }
  269. }
  270. /*!
  271. * \brief Free the query and the result memory in the core
  272. * \param _con database connection
  273. * \param _r result set
  274. * \return 0 on success, -1 on failure
  275. */
  276. int db_postgres_free_result(db1_con_t* _con, db1_res_t* _r)
  277. {
  278. if ((!_con) || (!_r)) {
  279. LM_ERR("invalid parameter value\n");
  280. return -1;
  281. }
  282. if (db_free_result(_r) < 0) {
  283. LM_ERR("unable to free result structure\n");
  284. return -1;
  285. }
  286. db_postgres_free_query(_con);
  287. return 0;
  288. }
  289. /*!
  290. * \brief Query table for specified rows
  291. * \param _h structure representing database connection
  292. * \param _k key names
  293. * \param _op operators
  294. * \param _v values of the keys that must match
  295. * \param _c column names to return
  296. * \param _n nmber of key=values pairs to compare
  297. * \param _nc number of columns to return
  298. * \param _o order by the specified column
  299. * \param _r result set
  300. * \return 0 on success, negative on failure
  301. */
  302. int db_postgres_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  303. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  304. const db_key_t _o, db1_res_t** _r)
  305. {
  306. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  307. db_postgres_submit_query, db_postgres_store_result);
  308. }
  309. /*!
  310. * Execute a raw SQL query
  311. * \param _h database connection
  312. * \param _s raw query string
  313. * \param _r result set
  314. * \return 0 on success, negative on failure
  315. */
  316. int db_postgres_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  317. {
  318. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  319. db_postgres_store_result);
  320. }
  321. /*!
  322. * \brief Retrieve result set
  323. * \param _con structure representing the database connection
  324. * \param _r pointer to a structure represending the result set
  325. * \return 0 If the status of the last command produced a result set and,
  326. * If the result set contains data or the convert_result() routine
  327. * completed successfully. Negative if the status of the last command was
  328. * not handled or if the convert_result() returned an error.
  329. * \note A new result structure is allocated on every call to this routine.
  330. * If this routine returns 0, it is the callers responsbility to free the
  331. * result structure. If this routine returns < 0, then the result structure
  332. * is freed before returning to the caller.
  333. */
  334. int db_postgres_store_result(const db1_con_t* _con, db1_res_t** _r)
  335. {
  336. PGresult *res = NULL;
  337. ExecStatusType pqresult;
  338. int rc = 0;
  339. *_r = db_new_result();
  340. if (*_r==NULL) {
  341. LM_ERR("failed to init new result\n");
  342. rc = -1;
  343. goto done;
  344. }
  345. while (1) {
  346. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  347. CON_RESULT(_con) = res;
  348. } else {
  349. break;
  350. }
  351. }
  352. pqresult = PQresultStatus(CON_RESULT(_con));
  353. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  354. PQresStatus(pqresult), CON_RESULT(_con));
  355. switch(pqresult) {
  356. case PGRES_COMMAND_OK:
  357. /* Successful completion of a command returning no data
  358. * (such as INSERT or UPDATE). */
  359. rc = 0;
  360. break;
  361. case PGRES_TUPLES_OK:
  362. /* Successful completion of a command returning data
  363. * (such as a SELECT or SHOW). */
  364. if (db_postgres_convert_result(_con, *_r) < 0) {
  365. LM_ERR("error while converting result\n");
  366. LM_DBG("freeing result set at %p\n", _r);
  367. pkg_free(*_r);
  368. *_r = 0;
  369. rc = -4;
  370. break;
  371. }
  372. rc = 0;
  373. break;
  374. /* query failed */
  375. case PGRES_FATAL_ERROR:
  376. LM_ERR("invalid query, execution aborted\n");
  377. LM_ERR("driver error: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  378. db_free_result(*_r);
  379. *_r = 0;
  380. rc = -3;
  381. break;
  382. case PGRES_EMPTY_QUERY:
  383. /* notice or warning */
  384. case PGRES_NONFATAL_ERROR:
  385. /* status for COPY command, not used */
  386. case PGRES_COPY_OUT:
  387. case PGRES_COPY_IN:
  388. /* unexpected response */
  389. case PGRES_BAD_RESPONSE:
  390. default:
  391. LM_ERR("probable invalid query, execution aborted\n");
  392. LM_ERR("driver message: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  393. db_free_result(*_r);
  394. *_r = 0;
  395. rc = -4;
  396. break;
  397. }
  398. done:
  399. db_postgres_free_query(_con);
  400. return (rc);
  401. }
  402. /*!
  403. * \brief Insert a row into specified table
  404. * \param _h structure representing database connection
  405. * \param _k key names
  406. * \param _v values of the keys
  407. * \param _n number of key=value pairs
  408. * \return 0 on success, negative on failure
  409. */
  410. int db_postgres_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  411. const int _n)
  412. {
  413. db1_res_t* _r = NULL;
  414. int tmp = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  415. // finish the async query, otherwise the next query will not complete
  416. if (db_postgres_store_result(_h, &_r) != 0)
  417. LM_WARN("unexpected result returned");
  418. if (_r)
  419. db_free_result(_r);
  420. return tmp;
  421. }
  422. /*!
  423. * \brief Delete a row from the specified table
  424. * \param _h structure representing database connection
  425. * \param _k key names
  426. * \param _o operators
  427. * \param _v values of the keys that must match
  428. * \param _n number of key=value pairs
  429. * \return 0 on success, negative on failure
  430. */
  431. int db_postgres_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  432. const db_val_t* _v, const int _n)
  433. {
  434. db1_res_t* _r = NULL;
  435. int tmp = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  436. db_postgres_submit_query);
  437. if (db_postgres_store_result(_h, &_r) != 0)
  438. LM_WARN("unexpected result returned");
  439. if (_r)
  440. db_free_result(_r);
  441. return tmp;
  442. }
  443. /*!
  444. * Update some rows in the specified table
  445. * \param _h structure representing database connection
  446. * \param _k key names
  447. * \param _o operators
  448. * \param _v values of the keys that must match
  449. * \param _uk updated columns
  450. * \param _uv updated values of the columns
  451. * \param _n number of key=value pairs
  452. * \param _un number of columns to update
  453. * \return 0 on success, negative on failure
  454. */
  455. int db_postgres_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  456. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  457. const int _un)
  458. {
  459. db1_res_t* _r = NULL;
  460. int tmp = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_postgres_val2str,
  461. db_postgres_submit_query);
  462. if (db_postgres_store_result(_h, &_r) != 0)
  463. LM_WARN("unexpected result returned");
  464. if (_r)
  465. db_free_result(_r);
  466. return tmp;
  467. }
  468. /*!
  469. * Store name of table that will be used by subsequent database functions
  470. * \param _con database connection
  471. * \param _t table name
  472. * \return 0 on success, negative on error
  473. */
  474. int db_postgres_use_table(db1_con_t* _con, const str* _t)
  475. {
  476. return db_use_table(_con, _t);
  477. }