km_dbase.c 15 KB

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