dbase.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. * $Id$
  3. *
  4. * UNIXODBC module core functions
  5. *
  6. * Copyright (C) 2005-2006 Marco Lorrai
  7. * Copyright (C) 2007-2008 1&1 Internet AG
  8. *
  9. * This file is part of Kamailio, a free SIP server.
  10. *
  11. * Kamailio is free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 2 of the License, or
  14. * (at your option) any later version
  15. *
  16. * Kamailio is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. *
  25. *
  26. * History:
  27. * --------
  28. * 2005-12-01 initial commit (chgen)
  29. * 2006-04-03 fixed invalid handle to extract error (sgupta)
  30. * 2006-04-04 removed deprecated ODBC functions, closed cursors on error
  31. * (sgupta)
  32. * 2006-05-05 Fixed reconnect code to actually work on connection loss
  33. * (sgupta)
  34. */
  35. #include "../../mem/mem.h"
  36. #include "../../dprint.h"
  37. #include "../../lib/srdb1/db_query.h"
  38. #include "val.h"
  39. #include "connection.h"
  40. #include "row.h"
  41. #include "res.h"
  42. #include "list.h"
  43. #include "db_unixodbc.h"
  44. #include "dbase.h"
  45. /*
  46. * Reconnect if connection is broken
  47. */
  48. static int reconnect(const db1_con_t* _h)
  49. {
  50. int ret = 0;
  51. SQLCHAR outstr[1024];
  52. SQLSMALLINT outstrlen;
  53. char conn_str[MAX_CONN_STR_LEN];
  54. LM_ERR("Attempting DB reconnect\n");
  55. /* Disconnect */
  56. SQLDisconnect (CON_CONNECTION(_h));
  57. /* Reconnect */
  58. if (!db_unixodbc_build_conn_str(CON_ID(_h), conn_str)) {
  59. LM_ERR("failed to build connection string\n");
  60. return ret;
  61. }
  62. ret = SQLDriverConnect(CON_CONNECTION(_h), (void *)1,
  63. (SQLCHAR*)conn_str, SQL_NTS, outstr, sizeof(outstr),
  64. &outstrlen, SQL_DRIVER_COMPLETE);
  65. if (!SQL_SUCCEEDED(ret)) {
  66. LM_ERR("failed to connect\n");
  67. db_unixodbc_extract_error("SQLDriverConnect", CON_CONNECTION(_h),
  68. SQL_HANDLE_DBC, NULL);
  69. return ret;
  70. }
  71. ret = SQLAllocHandle(SQL_HANDLE_STMT, CON_CONNECTION(_h),
  72. &CON_RESULT(_h));
  73. if (!SQL_SUCCEEDED(ret)) {
  74. LM_ERR("Statement allocation error %d\n", (int)(long)CON_CONNECTION(_h));
  75. db_unixodbc_extract_error("SQLAllocStmt", CON_CONNECTION(_h), SQL_HANDLE_DBC,NULL);
  76. return ret;
  77. }
  78. return ret;
  79. }
  80. /*
  81. * Send an SQL query to the server
  82. */
  83. static int db_unixodbc_submit_query(const db1_con_t* _h, const str* _s)
  84. {
  85. int ret = 0;
  86. SQLCHAR sqlstate[7];
  87. if (!_h || !_s || !_s->s) {
  88. LM_ERR("invalid parameter value\n");
  89. return -1;
  90. }
  91. /* first do some cleanup if required */
  92. if(CON_RESULT(_h))
  93. {
  94. SQLCloseCursor(CON_RESULT(_h));
  95. SQLFreeHandle(SQL_HANDLE_STMT, CON_RESULT(_h));
  96. }
  97. ret = SQLAllocHandle(SQL_HANDLE_STMT, CON_CONNECTION(_h), &CON_RESULT(_h));
  98. if (!SQL_SUCCEEDED(ret))
  99. {
  100. LM_ERR("statement allocation error %d\n",
  101. (int)(long)CON_CONNECTION(_h));
  102. db_unixodbc_extract_error("SQLAllocStmt", CON_CONNECTION(_h), SQL_HANDLE_DBC,
  103. (char*)sqlstate);
  104. /* Connection broken */
  105. if( !strncmp((char*)sqlstate,"08003",5) ||
  106. !strncmp((char*)sqlstate,"08S01",5) ) {
  107. ret = reconnect(_h);
  108. if( !SQL_SUCCEEDED(ret) ) return ret;
  109. } else {
  110. return ret;
  111. }
  112. }
  113. ret=SQLExecDirect(CON_RESULT(_h), (SQLCHAR*)_s->s, _s->len);
  114. if (!SQL_SUCCEEDED(ret))
  115. {
  116. SQLCHAR sqlstate[7];
  117. LM_ERR("rv=%d. Query= %.*s\n", ret, _s->len, _s->s);
  118. db_unixodbc_extract_error("SQLExecDirect", CON_RESULT(_h), SQL_HANDLE_STMT,
  119. (char*)sqlstate);
  120. /* Connection broken */
  121. if( !strncmp((char*)sqlstate,"08003",5) ||
  122. !strncmp((char*)sqlstate,"08S01",5)
  123. )
  124. {
  125. ret = reconnect(_h);
  126. if( SQL_SUCCEEDED(ret) ) {
  127. /* Try again */
  128. ret=SQLExecDirect(CON_RESULT(_h), (SQLCHAR*)_s->s, _s->len);
  129. if (!SQL_SUCCEEDED(ret)) {
  130. LM_ERR("rv=%d. Query= %.*s\n", ret, _s->len, _s->s);
  131. db_unixodbc_extract_error("SQLExecDirect", CON_RESULT(_h),
  132. SQL_HANDLE_STMT, (char*)sqlstate);
  133. /* Close the cursor */
  134. SQLCloseCursor(CON_RESULT(_h));
  135. SQLFreeHandle(SQL_HANDLE_STMT, CON_RESULT(_h));
  136. }
  137. }
  138. }
  139. else {
  140. /* Close the cursor */
  141. SQLCloseCursor(CON_RESULT(_h));
  142. SQLFreeHandle(SQL_HANDLE_STMT, CON_RESULT(_h));
  143. }
  144. }
  145. return ret;
  146. }
  147. /*
  148. * Initialize database module
  149. * No function should be called before this
  150. */
  151. db1_con_t* db_unixodbc_init(const str* _url)
  152. {
  153. return db_do_init(_url, (void*)db_unixodbc_new_connection);
  154. }
  155. /*
  156. * Shut down database module
  157. * No function should be called after this
  158. */
  159. void db_unixodbc_close(db1_con_t* _h)
  160. {
  161. return db_do_close(_h, db_unixodbc_free_connection);
  162. }
  163. /*
  164. * Retrieve result set
  165. */
  166. static int db_unixodbc_store_result(const db1_con_t* _h, db1_res_t** _r)
  167. {
  168. if ((!_h) || (!_r))
  169. {
  170. LM_ERR("invalid parameter value\n");
  171. return -1;
  172. }
  173. *_r = db_new_result();
  174. if (*_r == 0)
  175. {
  176. LM_ERR("no memory left\n");
  177. return -2;
  178. }
  179. if (db_unixodbc_convert_result(_h, *_r) < 0)
  180. {
  181. LM_ERR("failed to convert result\n");
  182. LM_DBG("freeing result set at %p\n", _r);
  183. pkg_free(*_r);
  184. *_r = 0;
  185. return -4;
  186. }
  187. return 0;
  188. }
  189. /*
  190. * Release a result set from memory
  191. */
  192. int db_unixodbc_free_result(db1_con_t* _h, db1_res_t* _r)
  193. {
  194. if ((!_h) || (!_r))
  195. {
  196. LM_ERR("invalid parameter value\n");
  197. return -1;
  198. }
  199. if (db_free_result(_r) < 0)
  200. {
  201. LM_ERR("failed to free result structure\n");
  202. return -1;
  203. }
  204. SQLFreeHandle(SQL_HANDLE_STMT, CON_RESULT(_h));
  205. CON_RESULT(_h) = 0;
  206. return 0;
  207. }
  208. /*
  209. * Query table for specified rows
  210. * _h: structure representing database connection
  211. * _k: key names
  212. * _op: operators
  213. * _v: values of the keys that must match
  214. * _c: column names to return
  215. * _n: number of key=values pairs to compare
  216. * _nc: number of columns to return
  217. * _o: order by the specified column
  218. */
  219. int db_unixodbc_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  220. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  221. const db_key_t _o, db1_res_t** _r)
  222. {
  223. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r,
  224. db_unixodbc_val2str, db_unixodbc_submit_query, db_unixodbc_store_result);
  225. }
  226. /*!
  227. * \brief Gets a partial result set, fetch rows from a result
  228. *
  229. * Gets a partial result set, fetch a number of rows from a databae result.
  230. * This function initialize the given result structure on the first run, and
  231. * fetches the nrows number of rows. On subsequenting runs, it uses the
  232. * existing result and fetches more rows, until it reaches the end of the
  233. * result set. Because of this the result needs to be null in the first
  234. * invocation of the function. If the number of wanted rows is zero, the
  235. * function returns anything with a result of zero.
  236. * \param _h structure representing the database connection
  237. * \param _r pointer to a structure representing the result
  238. * \param nrows number of fetched rows
  239. * \return return zero on success, negative value on failure
  240. */
  241. int db_unixodbc_fetch_result(const db1_con_t* _h, db1_res_t** _r, const int nrows)
  242. {
  243. int row_n = 0, i = 0, ret = 0, len;
  244. SQLSMALLINT columns;
  245. list* rows = NULL;
  246. list* rowstart = NULL;
  247. strn* temp_row = NULL;
  248. if ((!_h) || (!_r) || nrows < 0)
  249. {
  250. LM_ERR("invalid parameter value\n");
  251. return -1;
  252. }
  253. /* exit if the fetch count is zero */
  254. if (nrows == 0) {
  255. if (*_r)
  256. db_free_result(*_r);
  257. *_r = 0;
  258. return 0;
  259. }
  260. /* On the first fetch for a query, allocate structures and get columns */
  261. if(*_r == NULL) {
  262. /* Allocate a new result structure */
  263. *_r = db_new_result();
  264. LM_DBG("just allocated a new db result structure");
  265. if (*_r == NULL) {
  266. LM_ERR("no memory left\n");
  267. return -2;
  268. }
  269. /* Get columns names and count */
  270. if (db_unixodbc_get_columns(_h, *_r) < 0) {
  271. LM_ERR("getting column names failed\n");
  272. db_free_columns(*_r);
  273. return -2;
  274. }
  275. /* On subsequent fetch attempts, reuse already allocated structures */
  276. } else {
  277. LM_DBG("db result structure already exist, reusing\n");
  278. /* free old rows */
  279. if(RES_ROWS(*_r) != NULL)
  280. db_free_rows(*_r);
  281. RES_ROWS(*_r) = 0;
  282. RES_ROW_N(*_r) = 0;
  283. }
  284. SQLNumResultCols(CON_RESULT(_h), (SQLSMALLINT *)&columns);
  285. /* Now fetch nrows at most */
  286. len = sizeof(db_row_t) * nrows;
  287. RES_ROWS(*_r) = (struct db_row*)pkg_malloc(len);
  288. if (!RES_ROWS(*_r)) {
  289. LM_ERR("no memory left\n");
  290. return -5;
  291. }
  292. LM_DBG("allocated %d bytes for RES_ROWS at %p\n", len, RES_ROWS(*_r));
  293. LM_DBG("Now fetching %i rows at most\n", nrows);
  294. while(SQL_SUCCEEDED(ret = SQLFetch(CON_RESULT(_h)))) {
  295. /* Allocate a temporary row */
  296. temp_row = db_unixodbc_new_cellrow(columns);
  297. if (!temp_row) {
  298. LM_ERR("no private memory left\n");
  299. pkg_free(RES_ROWS(*_r));
  300. pkg_free(*_r);
  301. *_r = 0;
  302. return -1;
  303. }
  304. LM_DBG("fetching %d columns for row %d...\n",columns, row_n);
  305. for(i=0; i < columns; i++) {
  306. LM_DBG("fetching column %d\n",i);
  307. if (!db_unixodbc_load_cell(_h, i+1, temp_row + i, RES_TYPES(*_r)[i])) {
  308. pkg_free(RES_ROWS(*_r));
  309. db_unixodbc_free_cellrow(columns, temp_row);
  310. pkg_free(*_r);
  311. *_r = 0;
  312. return -5;
  313. }
  314. }
  315. LM_DBG("got temp_row at %p\n", temp_row);
  316. if (db_unixodbc_list_insert(&rowstart, &rows, columns, temp_row) < 0) {
  317. LM_ERR("SQL result row insert failed\n");
  318. pkg_free(RES_ROWS(*_r));
  319. db_unixodbc_free_cellrow(columns, temp_row);
  320. pkg_free(*_r);
  321. *_r = 0;
  322. return -5;
  323. }
  324. /* Free temporary row data */
  325. LM_DBG("freeing temp_row at %p\n", temp_row);
  326. db_unixodbc_free_cellrow(columns, temp_row);
  327. temp_row = NULL;
  328. row_n++;
  329. if (row_n == nrows) {
  330. break;
  331. }
  332. }
  333. CON_ROW(_h) = NULL;
  334. RES_ROW_N(*_r) = row_n;
  335. if (!row_n) {
  336. LM_DBG("no more rows to process for db fetch");
  337. pkg_free(RES_ROWS(*_r));
  338. RES_ROWS(*_r) = 0;
  339. return 0;
  340. }
  341. /* Convert rows to internal format */
  342. memset(RES_ROWS(*_r), 0, len);
  343. i = 0;
  344. rows = rowstart;
  345. while(rows)
  346. {
  347. LM_DBG("converting row #%d\n", i);
  348. CON_ROW(_h) = rows->data;
  349. if (!CON_ROW(_h))
  350. {
  351. LM_ERR("string null\n");
  352. RES_ROW_N(*_r) = row_n;
  353. db_free_rows(*_r);
  354. return -3;
  355. }
  356. if (db_unixodbc_convert_row(_h, *_r, &(RES_ROWS(*_r)[i]), rows->lengths) < 0) {
  357. LM_ERR("converting fetched row #%d failed\n", i);
  358. RES_ROW_N(*_r) = i;
  359. db_free_rows(*_r);
  360. return -4;
  361. }
  362. i++;
  363. rows = rows->next;
  364. }
  365. db_unixodbc_list_destroy(rowstart);
  366. /* update the total number of rows processed */
  367. RES_LAST_ROW(*_r) += row_n;
  368. LM_DBG("fetch from db processed %d rows so far\n", RES_LAST_ROW(*_r));
  369. return 0;
  370. }
  371. /*
  372. * Execute a raw SQL query
  373. */
  374. int db_unixodbc_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  375. {
  376. return db_do_raw_query(_h, _s, _r, db_unixodbc_submit_query,
  377. db_unixodbc_store_result);
  378. }
  379. /*
  380. * Insert a row into specified table
  381. * _h: structure representing database connection
  382. * _k: key names
  383. * _v: values of the keys
  384. * _n: number of key=value pairs
  385. */
  386. int db_unixodbc_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v, const int _n)
  387. {
  388. return db_do_insert(_h, _k, _v, _n, db_unixodbc_val2str,
  389. db_unixodbc_submit_query);
  390. }
  391. /*
  392. * Delete a row from the specified table
  393. * _h: structure representing database connection
  394. * _k: key names
  395. * _o: operators
  396. * _v: values of the keys that must match
  397. * _n: number of key=value pairs
  398. */
  399. int db_unixodbc_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  400. const db_val_t* _v, const int _n)
  401. {
  402. return db_do_delete(_h, _k, _o, _v, _n, db_unixodbc_val2str,
  403. db_unixodbc_submit_query);
  404. }
  405. /*
  406. * Update some rows in the specified table
  407. * _h: structure representing database connection
  408. * _k: key names
  409. * _o: operators
  410. * _v: values of the keys that must match
  411. * _uk: updated columns
  412. * _uv: updated values of the columns
  413. * _n: number of key=value pairs
  414. * _un: number of columns to update
  415. */
  416. int db_unixodbc_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  417. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n, const int _un)
  418. {
  419. return db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_unixodbc_val2str,
  420. db_unixodbc_submit_query);
  421. }
  422. /*
  423. * Just like insert, but replace the row if it exists
  424. */
  425. int db_unixodbc_replace(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v, const int _n,
  426. const int _un, const int _m)
  427. {
  428. return db_do_replace(_h, _k, _v, _n, db_unixodbc_val2str,
  429. db_unixodbc_submit_query);
  430. }
  431. /*
  432. * Store name of table that will be used by
  433. * subsequent database functions
  434. */
  435. int db_unixodbc_use_table(db1_con_t* _h, const str* _t)
  436. {
  437. return db_use_table(_h, _t);
  438. }