km_dbase.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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 <stdlib.h>
  70. #include "../../dprint.h"
  71. #include "../../mem/mem.h"
  72. #include "../../lib/srdb1/db.h"
  73. #include "../../lib/srdb1/db_ut.h"
  74. #include "../../lib/srdb1/db_query.h"
  75. #include "km_dbase.h"
  76. #include "km_pg_con.h"
  77. #include "km_val.h"
  78. #include "km_res.h"
  79. #include "pg_mod.h"
  80. static void db_postgres_free_query(const db1_con_t* _con);
  81. /*!
  82. * \brief Initialize database for future queries
  83. * \param _url URL of the database that should be opened
  84. * \return database connection on success, NULL on error
  85. * \note this function must be called prior to any database functions
  86. */
  87. db1_con_t *db_postgres_init(const str* _url)
  88. {
  89. return db_do_init(_url, (void*) db_postgres_new_connection);
  90. }
  91. /*!
  92. * \brief Close database when the database is no longer needed
  93. * \param _h closed connection, as returned from db_postgres_init
  94. * \note free all memory and resources
  95. */
  96. void db_postgres_close(db1_con_t* _h)
  97. {
  98. db_do_close(_h, db_postgres_free_connection);
  99. }
  100. /*!
  101. * \brief Submit_query, run a query
  102. * \param _con database connection
  103. * \param _s query string
  104. * \return 0 on success, negative on failure
  105. */
  106. static int db_postgres_submit_query(const db1_con_t* _con, const str* _s)
  107. {
  108. int i;
  109. ExecStatusType pqresult;
  110. if(! _con || !_s || !_s->s)
  111. {
  112. LM_ERR("invalid parameter value\n");
  113. return(-1);
  114. }
  115. /* this bit of nonsense in case our connection get screwed up */
  116. switch(PQstatus(CON_CONNECTION(_con)))
  117. {
  118. case CONNECTION_OK:
  119. break;
  120. case CONNECTION_BAD:
  121. LM_DBG("connection reset\n");
  122. PQreset(CON_CONNECTION(_con));
  123. break;
  124. case CONNECTION_STARTED:
  125. case CONNECTION_MADE:
  126. case CONNECTION_AWAITING_RESPONSE:
  127. case CONNECTION_AUTH_OK:
  128. case CONNECTION_SETENV:
  129. case CONNECTION_SSL_STARTUP:
  130. case CONNECTION_NEEDED:
  131. default:
  132. LM_ERR("%p PQstatus(%s) invalid: %.*s\n", _con,
  133. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  134. return -1;
  135. }
  136. for(i = 0; i <= pg_retries; i++) {
  137. /* free any previous query that is laying about */
  138. db_postgres_free_query(_con);
  139. /* exec the query */
  140. if (PQsendQuery(CON_CONNECTION(_con), _s->s)) {
  141. pqresult = PQresultStatus(CON_RESULT(_con));
  142. if((pqresult!=PGRES_FATAL_ERROR)
  143. || (PQstatus(CON_CONNECTION(_con))==CONNECTION_OK))
  144. {
  145. LM_DBG("sending query ok: %p (%d) - [%.*s]\n",
  146. _con, pqresult, _s->len, _s->s);
  147. return 0;
  148. }
  149. LM_WARN("postgres result check failed with code %d (%s)\n",
  150. pqresult, PQresStatus(pqresult));
  151. }
  152. LM_WARN("postgres query command failed, connection status %d,"
  153. " error [%s]\n", PQstatus(CON_CONNECTION(_con)),
  154. PQerrorMessage(CON_CONNECTION(_con)));
  155. if(PQstatus(CON_CONNECTION(_con))!=CONNECTION_OK)
  156. {
  157. LM_DBG("reseting the connection to postgress server\n");
  158. PQreset(CON_CONNECTION(_con));
  159. }
  160. }
  161. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  162. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  163. return -1;
  164. }
  165. /*!
  166. * \brief Gets a partial result set, fetch rows from a result
  167. *
  168. * Gets a partial result set, fetch a number of rows from a database result.
  169. * This function initialize the given result structure on the first run, and
  170. * fetches the nrows number of rows. On subsequenting runs, it uses the
  171. * existing result and fetches more rows, until it reaches the end of the
  172. * result set. Because of this the result needs to be null in the first
  173. * invocation of the function. If the number of wanted rows is zero, the
  174. * function returns anything with a result of zero.
  175. * \param _con database connection
  176. * \param _res result set
  177. * \param nrows number of fetches rows
  178. * \return 0 on success, negative on failure
  179. */
  180. int db_postgres_fetch_result(const db1_con_t* _con, db1_res_t** _res, const int nrows)
  181. {
  182. int rows;
  183. PGresult *res = NULL;
  184. ExecStatusType pqresult;
  185. if (!_con || !_res || nrows < 0) {
  186. LM_ERR("invalid parameter value\n");
  187. return -1;
  188. }
  189. /* exit if the fetch count is zero */
  190. if (nrows == 0) {
  191. if (*_res)
  192. db_free_result(*_res);
  193. *_res = 0;
  194. return 0;
  195. }
  196. if (*_res == NULL) {
  197. /* Allocate a new result structure */
  198. *_res = db_new_result();
  199. /* Get the result of the previous query */
  200. while (1) {
  201. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  202. CON_RESULT(_con) = res;
  203. } else {
  204. break;
  205. }
  206. }
  207. pqresult = PQresultStatus(CON_RESULT(_con));
  208. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  209. PQresStatus(pqresult), CON_RESULT(_con));
  210. switch(pqresult) {
  211. case PGRES_COMMAND_OK:
  212. /* Successful completion of a command returning no data
  213. * (such as INSERT or UPDATE). */
  214. return 0;
  215. case PGRES_TUPLES_OK:
  216. /* Successful completion of a command returning data
  217. * (such as a SELECT or SHOW). */
  218. if (db_postgres_get_columns(_con, *_res) < 0) {
  219. LM_ERR("failed to get column names\n");
  220. return -2;
  221. }
  222. break;
  223. case PGRES_FATAL_ERROR:
  224. LM_ERR("%p - invalid query, execution aborted\n", _con);
  225. LM_ERR("%p - PQresultStatus(%s)\n", _con,
  226. PQresStatus(pqresult));
  227. LM_ERR("%p: %s\n", _con,
  228. PQresultErrorMessage(CON_RESULT(_con)));
  229. if (*_res)
  230. db_free_result(*_res);
  231. *_res = 0;
  232. return -3;
  233. case PGRES_EMPTY_QUERY:
  234. /* notice or warning */
  235. case PGRES_NONFATAL_ERROR:
  236. /* status for COPY command, not used */
  237. case PGRES_COPY_OUT:
  238. case PGRES_COPY_IN:
  239. /* unexpected response */
  240. case PGRES_BAD_RESPONSE:
  241. default:
  242. LM_ERR("%p - probable invalid query\n", _con);
  243. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  244. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  245. if (*_res)
  246. db_free_result(*_res);
  247. *_res = 0;
  248. return -4;
  249. }
  250. } else {
  251. if(RES_ROWS(*_res) != NULL) {
  252. db_free_rows(*_res);
  253. }
  254. RES_ROWS(*_res) = 0;
  255. RES_ROW_N(*_res) = 0;
  256. }
  257. /* Get the number of rows (tuples) in the query result. */
  258. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  259. /* determine the number of rows remaining to be processed */
  260. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  261. /* If there aren't any more rows left to process, exit */
  262. if (rows <= 0)
  263. return 0;
  264. /* if the fetch count is less than the remaining rows to process */
  265. /* set the number of rows to process (during this call) equal to the fetch count */
  266. if (nrows < rows)
  267. rows = nrows;
  268. RES_ROW_N(*_res) = rows;
  269. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  270. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  271. if (db_postgres_convert_rows(_con, *_res) < 0) {
  272. LM_ERR("failed to convert rows\n");
  273. if (*_res)
  274. db_free_result(*_res);
  275. *_res = 0;
  276. return -3;
  277. }
  278. /* update the total number of rows processed */
  279. RES_LAST_ROW(*_res) += rows;
  280. return 0;
  281. }
  282. /*!
  283. * \brief Free database and any old query results
  284. * \param _con database connection
  285. */
  286. static void db_postgres_free_query(const db1_con_t* _con)
  287. {
  288. if(CON_RESULT(_con))
  289. {
  290. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  291. PQclear(CON_RESULT(_con));
  292. CON_RESULT(_con) = 0;
  293. }
  294. }
  295. /*!
  296. * \brief Free the query and the result memory in the core
  297. * \param _con database connection
  298. * \param _r result set
  299. * \return 0 on success, -1 on failure
  300. */
  301. int db_postgres_free_result(db1_con_t* _con, db1_res_t* _r)
  302. {
  303. if ((!_con) || (!_r)) {
  304. LM_ERR("invalid parameter value\n");
  305. return -1;
  306. }
  307. if (db_free_result(_r) < 0) {
  308. LM_ERR("unable to free result structure\n");
  309. return -1;
  310. }
  311. db_postgres_free_query(_con);
  312. return 0;
  313. }
  314. /*!
  315. * \brief Query table for specified rows
  316. * \param _h structure representing database connection
  317. * \param _k key names
  318. * \param _op operators
  319. * \param _v values of the keys that must match
  320. * \param _c column names to return
  321. * \param _n nmber of key=values pairs to compare
  322. * \param _nc number of columns to return
  323. * \param _o order by the specified column
  324. * \param _r result set
  325. * \return 0 on success, negative on failure
  326. */
  327. int db_postgres_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  328. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  329. const db_key_t _o, db1_res_t** _r)
  330. {
  331. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  332. db_postgres_submit_query, db_postgres_store_result);
  333. }
  334. /*!
  335. * Execute a raw SQL query
  336. * \param _h database connection
  337. * \param _s raw query string
  338. * \param _r result set
  339. * \return 0 on success, negative on failure
  340. */
  341. int db_postgres_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  342. {
  343. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  344. db_postgres_store_result);
  345. }
  346. /*!
  347. * \brief Retrieve result set
  348. * \param _con structure representing the database connection
  349. * \param _r pointer to a structure represending the result set
  350. * \return 0 If the status of the last command produced a result set and,
  351. * If the result set contains data or the convert_result() routine
  352. * completed successfully. Negative if the status of the last command was
  353. * not handled or if the convert_result() returned an error.
  354. * \note A new result structure is allocated on every call to this routine.
  355. * If this routine returns 0, it is the callers responsbility to free the
  356. * result structure. If this routine returns < 0, then the result structure
  357. * is freed before returning to the caller.
  358. */
  359. int db_postgres_store_result(const db1_con_t* _con, db1_res_t** _r)
  360. {
  361. PGresult *res = NULL;
  362. ExecStatusType pqresult;
  363. int rc = 0;
  364. *_r = db_new_result();
  365. if (*_r==NULL) {
  366. LM_ERR("failed to init new result\n");
  367. rc = -1;
  368. goto done;
  369. }
  370. while (1) {
  371. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  372. CON_RESULT(_con) = res;
  373. } else {
  374. break;
  375. }
  376. }
  377. pqresult = PQresultStatus(CON_RESULT(_con));
  378. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  379. PQresStatus(pqresult), CON_RESULT(_con));
  380. CON_AFFECTED(_con) = 0;
  381. switch(pqresult) {
  382. case PGRES_COMMAND_OK:
  383. /* Successful completion of a command returning no data
  384. * (such as INSERT or UPDATE). */
  385. rc = 0;
  386. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  387. break;
  388. case PGRES_TUPLES_OK:
  389. /* Successful completion of a command returning data
  390. * (such as a SELECT or SHOW). */
  391. if (db_postgres_convert_result(_con, *_r) < 0) {
  392. LM_ERR("error while converting result\n");
  393. LM_DBG("freeing result set at %p\n", _r);
  394. pkg_free(*_r);
  395. *_r = 0;
  396. rc = -4;
  397. break;
  398. }
  399. rc = 0;
  400. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  401. break;
  402. /* query failed */
  403. case PGRES_FATAL_ERROR:
  404. LM_ERR("invalid query, execution aborted\n");
  405. LM_ERR("driver error: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  406. db_free_result(*_r);
  407. *_r = 0;
  408. rc = -3;
  409. break;
  410. case PGRES_EMPTY_QUERY:
  411. /* notice or warning */
  412. case PGRES_NONFATAL_ERROR:
  413. /* status for COPY command, not used */
  414. case PGRES_COPY_OUT:
  415. case PGRES_COPY_IN:
  416. /* unexpected response */
  417. case PGRES_BAD_RESPONSE:
  418. default:
  419. LM_ERR("probable invalid query, execution aborted\n");
  420. LM_ERR("driver message: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  421. db_free_result(*_r);
  422. *_r = 0;
  423. rc = -4;
  424. break;
  425. }
  426. done:
  427. db_postgres_free_query(_con);
  428. return (rc);
  429. }
  430. /*!
  431. * \brief Insert a row into specified table
  432. * \param _h structure representing database connection
  433. * \param _k key names
  434. * \param _v values of the keys
  435. * \param _n number of key=value pairs
  436. * \return 0 on success, negative on failure
  437. */
  438. int db_postgres_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  439. const int _n)
  440. {
  441. db1_res_t* _r = NULL;
  442. int tmp = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  443. // finish the async query, otherwise the next query will not complete
  444. if (db_postgres_store_result(_h, &_r) != 0)
  445. LM_WARN("unexpected result returned");
  446. if (_r)
  447. db_free_result(_r);
  448. return tmp;
  449. }
  450. /*!
  451. * \brief Delete a row from the specified table
  452. * \param _h structure representing database connection
  453. * \param _k key names
  454. * \param _o operators
  455. * \param _v values of the keys that must match
  456. * \param _n number of key=value pairs
  457. * \return 0 on success, negative on failure
  458. */
  459. int db_postgres_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  460. const db_val_t* _v, const int _n)
  461. {
  462. db1_res_t* _r = NULL;
  463. int tmp = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  464. db_postgres_submit_query);
  465. if (db_postgres_store_result(_h, &_r) != 0)
  466. LM_WARN("unexpected result returned");
  467. if (_r)
  468. db_free_result(_r);
  469. return tmp;
  470. }
  471. /*!
  472. * Update some rows in the specified table
  473. * \param _h structure representing database connection
  474. * \param _k key names
  475. * \param _o operators
  476. * \param _v values of the keys that must match
  477. * \param _uk updated columns
  478. * \param _uv updated values of the columns
  479. * \param _n number of key=value pairs
  480. * \param _un number of columns to update
  481. * \return 0 on success, negative on failure
  482. */
  483. int db_postgres_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  484. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  485. const int _un)
  486. {
  487. db1_res_t* _r = NULL;
  488. int tmp = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_postgres_val2str,
  489. db_postgres_submit_query);
  490. if (db_postgres_store_result(_h, &_r) != 0)
  491. LM_WARN("unexpected result returned");
  492. if (_r)
  493. db_free_result(_r);
  494. return tmp;
  495. }
  496. /**
  497. * Returns the affected rows of the last query.
  498. * \param _h database handle
  499. * \return returns the affected rows as integer or -1 on error.
  500. */
  501. int db_postgres_affected_rows(const db1_con_t* _h)
  502. {
  503. if (!_h) {
  504. LM_ERR("invalid parameter value\n");
  505. return -1;
  506. }
  507. return CON_AFFECTED(_h);
  508. }
  509. /*!
  510. * Store name of table that will be used by subsequent database functions
  511. * \param _con database connection
  512. * \param _t table name
  513. * \return 0 on success, negative on error
  514. */
  515. int db_postgres_use_table(db1_con_t* _con, const str* _t)
  516. {
  517. return db_use_table(_con, _t);
  518. }