dbase.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /*
  2. * $Id$
  3. *
  4. * Postgres module core functions
  5. *
  6. * Portions Copyright (C) 2001-2003 FhG FOKUS
  7. * Copyright (C) 2003 August.Net Services, LLC
  8. * Portions Copyright (C) 2005 iptelorg GmbH
  9. *
  10. * This file is part of ser, a free SIP server.
  11. *
  12. * ser is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version
  16. *
  17. * For a license to use the ser software under conditions
  18. * other than those described here, or to purchase support for this
  19. * software, please contact iptel.org by e-mail at the following addresses:
  20. * [email protected]
  21. *
  22. * ser is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program; if not, write to the Free Software
  29. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  30. */
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <stdlib.h>
  34. #include <time.h>
  35. #include <libpq-fe.h>
  36. #include <netinet/in.h>
  37. #include "../../mem/mem.h"
  38. #include "../../dprint.h"
  39. #include "../../db/db_pool.h"
  40. #include "../../ut.h"
  41. #include "../../globals.h"
  42. #include "../../pt.h"
  43. #include "pg_con.h"
  44. #include "pg_type.h"
  45. #include "db_mod.h"
  46. #include "res.h"
  47. #include "dbase.h"
  48. #define SELECTALL "select * "
  49. #define SELECT "select "
  50. #define FROM "from "
  51. #define ORDER "order by "
  52. #define WHERE "where "
  53. #define AND " and "
  54. #define INSERT "insert into "
  55. #define VALUES ") values ("
  56. #define DELETE "delete from "
  57. #define UPDATE "update "
  58. #define SET "set "
  59. #define MAX_OPERATOR_LEN (sizeof(" is NULL") - 1)
  60. struct pg_params {
  61. int n;
  62. int cur;
  63. const char** data;
  64. int* len;
  65. int* formats;
  66. Oid* types;
  67. };
  68. static void free_pg_params(struct pg_params* ptr)
  69. {
  70. if (!ptr) return;
  71. if (ptr->data) pkg_free(ptr->data);
  72. if (ptr->len) pkg_free(ptr->len);
  73. if (ptr->formats) pkg_free(ptr->formats);
  74. if (ptr->types) pkg_free(ptr->types);
  75. pkg_free(ptr);
  76. }
  77. static struct pg_params* new_pg_params(int n)
  78. {
  79. struct pg_params* ptr;
  80. ptr = (struct pg_params*)pkg_malloc(sizeof(struct pg_params));
  81. if (!ptr) goto error;
  82. ptr->formats = (int*)pkg_malloc(sizeof(int) * n);
  83. if (!ptr->formats) goto error;
  84. ptr->data = (const char**)pkg_malloc(sizeof(const char*) * n);
  85. if (!ptr->data) goto error;
  86. ptr->len = (int*)pkg_malloc(sizeof(int) * n);
  87. if (!ptr->len) goto error;
  88. ptr->types = (int*)pkg_malloc(sizeof(Oid) * n);
  89. if (!ptr->types) goto error;
  90. memset((char*)ptr->data, 0, sizeof(const char*) * n);
  91. memset(ptr->len, 0, sizeof(int) * n);
  92. memset(ptr->types, 0, sizeof(Oid) * n);
  93. ptr->n = n;
  94. ptr->cur = 0;
  95. return ptr;
  96. error:
  97. ERR("No memory left\n");
  98. free_pg_params(ptr);
  99. return 0;
  100. }
  101. static inline int params_add(struct pg_params* p, db_con_t* con, db_val_t* vals, int n, int skip_null)
  102. {
  103. int i, i1, i2;
  104. db_val_t* val;
  105. if (!p) {
  106. ERR("Invalid parameter value\n");
  107. return -1;
  108. }
  109. if (p->cur + n > p->n) {
  110. ERR("Arrays too short (bug in postgres module)\n");
  111. return -1;
  112. }
  113. for(i = 0; i < n; i++) {
  114. val = &vals[i];
  115. p->formats[p->cur] = 1;
  116. if (val->nul) {
  117. /* When assembling parameters for where clause we skip parameters
  118. * that have null values because they are expressed as is null.
  119. * At other places we include them.
  120. */
  121. if (!skip_null) p->cur++;
  122. continue;
  123. }
  124. switch(val->type) {
  125. case DB_INT:
  126. val->val.int_val = ntohl(val->val.int_val);
  127. p->data[p->cur] = (const char*)&val->val.int_val;
  128. p->len[p->cur] = 4;
  129. p->types[p->cur] = INT4OID;
  130. break;
  131. case DB_FLOAT:
  132. /* Change the byte order of 4-byte value to network
  133. * byte order if necessary
  134. */
  135. val->val.int_val = htonl(val->val.int_val);
  136. p->data[p->cur] = (const char*)&val->val.int_val;
  137. p->len[p->cur] = 4;
  138. p->types[p->cur] = FLOAT4OID;
  139. break;
  140. case DB_DOUBLE:
  141. /* Change the byte order of 8-byte value to network
  142. * byte order if necessary
  143. */
  144. i1 = htonl(val->val.int8_val >> 32);
  145. i2 = htonl(val->val.int8_val & 0xffffffff);
  146. val->val.int_val = i1;
  147. (&val->val.int_val)[1] = i2;
  148. p->data[p->cur] = (const char*)&val->val.int_val;
  149. p->len[p->cur] = 8;
  150. p->types[p->cur] = FLOAT8OID;
  151. break;
  152. case DB_STRING:
  153. p->formats[p->cur] = 0;
  154. p->data[p->cur] = val->val.string_val;
  155. break;
  156. case DB_STR:
  157. p->data[p->cur] = val->val.str_val.s;
  158. p->len[p->cur] = val->val.str_val.len;
  159. break;
  160. case DB_DATETIME:
  161. if (CON_FLAGS(con) & PG_INT8_TIMESTAMP) {
  162. val->val.int8_val = ((long long)val->val.time_val - PG_EPOCH_TIME) * 1000000;
  163. } else {
  164. val->val.double_val = (double)val->val.time_val - (double)PG_EPOCH_TIME;
  165. }
  166. i1 = htonl(val->val.int8_val >> 32);
  167. i2 = htonl(val->val.int8_val & 0xffffffff);
  168. val->val.int_val = i1;
  169. (&val->val.int_val)[1] = i2;
  170. p->data[p->cur] = (const char*)&val->val.int_val;
  171. p->len[p->cur] = 8;
  172. p->types[p->cur] = TIMESTAMPOID;
  173. break;
  174. case DB_BLOB:
  175. p->data[p->cur] = val->val.blob_val.s;
  176. p->len[p->cur] = val->val.blob_val.len;
  177. break;
  178. case DB_BITMAP:
  179. (&val->val.int_val)[1] = htonl(val->val.int_val);
  180. val->val.int_val = htonl(32);
  181. p->data[p->cur] = (const char*)&val->val.int_val;
  182. p->len[p->cur] = 8;
  183. p->types[p->cur] = BITOID;
  184. break;
  185. }
  186. p->cur++;
  187. }
  188. return 0;
  189. }
  190. static inline void free_params(struct pg_params* p)
  191. {
  192. if (p->data) pkg_free(p->data);
  193. if (p->len) pkg_free(p->len);
  194. if (p->formats) pkg_free(p->formats);
  195. }
  196. /*
  197. * Initialize database module
  198. * No function should be called before this
  199. */
  200. db_con_t* pg_init(const char* url)
  201. {
  202. struct db_id* id;
  203. struct pg_con* con;
  204. db_con_t* res;
  205. id = 0;
  206. res = 0;
  207. /* if called from PROC_MAIN, allow it only from mod_init( when pt==0)*/
  208. if (is_main && fixup_complete){
  209. LOG(L_ERR, "BUG: postgres: pg_init: called from the main process,"
  210. " ignoring...\n");
  211. }
  212. if (!url) {
  213. ERR("Invalid parameter value\n");
  214. return 0;
  215. }
  216. res = pkg_malloc(sizeof(db_con_t) + sizeof(struct pg_con*));
  217. if (!res) {
  218. ERR("No memory left\n");
  219. return 0;
  220. }
  221. memset(res, 0, sizeof(db_con_t) + sizeof(struct pg_con*));
  222. id = new_db_id(url);
  223. if (!id) {
  224. ERR("Cannot parse URL '%s'\n", url);
  225. goto err;
  226. }
  227. /* Find the connection in the pool */
  228. con = (struct pg_con*)pool_get(id);
  229. if (!con) {
  230. DBG("Connection '%s' not found in pool\n", url);
  231. /* Not in the pool yet */
  232. con = pg_new_connection(id);
  233. if (!con) {
  234. goto err;
  235. }
  236. pool_insert((struct pool_con*)con);
  237. } else {
  238. DBG("Connection '%s' found in pool\n", url);
  239. }
  240. res->tail = (unsigned long)con;
  241. return res;
  242. err:
  243. if (id) free_db_id(id);
  244. if (res) pkg_free(res);
  245. return 0;
  246. }
  247. /*
  248. * Shut down database module
  249. * No function should be called after this
  250. */
  251. void pg_close(db_con_t* handle)
  252. {
  253. struct pool_con* con;
  254. if (!handle) {
  255. ERR("Invalid parameter value\n");
  256. return;
  257. }
  258. con = (struct pool_con*)handle->tail;
  259. if (pool_remove(con) != 0) {
  260. pg_free_connection((struct pg_con*)con);
  261. }
  262. pkg_free(handle);
  263. }
  264. static int calc_param_len(start, num)
  265. {
  266. int max, len, order;
  267. if (!num) return 0;
  268. max = start + num - 1;
  269. len = num; /* $ */
  270. order = 0;
  271. while(max) {
  272. order++;
  273. max /= 10;
  274. }
  275. return len + order * num;
  276. }
  277. /*
  278. * Append a constant string, uses sizeof to figure the length
  279. * of the string
  280. */
  281. #define append(buf, ptr) \
  282. do { \
  283. if ((buf).len < (sizeof(ptr) - 1)) goto shortbuf; \
  284. memcpy((buf).s, (ptr), sizeof(ptr) - 1); \
  285. (buf).s += sizeof(ptr) - 1; \
  286. (buf).len -= sizeof(ptr) - 1; \
  287. } while(0);
  288. /*
  289. * Append zero terminated string, uses strlen to obtain the
  290. * length of the string
  291. */
  292. #define append_str(buf, op) \
  293. do { \
  294. int len; \
  295. len = strlen(op); \
  296. if ((buf).len < len) goto shortbuf; \
  297. memcpy((buf).s, (op), len); \
  298. (buf).s += len; \
  299. (buf).len -= len; \
  300. } while(0);
  301. /*
  302. * Append a parameter, accepts the number of the
  303. * parameter to be appended
  304. */
  305. #define append_param(buf, num) \
  306. do { \
  307. const char* c; \
  308. int len; \
  309. c = int2str((num), &len); \
  310. if ((buf).len < len + 1) goto shortbuf; \
  311. *(buf).s='$'; (buf).s++; (buf).len--; \
  312. memcpy((buf).s, c, len); \
  313. (buf).s += len; (buf).len -= len; \
  314. } while(0);
  315. /*
  316. * Calculate the length of buffer needed to hold the insert query
  317. */
  318. static unsigned int calc_insert_len(db_con_t* con, db_key_t* keys, int n)
  319. {
  320. int i;
  321. unsigned int len;
  322. if (!n) return 0;
  323. len = sizeof(INSERT) - 1;
  324. len += strlen(CON_TABLE(con)); /* Table name */
  325. len += 2; /* _( */
  326. for(i = 0; i < n; i++) {
  327. len += strlen(keys[i]); /* Key names */
  328. }
  329. len += n - 1; /* , */
  330. len += sizeof(VALUES);
  331. len += calc_param_len(1, n);
  332. len += n - 1;
  333. len += 1; /* ) */
  334. return len;
  335. }
  336. /*
  337. * Calculate the length of buffer needed to hold the delete query
  338. */
  339. static unsigned int calc_delete_len(db_con_t* con, db_key_t* keys, int n)
  340. {
  341. int i;
  342. unsigned int len;
  343. len = sizeof(DELETE) - 1;
  344. len += strlen(CON_TABLE(con));
  345. if (n) {
  346. len += 1; /* _ */
  347. len += sizeof(WHERE) - 1;
  348. len += n * MAX_OPERATOR_LEN;
  349. len += (sizeof(AND) - 1) * (n - 1);
  350. for(i = 0; i < n; i++) {
  351. len += strlen(keys[i]);
  352. }
  353. len += calc_param_len(1, n);
  354. }
  355. return len;
  356. }
  357. static unsigned int calc_select_len(db_con_t* con, db_key_t* cols, db_key_t* keys, int n, int ncol, db_key_t order)
  358. {
  359. int i;
  360. unsigned int len;
  361. if (!cols) {
  362. len = sizeof(SELECTALL) - 1;
  363. } else {
  364. len = sizeof(SELECT);
  365. for(i = 0; i < ncol; i++) {
  366. len += strlen(cols[i]);
  367. }
  368. len += ncol - 1; /* , */
  369. len++; /* space */
  370. }
  371. len += sizeof(FROM) - 1;
  372. len += strlen(CON_TABLE(con));
  373. len += 1; /* _ */
  374. if (n) {
  375. len += sizeof(WHERE) - 1;
  376. len += n * MAX_OPERATOR_LEN;
  377. len += (sizeof(AND) - 1) * (n - 1);
  378. for(i = 0; i < n; i++) {
  379. len += strlen(keys[i]);
  380. }
  381. len += calc_param_len(1, n);
  382. len++; /* space */
  383. }
  384. if (order) {
  385. len += sizeof(ORDER);
  386. len += strlen(order);
  387. }
  388. return len;
  389. }
  390. static unsigned int calc_update_len(db_con_t* con, db_key_t* ukeys, db_key_t* keys, int un, int n)
  391. {
  392. int i;
  393. unsigned int len;
  394. if (!un) return 0;
  395. len = sizeof(UPDATE) - 1;
  396. len += strlen(CON_TABLE(con));
  397. len += 1; /* _ */
  398. len += sizeof(SET) - 1;
  399. len += un; /* = */
  400. for (i = 0; i < un; i++) {
  401. len += strlen(ukeys[i]);
  402. }
  403. len += calc_param_len(1, un);
  404. len += un; /* , and last space */
  405. if (n) {
  406. len += sizeof(WHERE) - 1;
  407. len += n * MAX_OPERATOR_LEN;
  408. len += (sizeof(AND) - 1) * (n - 1);
  409. for(i = 0; i < n; i++) {
  410. len += strlen(keys[i]);
  411. }
  412. len += calc_param_len(1 + un, n);
  413. }
  414. return len;
  415. }
  416. static char* print_insert(db_con_t* con, db_key_t* keys, int n)
  417. {
  418. unsigned int len;
  419. int i;
  420. char* s;
  421. str p;
  422. if (!n || !keys) {
  423. ERR("Nothing to insert\n");
  424. return 0;
  425. }
  426. len = calc_insert_len(con, keys, n);
  427. s = (char*)pkg_malloc(len + 1);
  428. if (!s) {
  429. ERR("Unable to allocate %d of memory\n", len);
  430. return 0;
  431. }
  432. p.s = s;
  433. p.len = len;
  434. append(p, INSERT);
  435. append_str(p, CON_TABLE(con));
  436. append(p, " (");
  437. append_str(p, keys[0]);
  438. for(i = 1; i < n; i++) {
  439. append(p, ",");
  440. append_str(p, keys[i]);
  441. }
  442. append(p, VALUES);
  443. append_param(p, 1);
  444. for(i = 1; i < n; i++) {
  445. append(p, ",");
  446. append_param(p, i + 1);
  447. }
  448. append(p, ")");
  449. *p.s = '\0';
  450. return s;
  451. shortbuf:
  452. ERR("Buffer too short (bug in postgres module)\n");
  453. pkg_free(s);
  454. return 0;
  455. }
  456. static char* print_select(db_con_t* con, db_key_t* cols, db_key_t* keys, db_val_t* vals,
  457. int n, int ncol, db_op_t* ops, db_key_t order)
  458. {
  459. unsigned int len;
  460. int i;
  461. char* s;
  462. str p;
  463. len = calc_select_len(con, cols, keys, n, ncol, order);
  464. s = (char*)pkg_malloc(len + 1);
  465. if (!s) {
  466. ERR("Unable to allocate %d of memory\n", len);
  467. return 0;
  468. }
  469. p.s = s;
  470. p.len = len;
  471. if (!cols || !ncol) {
  472. append(p, SELECTALL);
  473. } else {
  474. append(p, SELECT);
  475. append_str(p, cols[0]);
  476. for(i = 1; i < ncol; i++) {
  477. append(p, ",");
  478. append_str(p, cols[i]);
  479. }
  480. append(p, " ");
  481. }
  482. append(p, FROM);
  483. append_str(p, CON_TABLE(con));
  484. append(p, " ");
  485. if (n) {
  486. append(p, WHERE);
  487. append_str(p, keys[0]);
  488. if (vals[0].nul) {
  489. append(p, " is NULL");
  490. } else {
  491. if (ops) {
  492. append_str(p, *ops);
  493. ops++;
  494. } else {
  495. append(p, "=");
  496. }
  497. append_param(p, 1);
  498. }
  499. for(i = 1; i < n; i++) {
  500. append(p, AND);
  501. append_str(p, keys[i]);
  502. if (vals[i].nul) {
  503. append(p, " is NULL");
  504. } else {
  505. if (ops) {
  506. append_str(p, *ops);
  507. ops++;
  508. } else {
  509. append(p, "=");
  510. }
  511. append_param(p, i + 1);
  512. }
  513. }
  514. append(p, " ");
  515. }
  516. if (order) {
  517. append(p, ORDER);
  518. append_str(p, order);
  519. }
  520. *p.s = '\0'; /* Zero termination */
  521. return s;
  522. shortbuf:
  523. ERR("Buffer too short (bug in postgres module)\n");
  524. pkg_free(s);
  525. return 0;
  526. }
  527. static char* print_delete(db_con_t* con, db_key_t* keys, db_op_t* ops, db_val_t* vals, int n)
  528. {
  529. unsigned int len;
  530. int i;
  531. char* s;
  532. str p;
  533. len = calc_delete_len(con, keys, n);
  534. s = (char*)pkg_malloc(len + 1);
  535. if (!s) {
  536. ERR("Unable to allocate %d of memory\n", len);
  537. return 0;
  538. }
  539. p.s = s;
  540. p.len = len;
  541. append(p, DELETE);
  542. append_str(p, CON_TABLE(con));
  543. append(p, " ");
  544. if (n) {
  545. append(p, WHERE);
  546. append_str(p, keys[0]);
  547. if (vals[0].nul) {
  548. append(p, " is NULL");
  549. } else {
  550. if (ops) {
  551. append_str(p, *ops);
  552. ops++;
  553. } else {
  554. append(p, "=");
  555. }
  556. append_param(p, 1);
  557. }
  558. for(i = 1; i < n; i++) {
  559. append(p, AND);
  560. append_str(p, keys[i]);
  561. if (vals[i].nul) {
  562. append(p, " is NULL");
  563. } else {
  564. if (ops) {
  565. append_str(p, *ops);
  566. ops++;
  567. } else {
  568. append(p, "=");
  569. }
  570. append_param(p, i + 1);
  571. }
  572. }
  573. }
  574. *p.s = '\0';
  575. return s;
  576. shortbuf:
  577. ERR("Buffer too short (bug in postgres module)\n");
  578. pkg_free(s);
  579. return 0;
  580. }
  581. static char* print_update(db_con_t* con, db_key_t* ukeys, db_key_t* keys, db_op_t* ops,
  582. db_val_t* vals, int un, int n)
  583. {
  584. unsigned int len, param_no;
  585. char* s;
  586. int i;
  587. str p;
  588. if (!un) {
  589. ERR("Nothing to update\n");
  590. return 0;
  591. }
  592. param_no = 1;
  593. len = calc_update_len(con, ukeys, keys, un, n);
  594. s = (char*)pkg_malloc(len + 1);
  595. if (!s) {
  596. ERR("Unable to allocate %d of memory\n", len);
  597. return 0;
  598. }
  599. p.s = s;
  600. p.len = len;
  601. append(p, UPDATE);
  602. append_str(p, CON_TABLE(con));
  603. append(p, " " SET);
  604. append_str(p, ukeys[0]);
  605. append(p, "=");
  606. append_param(p, param_no++);
  607. for(i = 1; i < un; i++) {
  608. append(p, ",");
  609. append_str(p, ukeys[i]);
  610. append(p, "=");
  611. append_param(p, param_no++);
  612. }
  613. append(p, " ");
  614. if (n) {
  615. append(p, WHERE);
  616. append_str(p, keys[0]);
  617. if (vals[0].nul) {
  618. append(p, " is NULL");
  619. } else {
  620. if (ops) {
  621. append_str(p, *ops);
  622. ops++;
  623. } else {
  624. append(p, "=");
  625. }
  626. append_param(p, param_no++);
  627. }
  628. for(i = 1; i < n; i++) {
  629. append(p, AND);
  630. append_str(p, keys[i]);
  631. if (vals[i].nul) {
  632. append(p, " is NULL");
  633. } else {
  634. if (ops) {
  635. append_str(p, *ops);
  636. ops++;
  637. } else {
  638. append(p, "=");
  639. }
  640. append_param(p, param_no++);
  641. }
  642. }
  643. }
  644. *p.s = '\0';
  645. return s;
  646. shortbuf:
  647. ERR("Buffer too short (bug in postgres module)\n");
  648. pkg_free(s);
  649. return 0;
  650. }
  651. /*
  652. * Return values: 1 Query failed, bad connection
  653. * 0 Query succeeded
  654. * -1 Query failed due to some other reason
  655. */
  656. static int submit_query(db_res_t** res, db_con_t* con, const char* query, struct pg_params* params)
  657. {
  658. PGresult* pgres;
  659. DBG("Executing '%s'\n", query);
  660. if (params && params->cur) {
  661. pgres = PQexecParams(CON_CONNECTION(con), query,
  662. params->cur, params->types,
  663. params->data, params->len,
  664. params->formats, 1);
  665. } else {
  666. pgres = PQexecParams(CON_CONNECTION(con), query, 0, 0, 0, 0, 0, 1);
  667. }
  668. switch(PQresultStatus(pgres)) {
  669. case PGRES_EMPTY_QUERY:
  670. ERR("BUG: db_raw_query received an empty query\n");
  671. goto error;
  672. case PGRES_COMMAND_OK:
  673. case PGRES_NONFATAL_ERROR:
  674. case PGRES_TUPLES_OK:
  675. /* Success */
  676. break;
  677. case PGRES_COPY_OUT:
  678. case PGRES_COPY_IN:
  679. ERR("Unsupported transfer mode\n");
  680. goto error;
  681. case PGRES_BAD_RESPONSE:
  682. case PGRES_FATAL_ERROR:
  683. ERR("Error: %s", PQresultErrorMessage(pgres));
  684. if (PQstatus(CON_CONNECTION(con)) != CONNECTION_BAD) {
  685. goto error;
  686. }
  687. ERR("Bad connection\n");
  688. PQclear(pgres);
  689. return 1;
  690. }
  691. if (res) {
  692. *res = pg_new_result(pgres);
  693. if (!(*res)) goto error;
  694. } else {
  695. PQclear(pgres);
  696. }
  697. return 0;
  698. error:
  699. PQclear(pgres);
  700. return -1;
  701. }
  702. static int reconnect(db_con_t* con)
  703. {
  704. int attempts_left = reconnect_attempts;
  705. while(attempts_left) {
  706. ERR("Trying to recover the connection\n");
  707. PQreset(CON_CONNECTION(con));
  708. if (PQstatus(CON_CONNECTION(con)) == CONNECTION_OK) {
  709. ERR("Successfuly reconnected\n");
  710. return 0;
  711. }
  712. ERR("Reconnect attempt failed\n");
  713. attempts_left--;
  714. }
  715. ERR("No more reconnect attempts left, giving up\n");
  716. return -1;
  717. }
  718. /*
  719. * Query table for specified rows
  720. * con: structure representing database connection
  721. * keys: key names
  722. * ops: operators
  723. * vals: values of the keys that must match
  724. * cols: column names to return
  725. * n: number of key=values pairs to compare
  726. * ncol: number of columns to return
  727. * order: order by the specified column
  728. * res: query result
  729. */
  730. int pg_query(db_con_t* con, db_key_t* keys, db_op_t* ops,
  731. db_val_t* vals, db_key_t* cols, int n, int ncols,
  732. db_key_t order, db_res_t** res)
  733. {
  734. int ret;
  735. char* select;
  736. struct pg_params* params;
  737. params = 0;
  738. select = 0;
  739. if (res) *res = 0;
  740. if (!con) {
  741. ERR("Invalid parameter value\n");
  742. return -1;
  743. }
  744. select = print_select(con, cols, keys, vals, n, ncols, ops, order);
  745. if (!select) goto err;
  746. params = new_pg_params(n);
  747. if (!params) goto err;
  748. if (params_add(params, con, vals, n, 1) < 0) goto err;
  749. do {
  750. ret = submit_query(res, con, select, params);
  751. if (ret < 0) goto err; /* Unknown error, bail out */
  752. if (ret > 0) { /* Disconnected, try to reconnect */
  753. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  754. else continue; /* Try one more time (ret is > 0) */
  755. }
  756. } while(ret != 0);
  757. if (res && pg_convert_result(*res, con) < 0) {
  758. pg_free_result(*res);
  759. goto err;
  760. }
  761. free_pg_params(params);
  762. pkg_free(select);
  763. return 0;
  764. err:
  765. if (params) free_pg_params(params);
  766. if (select) pkg_free(select);
  767. return -1;
  768. }
  769. /*
  770. * Execute a raw SQL query
  771. */
  772. int pg_raw_query(db_con_t* con, char* query, db_res_t** res)
  773. {
  774. int ret;
  775. if (!con || !query) {
  776. ERR("Invalid parameter value\n");
  777. return -1;
  778. }
  779. do {
  780. ret = submit_query(res, con, query, 0);
  781. if (ret < 0) return -1; /* Unknown error, bail out */
  782. if (ret > 0) { /* Disconnected, try to reconnect */
  783. if (reconnect(con) < 0) return -1; /* Failed to reconnect */
  784. else continue; /* Try one more time (ret is > 0) */
  785. }
  786. } while(ret != 0);
  787. if (res && (pg_convert_result(*res, con) < 0)) {
  788. pg_free_result(*res);
  789. return -1;
  790. }
  791. return 0;
  792. }
  793. /*
  794. * Insert a row into specified table
  795. * con: structure representing database connection
  796. * keys: key names
  797. * vals: values of the keys
  798. * n: number of key=value pairs
  799. */
  800. int pg_insert(db_con_t* con, db_key_t* keys, db_val_t* vals, int n)
  801. {
  802. int ret;
  803. char* insert;
  804. struct pg_params* params;
  805. if (!con || !keys || !vals || !n) {
  806. ERR("Invalid parameter value\n");
  807. return -1;
  808. }
  809. params = 0;
  810. insert = 0;
  811. insert = print_insert(con, keys, n);
  812. if (!insert) goto err;
  813. params = new_pg_params(n);
  814. if (!params) goto err;
  815. if (params_add(params, con, vals, n, 0) < 0) goto err;
  816. do {
  817. ret = submit_query(0, con, insert, params);
  818. if (ret < 0) goto err; /* Unknown error, bail out */
  819. if (ret > 0) { /* Disconnected, try to reconnect */
  820. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  821. else continue; /* Try one more time (ret is > 0) */
  822. }
  823. } while(ret != 0);
  824. free_pg_params(params);
  825. pkg_free(insert);
  826. return 0;
  827. err:
  828. if (params) free_pg_params(params);
  829. if (insert) pkg_free(insert);
  830. return -1;
  831. }
  832. /*
  833. * Delete a row from the specified table
  834. * con : structure representing database connection
  835. * keys: key names
  836. * ops : operators
  837. * vals: values of the keys that must match
  838. * n : number of key=value pairs
  839. */
  840. int pg_delete(db_con_t* con, db_key_t* keys, db_op_t* ops, db_val_t* vals, int n)
  841. {
  842. int ret;
  843. char* delete;
  844. struct pg_params* params;
  845. if (!con) {
  846. ERR("Invalid parameter value\n");
  847. return -1;
  848. }
  849. params = 0;
  850. delete = 0;
  851. delete = print_delete(con, keys, ops, vals, n);
  852. if (!delete) goto err;
  853. params = new_pg_params(n);
  854. if (!params) goto err;
  855. if (params_add(params, con, vals, n, 1) < 0) goto err;
  856. do {
  857. ret = submit_query(0, con, delete, params);
  858. if (ret < 0) goto err; /* Unknown error, bail out */
  859. if (ret > 0) { /* Disconnected, try to reconnect */
  860. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  861. else continue; /* Try one more time (ret is > 0) */
  862. }
  863. } while(ret != 0);
  864. free_pg_params(params);
  865. pkg_free(delete);
  866. return 0;
  867. err:
  868. if (params) free_pg_params(params);
  869. if (delete) pkg_free(delete);
  870. return -1;
  871. }
  872. /*
  873. * Update some rows in the specified table
  874. * con : structure representing database connection
  875. * keys : key names
  876. * ops : operators
  877. * vals : values of the keys that must match
  878. * ucols: updated columns
  879. * uvals: updated values of the columns
  880. * n : number of key=value pairs
  881. * un : number of columns to update
  882. */
  883. int pg_update(db_con_t* con, db_key_t* keys, db_op_t* ops, db_val_t* vals,
  884. db_key_t* ucols, db_val_t* uvals, int n, int un)
  885. {
  886. int ret;
  887. char* update;
  888. struct pg_params* params;
  889. if (!con || !ucols || !uvals || !un) {
  890. ERR("Invalid parameter value\n");
  891. return -1;
  892. }
  893. params = 0;
  894. update = 0;
  895. update = print_update(con, ucols, keys, ops, vals, un, n);
  896. if (!update) goto err;
  897. params = new_pg_params(n + un);
  898. if (!params) goto err;
  899. if (params_add(params, con, uvals, un, 0) < 0) goto err;
  900. if (params_add(params, con, vals, n, 1) < 0) goto err;
  901. do {
  902. ret = submit_query(0, con, update, params);
  903. if (ret < 0) goto err; /* Unknown error, bail out */
  904. if (ret > 0) { /* Disconnected, try to reconnect */
  905. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  906. else continue; /* Try one more time (ret is > 0) */
  907. }
  908. } while(ret != 0);
  909. free_pg_params(params);
  910. pkg_free(update);
  911. return 0;
  912. err:
  913. if (params) free_pg_params(params);
  914. if (update) pkg_free(update);
  915. return -1;
  916. }
  917. /*
  918. * Release a result set from memory
  919. */
  920. int pg_db_free_result(db_con_t* con, db_res_t* res)
  921. {
  922. pg_free_result(res);
  923. return 0;
  924. }