km_dbase.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 "../../db/db.h"
  72. #include "../../db/db_ut.h"
  73. #include "../../db/db_query.h"
  74. #include "dbase.h"
  75. #include "pg_con.h"
  76. #include "val.h"
  77. #include "res.h"
  78. static void free_query(const db_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. db_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(db_con_t* _h)
  95. {
  96. db_do_close(_h, db_postgres_free_connection);
  97. }
  98. /*!
  99. * \brief Submit_query, run a query
  100. * \param _h database connection
  101. * \param _s query string
  102. * \return 0 on success, negative on failure
  103. */
  104. static int db_postgres_submit_query(const db_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. if(CON_RESULT(_con))
  134. {
  135. free_query(_con);
  136. }
  137. /* exec the query */
  138. if (PQsendQuery(CON_CONNECTION(_con), _s->s)) {
  139. LM_DBG("%p PQsendQuery(%.*s)\n", _con, _s->len, _s->s);
  140. } else {
  141. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  142. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  143. return -1;
  144. }
  145. return 0;
  146. }
  147. /*!
  148. * \brief Gets a partial result set, fetch rows from a result
  149. *
  150. * Gets a partial result set, fetch a number of rows from a database result.
  151. * This function initialize the given result structure on the first run, and
  152. * fetches the nrows number of rows. On subsequenting runs, it uses the
  153. * existing result and fetches more rows, until it reaches the end of the
  154. * result set. Because of this the result needs to be null in the first
  155. * invocation of the function. If the number of wanted rows is zero, the
  156. * function returns anything with a result of zero.
  157. * \param _con database connection
  158. * \param _res result set
  159. * \param nrows number of fetches rows
  160. * \return 0 on success, negative on failure
  161. */
  162. int db_postgres_fetch_result(const db_con_t* _con, db_res_t** _res, const int nrows)
  163. {
  164. int rows;
  165. PGresult *res = NULL;
  166. ExecStatusType pqresult;
  167. if (!_con || !_res || nrows < 0) {
  168. LM_ERR("invalid parameter value\n");
  169. return -1;
  170. }
  171. /* exit if the fetch count is zero */
  172. if (nrows == 0) {
  173. if (*_res)
  174. db_free_result(*_res);
  175. *_res = 0;
  176. return 0;
  177. }
  178. if (*_res == NULL) {
  179. /* Allocate a new result structure */
  180. *_res = db_new_result();
  181. /* Get the result of the previous query */
  182. while (1) {
  183. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  184. CON_RESULT(_con) = res;
  185. } else {
  186. break;
  187. }
  188. }
  189. pqresult = PQresultStatus(CON_RESULT(_con));
  190. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  191. PQresStatus(pqresult), CON_RESULT(_con));
  192. switch(pqresult) {
  193. case PGRES_COMMAND_OK:
  194. /* Successful completion of a command returning no data (such as INSERT or UPDATE). */
  195. return 0;
  196. case PGRES_TUPLES_OK:
  197. /* Successful completion of a command returning data (such as a SELECT or SHOW). */
  198. if (db_postgres_get_columns(_con, *_res) < 0) {
  199. LM_ERR("failed to get column names\n");
  200. return -2;
  201. }
  202. break;
  203. case PGRES_FATAL_ERROR:
  204. LM_ERR("%p - invalid query, execution aborted\n", _con);
  205. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  206. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  207. if (*_res)
  208. db_free_result(*_res);
  209. *_res = 0;
  210. return -3;
  211. case PGRES_EMPTY_QUERY:
  212. /* notice or warning */
  213. case PGRES_NONFATAL_ERROR:
  214. /* status for COPY command, not used */
  215. case PGRES_COPY_OUT:
  216. case PGRES_COPY_IN:
  217. /* unexpected response */
  218. case PGRES_BAD_RESPONSE:
  219. default:
  220. LM_ERR("%p - probable invalid query\n", _con);
  221. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  222. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  223. if (*_res)
  224. db_free_result(*_res);
  225. *_res = 0;
  226. return -4;
  227. }
  228. } else {
  229. if(RES_ROWS(*_res) != NULL) {
  230. db_free_rows(*_res);
  231. }
  232. RES_ROWS(*_res) = 0;
  233. RES_ROW_N(*_res) = 0;
  234. }
  235. /* Get the number of rows (tuples) in the query result. */
  236. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  237. /* determine the number of rows remaining to be processed */
  238. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  239. /* If there aren't any more rows left to process, exit */
  240. if (rows <= 0)
  241. return 0;
  242. /* if the fetch count is less than the remaining rows to process */
  243. /* set the number of rows to process (during this call) equal to the fetch count */
  244. if (nrows < rows)
  245. rows = nrows;
  246. RES_ROW_N(*_res) = rows;
  247. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  248. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  249. if (db_postgres_convert_rows(_con, *_res) < 0) {
  250. LM_ERR("failed to convert rows\n");
  251. if (*_res)
  252. db_free_result(*_res);
  253. *_res = 0;
  254. return -3;
  255. }
  256. /* update the total number of rows processed */
  257. RES_LAST_ROW(*_res) += rows;
  258. return 0;
  259. }
  260. /*!
  261. * \brief Free database and any old query results
  262. * \param _h database connection
  263. */
  264. static void free_query(const db_con_t* _con)
  265. {
  266. if(CON_RESULT(_con))
  267. {
  268. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  269. PQclear(CON_RESULT(_con));
  270. CON_RESULT(_con) = 0;
  271. }
  272. }
  273. /*!
  274. * \brief Free the query and the result memory in the core
  275. * \param _con database connection
  276. * \param _r result set
  277. * \return 0 on success, -1 on failure
  278. */
  279. int db_postgres_free_result(db_con_t* _con, db_res_t* _r)
  280. {
  281. if ((!_con) || (!_r)) {
  282. LM_ERR("invalid parameter value\n");
  283. return -1;
  284. }
  285. if (db_free_result(_r) < 0) {
  286. LM_ERR("unable to free result structure\n");
  287. return -1;
  288. }
  289. free_query(_con);
  290. return 0;
  291. }
  292. /*!
  293. * \brief Query table for specified rows
  294. * \param _con structure representing database connection
  295. * \param _k key names
  296. * \param _op operators
  297. * \param _v values of the keys that must match
  298. * \param _c column names to return
  299. * \param _n nmber of key=values pairs to compare
  300. * \param _nc number of columns to return
  301. * \param _o order by the specified column
  302. * \return 0 on success, negative on failure
  303. */
  304. int db_postgres_query(const db_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  305. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  306. const db_key_t _o, db_res_t** _r)
  307. {
  308. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  309. db_postgres_submit_query, db_postgres_store_result);
  310. }
  311. /*!
  312. * Execute a raw SQL query
  313. * \param _h database connection
  314. * \param _s raw query string
  315. * \param _r result set
  316. * \return 0 on success, negative on failure
  317. */
  318. int db_postgres_raw_query(const db_con_t* _h, const str* _s, db_res_t** _r)
  319. {
  320. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  321. db_postgres_store_result);
  322. }
  323. /*!
  324. * \brief Retrieve result set
  325. * \param _con structure representing the database connection
  326. * \param _r pointer to a structure represending the result set
  327. * \return 0 If the status of the last command produced a result set and,
  328. * If the result set contains data or the convert_result() routine
  329. * completed successfully. Negative if the status of the last command was
  330. * not handled or if the convert_result() returned an error.
  331. * \note A new result structure is allocated on every call to this routine.
  332. * If this routine returns 0, it is the callers responsbility to free the
  333. * result structure. If this routine returns < 0, then the result structure
  334. * is freed before returning to the caller.
  335. */
  336. int db_postgres_store_result(const db_con_t* _con, db_res_t** _r)
  337. {
  338. PGresult *res = NULL;
  339. ExecStatusType pqresult;
  340. int rc = 0;
  341. *_r = db_new_result();
  342. if (*_r==NULL) {
  343. LM_ERR("failed to init new result\n");
  344. rc = -1;
  345. goto done;
  346. }
  347. while (1) {
  348. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  349. CON_RESULT(_con) = res;
  350. } else {
  351. break;
  352. }
  353. }
  354. pqresult = PQresultStatus(CON_RESULT(_con));
  355. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  356. PQresStatus(pqresult), CON_RESULT(_con));
  357. switch(pqresult) {
  358. case PGRES_COMMAND_OK:
  359. /* Successful completion of a command returning no data
  360. * (such as INSERT or UPDATE). */
  361. rc = 0;
  362. break;
  363. case PGRES_TUPLES_OK:
  364. /* Successful completion of a command returning data
  365. * (such as a SELECT or SHOW). */
  366. if (db_postgres_convert_result(_con, *_r) < 0) {
  367. LM_ERR("%p Error returned from convert_result()\n", _con);
  368. db_free_result(*_r);
  369. *_r = 0;
  370. rc = -4;
  371. break;
  372. }
  373. rc = 0;
  374. break;
  375. /* query failed */
  376. case PGRES_FATAL_ERROR:
  377. LM_ERR("%p - invalid query, execution aborted\n", _con);
  378. LM_ERR("%p: %s\n", _con, PQresStatus(pqresult));
  379. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  380. db_free_result(*_r);
  381. *_r = 0;
  382. rc = -3;
  383. break;
  384. case PGRES_EMPTY_QUERY:
  385. /* notice or warning */
  386. case PGRES_NONFATAL_ERROR:
  387. /* status for COPY command, not used */
  388. case PGRES_COPY_OUT:
  389. case PGRES_COPY_IN:
  390. /* unexpected response */
  391. case PGRES_BAD_RESPONSE:
  392. default:
  393. LM_ERR("%p Probable invalid query\n", _con);
  394. LM_ERR("%p: %s\n", _con, PQresStatus(pqresult));
  395. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  396. db_free_result(*_r);
  397. *_r = 0;
  398. rc = -4;
  399. break;
  400. }
  401. done:
  402. free_query(_con);
  403. return (rc);
  404. }
  405. /*!
  406. * \brief Insert a row into specified table
  407. * \param _h structure representing database connection
  408. * \param _k key names
  409. * \param _v values of the keys
  410. * \param _n number of key=value pairs
  411. * \return 0 on success, negative on failure
  412. */
  413. int db_postgres_insert(const db_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  414. const int _n)
  415. {
  416. db_res_t* _r = NULL;
  417. int tmp = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  418. // finish the async query, otherwise the next query will not complete
  419. if (db_postgres_store_result(_h, &_r) != 0)
  420. LM_WARN("unexpected result returned");
  421. if (_r)
  422. db_free_result(_r);
  423. return tmp;
  424. }
  425. /*!
  426. * \brief Delete a row from the specified table
  427. * \param _h structure representing database connection
  428. * \param _k key names
  429. * \param _o operators
  430. * \param _v values of the keys that must match
  431. * \param _n number of key=value pairs
  432. * \return 0 on success, negative on failure
  433. */
  434. int db_postgres_delete(const db_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  435. const db_val_t* _v, const int _n)
  436. {
  437. db_res_t* _r = NULL;
  438. int tmp = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  439. db_postgres_submit_query);
  440. if (db_postgres_store_result(_h, &_r) != 0)
  441. LM_WARN("unexpected result returned");
  442. if (_r)
  443. db_free_result(_r);
  444. return tmp;
  445. }
  446. /*!
  447. * Update some rows in the specified table
  448. * \param _h structure representing database connection
  449. * \param _k key names
  450. * \param _o operators
  451. * \param _v values of the keys that must match
  452. * \param _uk updated columns
  453. * \param _uv updated values of the columns
  454. * \param _n number of key=value pairs
  455. * \param _un number of columns to update
  456. * \return 0 on success, negative on failure
  457. */
  458. int db_postgres_update(const db_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  459. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  460. const int _un)
  461. {
  462. db_res_t* _r = NULL;
  463. int tmp = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, 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. * Store name of table that will be used by subsequent database functions
  473. * \param _con database connection
  474. * \param _t table name
  475. * \return 0 on success, negative on error
  476. */
  477. int db_postgres_use_table(db_con_t* _con, const str* _t)
  478. {
  479. return db_use_table(_con, _t);
  480. }