dbhelper.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2020-03-06 lizhen9880 first version
  9. */
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <rtthread.h>
  13. #include <ctype.h>
  14. #include "dbhelper.h"
  15. #define DBG_ENABLE
  16. #define DBG_SECTION_NAME "app.dbhelper"
  17. #define DBG_LEVEL DBG_INFO
  18. #define DBG_COLOR
  19. #include <rtdbg.h>
  20. #if PKG_SQLITE_DB_NAME_MAX_LEN < 8
  21. #error "the database name length is too short"
  22. #endif
  23. #define DEFAULT_DB_NAME "/rt.db"
  24. static rt_mutex_t db_mutex_lock = RT_NULL;
  25. static char db_name[PKG_SQLITE_DB_NAME_MAX_LEN + 1] = DEFAULT_DB_NAME;
  26. /**
  27. * This function will initialize SQLite3 create a mutex as a lock.
  28. */
  29. int db_helper_init(void)
  30. {
  31. sqlite3_initialize();
  32. if (db_mutex_lock == RT_NULL)
  33. {
  34. db_mutex_lock = rt_mutex_create("dbmtx", RT_IPC_FLAG_FIFO);
  35. }
  36. if (db_mutex_lock == RT_NULL)
  37. {
  38. LOG_E("rt_mutex_create dbmtx failed!\n");
  39. return -RT_ERROR;
  40. }
  41. return RT_EOK;
  42. }
  43. INIT_APP_EXPORT(db_helper_init);
  44. /**
  45. * This function will create a database.
  46. *
  47. * @param sqlstr should be a SQL CREATE TABLE statements.
  48. * @return the result of sql execution.
  49. */
  50. int db_create_database(const char *sqlstr)
  51. {
  52. return db_nonquery_operator(sqlstr, 0, 0);
  53. }
  54. static int db_bind_by_var(sqlite3_stmt *stmt, const char *fmt, va_list args)
  55. {
  56. int len, npara = 1;
  57. int ret = SQLITE_OK;
  58. if (fmt == NULL)
  59. {
  60. return ret;
  61. }
  62. for (; *fmt; ++fmt)
  63. {
  64. if (*fmt != '%')
  65. {
  66. continue;
  67. }
  68. ++fmt;
  69. /* get length */
  70. len = 0;
  71. while (isdigit(*fmt))
  72. {
  73. len = len * 10 + (*fmt - '0');
  74. ++fmt;
  75. }
  76. switch (*fmt)
  77. {
  78. case 'd':
  79. ret = sqlite3_bind_int(stmt, npara, va_arg(args, int));
  80. break;
  81. case 'f':
  82. ret = sqlite3_bind_double(stmt, npara, va_arg(args, double));
  83. break;
  84. case 's':
  85. {
  86. char *str = va_arg(args, char *);
  87. ret = sqlite3_bind_text(stmt, npara, str, strlen(str), NULL);
  88. }
  89. break;
  90. case 'x':
  91. {
  92. char *pdata;
  93. pdata = va_arg(args, char *);
  94. ret = sqlite3_bind_blob(stmt, npara, pdata, len, NULL);
  95. }
  96. break;
  97. default:
  98. ret = SQLITE_ERROR;
  99. break;
  100. }
  101. ++npara;
  102. if (ret)
  103. return ret;
  104. }
  105. return ret;
  106. }
  107. /**
  108. * This function will be used for the SELECT operating.The additional arguments
  109. * following format are formatted and inserted in the resulting string replacing
  110. * their respective specifiers.
  111. *
  112. * @param sql the SQL statements.
  113. * @param create the callback function supported by user.
  114. * create@param stmt the SQL statement after preparing.
  115. * create@param arg the input parameter from 'db_query_by_varpara' arg.
  116. * create@return rule:SQLITE_OK:success,others:fail
  117. * @param arg the parameter for the callback "create".
  118. * @param fmt the args format.such as %s string,%d int.
  119. * @param ... the additional arguments
  120. * @return =SQLITE_OK:success, others:fail.
  121. */
  122. int db_query_by_varpara(const char *sql, int (*create)(sqlite3_stmt *stmt, void *arg), void *arg, const char *fmt, ...)
  123. {
  124. sqlite3 *db = NULL;
  125. sqlite3_stmt *stmt = NULL;
  126. if (sql == NULL)
  127. {
  128. return SQLITE_ERROR;
  129. }
  130. rt_mutex_take(db_mutex_lock, RT_WAITING_FOREVER);
  131. int rc = sqlite3_open(db_name, &db);
  132. if (rc != SQLITE_OK)
  133. {
  134. LOG_E("open database failed,rc=%d", rc);
  135. rt_mutex_release(db_mutex_lock);
  136. return rc;
  137. }
  138. rc = sqlite3_prepare(db, sql, -1, &stmt, NULL);
  139. if (rc != SQLITE_OK)
  140. {
  141. LOG_E("database prepare fail,rc=%d", rc);
  142. goto __db_exec_fail;
  143. }
  144. if (fmt)
  145. {
  146. va_list args;
  147. va_start(args, fmt);
  148. rc = db_bind_by_var(stmt, fmt, args);
  149. va_end(args);
  150. if (rc)
  151. {
  152. LOG_E("database bind fail,rc=%d", rc);
  153. goto __db_exec_fail;
  154. }
  155. }
  156. if (create)
  157. {
  158. rc = (*create)(stmt, arg);
  159. }
  160. else
  161. {
  162. rc = (sqlite3_step(stmt), 0);
  163. }
  164. sqlite3_finalize(stmt);
  165. goto __db_exec_ok;
  166. __db_exec_fail:
  167. LOG_E("db operator failed,rc=%d", rc);
  168. __db_exec_ok:
  169. sqlite3_close(db);
  170. rt_mutex_release(db_mutex_lock);
  171. return rc;
  172. }
  173. /**
  174. * This function will be used for the operating that is not SELECT.It support executing multiple
  175. * SQL statements.
  176. *
  177. * @param sqlstr the SQL statements strings.if there are more than one
  178. * statements in the sqlstr to execute,separate them by a semicolon(;).
  179. * @param bind the callback function supported by user.bind data and call the sqlite3_step function.
  180. * bind@param stmt the SQL statement after preparing.
  181. * bind@param index the index of SQL statements strings.
  182. * bind@param param the parameter from 'db_nonquery_operator' arg.
  183. * bind@return SQLITE_OK or SQLITE_DONE:success,others:fail
  184. * @param param the parameter for the callback "bind".
  185. * @return =SQLITE_OK:success, others:fail.
  186. */
  187. int db_nonquery_operator(const char *sqlstr, int (*bind)(sqlite3_stmt *stmt, int index, void *param), void *param)
  188. {
  189. sqlite3 *db = NULL;
  190. sqlite3_stmt *stmt = NULL;
  191. int index = 0, offset = 0, n = 0;
  192. if (sqlstr == NULL)
  193. {
  194. return SQLITE_ERROR;
  195. }
  196. rt_mutex_take(db_mutex_lock, RT_WAITING_FOREVER);
  197. int rc = sqlite3_open(db_name, &db);
  198. if (rc != SQLITE_OK)
  199. {
  200. LOG_E("open database failed,rc=%d", rc);
  201. rt_mutex_release(db_mutex_lock);
  202. return rc;
  203. }
  204. rc = sqlite3_exec(db, "begin transaction", 0, 0, NULL);
  205. if (rc != SQLITE_OK)
  206. {
  207. LOG_E("begin transaction:ret=%d", rc);
  208. goto __db_begin_fail;
  209. }
  210. char sql[DB_SQL_MAX_LEN];
  211. while (sqlstr[index] != 0)
  212. {
  213. offset = 0;
  214. do
  215. {
  216. if (offset >= DB_SQL_MAX_LEN)
  217. {
  218. LOG_E("sql is too long,(%d)", offset);
  219. rc = SQLITE_ERROR;
  220. goto __db_exec_fail;
  221. }
  222. if ((sqlstr[index] != ';') && (sqlstr[index] != 0))
  223. {
  224. sql[offset++] = sqlstr[index++];
  225. }
  226. else
  227. {
  228. sql[offset] = '\0';
  229. if (sqlstr[index] == ';')
  230. {
  231. index++;
  232. }
  233. n++;
  234. break;
  235. }
  236. } while (1);
  237. rc = sqlite3_prepare(db, sql, -1, &stmt, NULL);
  238. if (rc != SQLITE_OK)
  239. {
  240. LOG_E("prepare error,rc=%d", rc);
  241. goto __db_exec_fail;
  242. }
  243. if (bind)
  244. {
  245. rc = (*bind)(stmt, n, param);
  246. }
  247. else
  248. {
  249. rc = sqlite3_step(stmt);
  250. }
  251. sqlite3_finalize(stmt);
  252. if ((rc != SQLITE_OK) && (rc != SQLITE_DONE))
  253. {
  254. LOG_E("bind failed");
  255. goto __db_exec_fail;
  256. }
  257. }
  258. rc = sqlite3_exec(db, "commit transaction", 0, 0, NULL);
  259. if (rc)
  260. {
  261. LOG_E("commit transaction:%d", rc);
  262. goto __db_exec_fail;
  263. }
  264. goto __db_exec_ok;
  265. __db_exec_fail:
  266. if (sqlite3_exec(db, "rollback transaction", 0, 0, NULL))
  267. {
  268. LOG_E("rollback transaction error");
  269. }
  270. __db_begin_fail:
  271. LOG_E("db operator failed,rc=%d", rc);
  272. __db_exec_ok:
  273. sqlite3_close(db);
  274. rt_mutex_release(db_mutex_lock);
  275. return rc;
  276. }
  277. /**
  278. * This function will be used for the operating that is not SELECT.The additional
  279. * arguments following format are formatted and inserted in the resulting string
  280. * replacing their respective specifiers.
  281. *
  282. * @param sql the SQL statement.
  283. * @param fmt the args format.such as %s string,%d int.
  284. * @param ... the additional arguments
  285. * @return =SQLITE_OK:success, others:fail.
  286. */
  287. int db_nonquery_by_varpara(const char *sql, const char *fmt, ...)
  288. {
  289. sqlite3 *db = NULL;
  290. sqlite3_stmt *stmt = NULL;
  291. if (sql == NULL)
  292. {
  293. return SQLITE_ERROR;
  294. }
  295. rt_mutex_take(db_mutex_lock, RT_WAITING_FOREVER);
  296. int rc = sqlite3_open(db_name, &db);
  297. if (rc != SQLITE_OK)
  298. {
  299. LOG_E("open database failed,rc=%d\n", rc);
  300. rt_mutex_release(db_mutex_lock);
  301. return rc;
  302. }
  303. LOG_D("sql:%s", sql);
  304. rc = sqlite3_prepare(db, sql, -1, &stmt, NULL);
  305. if (rc != SQLITE_OK)
  306. {
  307. LOG_E("prepare error,rc=%d", rc);
  308. goto __db_exec_fail;
  309. }
  310. if (fmt)
  311. {
  312. va_list args;
  313. va_start(args, fmt);
  314. rc = db_bind_by_var(stmt, fmt, args);
  315. va_end(args);
  316. if (rc)
  317. {
  318. goto __db_exec_fail;
  319. }
  320. }
  321. rc = sqlite3_step(stmt);
  322. sqlite3_finalize(stmt);
  323. if ((rc != SQLITE_OK) && (rc != SQLITE_DONE))
  324. {
  325. LOG_E("bind error,rc=%d", rc);
  326. goto __db_exec_fail;
  327. }
  328. rc = SQLITE_OK;
  329. goto __db_exec_ok;
  330. __db_exec_fail:
  331. LOG_E("db operator failed,rc=%d", rc);
  332. __db_exec_ok:
  333. sqlite3_close(db);
  334. rt_mutex_release(db_mutex_lock);
  335. return rc;
  336. }
  337. /**
  338. * This function will be used for the transaction that is not SELECT.
  339. *
  340. * @param exec_sqls the callback function of executing SQL statements.
  341. * exec_sqls@param db the database connection handle
  342. * exec_sqls@param arg the input parameter from 'db_nonquery_transaction' function parameter 'arg'.
  343. * exec_sqls@return =SQLITE_OK or =SQLITE_DONE:success,others:fail
  344. * @param arg the parameter for the callback "exec_sqls".
  345. * @return =SQLITE_OK:success, others:fail.
  346. */
  347. int db_nonquery_transaction(int (*exec_sqls)(sqlite3 *db, void *arg), void *arg)
  348. {
  349. sqlite3 *db = NULL;
  350. rt_mutex_take(db_mutex_lock, RT_WAITING_FOREVER);
  351. int rc = sqlite3_open(db_name, &db);
  352. if (rc != SQLITE_OK)
  353. {
  354. LOG_E("open database failed,rc=%d", rc);
  355. rt_mutex_release(db_mutex_lock);
  356. return rc;
  357. }
  358. rc = sqlite3_exec(db, "begin transaction", 0, 0, NULL);
  359. if (rc != SQLITE_OK)
  360. {
  361. LOG_E("begin transaction:%d", rc);
  362. goto __db_begin_fail;
  363. }
  364. if (exec_sqls)
  365. {
  366. rc = (*exec_sqls)(db, arg);
  367. }
  368. else
  369. {
  370. rc = SQLITE_ERROR;
  371. }
  372. if ((rc != SQLITE_OK) && (rc != SQLITE_DONE))
  373. {
  374. LOG_E("prepare error,rc=%d", rc);
  375. goto __db_exec_fail;
  376. }
  377. rc = sqlite3_exec(db, "commit transaction", 0, 0, NULL);
  378. if (rc)
  379. {
  380. LOG_E("commit transaction:%d", rc);
  381. goto __db_exec_fail;
  382. }
  383. goto __db_exec_ok;
  384. __db_exec_fail:
  385. if (sqlite3_exec(db, "rollback transaction", 0, 0, NULL))
  386. {
  387. LOG_E("rollback transaction:error");
  388. }
  389. __db_begin_fail:
  390. LOG_E("db operator failed,rc=%d", rc);
  391. __db_exec_ok:
  392. sqlite3_close(db);
  393. rt_mutex_release(db_mutex_lock);
  394. return rc;
  395. }
  396. static int db_get_count(sqlite3_stmt *stmt, void *arg)
  397. {
  398. int ret, *count = arg;
  399. ret = sqlite3_step(stmt);
  400. if (ret != SQLITE_ROW)
  401. {
  402. return SQLITE_EMPTY;
  403. }
  404. *count = db_stmt_get_int(stmt, 0);
  405. return SQLITE_OK;
  406. }
  407. /**
  408. * This function will return the number of records returned by a select query.
  409. * This function only gets the 1st row of the 1st column.
  410. *
  411. * @param sql the SQL statement SELECT COUNT() FROM .
  412. * @return >=0:the count ,<0: fail.
  413. */
  414. int db_query_count_result(const char *sql)
  415. {
  416. int ret, count = 0;
  417. ret = db_query_by_varpara(sql, db_get_count, &count, NULL);
  418. if (ret == SQLITE_OK)
  419. {
  420. return count;
  421. }
  422. return -RT_ERROR;
  423. }
  424. /**
  425. * This function will get the blob from the "index" colum.
  426. *
  427. * @param stmt the SQL statement returned by the function sqlite3_step().
  428. * @param index the colum index.the first colum's index value is 0.
  429. * @param out the output buffer.the result will put in this buffer.
  430. * @return >=0:the result length ,<0: fail.
  431. */
  432. int db_stmt_get_blob(sqlite3_stmt *stmt, int index, unsigned char *out)
  433. {
  434. const char *pdata = sqlite3_column_blob(stmt, index);
  435. int len = sqlite3_column_bytes(stmt, index);
  436. if (pdata)
  437. {
  438. memcpy(out, pdata, len);
  439. return len;
  440. }
  441. return -RT_ERROR;
  442. }
  443. /**
  444. * This function will get the text from the "index" colum.
  445. *
  446. * @param stmt the SQL statement returned by the function sqlite3_step().
  447. * @param index the colum index.the first colum's index value is 0.
  448. * @param out the output buffer.the result will put in this buffer.
  449. * @return >=0:the result length ,<0: fail.
  450. */
  451. int db_stmt_get_text(sqlite3_stmt *stmt, int index, char *out)
  452. {
  453. const unsigned char *pdata = sqlite3_column_text(stmt, index);
  454. if (pdata)
  455. {
  456. int len = strlen((char *)pdata);
  457. strncpy(out, (char *)pdata, len);
  458. return len;
  459. }
  460. return -RT_ERROR;
  461. }
  462. /**
  463. * This function will get a integer from the "index" colum.
  464. *
  465. * @param stmt the SQL statement returned by the function sqlite3_step().
  466. * @param index the colum index.the first colum's index value is 0.
  467. * @return the result.
  468. */
  469. int db_stmt_get_int(sqlite3_stmt *stmt, int index)
  470. {
  471. return sqlite3_column_int(stmt, index);
  472. }
  473. /**
  474. * This function will get a double precision value from the "index" colum.
  475. *
  476. * @param stmt the SQL statement returned by the function sqlite3_step().
  477. * @param index the colum index.the first colum's index value is 0.
  478. * @return the result.
  479. */
  480. double db_stmt_get_double(sqlite3_stmt *stmt, int index)
  481. {
  482. return sqlite3_column_double(stmt, index);
  483. }
  484. /**
  485. * This function will check a table exist or not by table name.
  486. *
  487. * @param tbl_name the table name.
  488. * @return >0:existed; ==0:not existed; <0:ERROR
  489. */
  490. int db_table_is_exist(const char *tbl_name)
  491. {
  492. char sqlstr[DB_SQL_MAX_LEN];
  493. int cnt = 0;
  494. if (tbl_name == RT_NULL)
  495. {
  496. return -RT_ERROR;
  497. }
  498. rt_snprintf(sqlstr, DB_SQL_MAX_LEN, "select count(*) from sqlite_master where type = 'table' and name = '%s';", tbl_name);
  499. cnt = db_query_count_result(sqlstr);
  500. if (cnt > 0)
  501. {
  502. return cnt;
  503. }
  504. return -RT_ERROR;
  505. }
  506. /**
  507. * This function will connect DB
  508. *
  509. * @param name the DB filename.
  510. * @return RT_EOK:success
  511. * -RT_ERROR:the input name is too long
  512. */
  513. int db_connect(char *name)
  514. {
  515. int32_t len = 0;
  516. rt_mutex_take(db_mutex_lock, RT_WAITING_FOREVER);
  517. len = rt_strnlen(name, PKG_SQLITE_DB_NAME_MAX_LEN + 1);
  518. if (len >= PKG_SQLITE_DB_NAME_MAX_LEN + 1)
  519. {
  520. LOG_E("the database name '(%s)' lengh is too long(max:%d).", name, PKG_SQLITE_DB_NAME_MAX_LEN);
  521. rt_mutex_release(db_mutex_lock);
  522. return -RT_ERROR;
  523. }
  524. rt_strncpy(db_name, name, len);
  525. db_name[len] = '\0';
  526. return RT_EOK;
  527. }
  528. /**
  529. * This function will disconnect DB
  530. *
  531. * @param name the DB filename.
  532. * @return RT_EOK:success
  533. * -RT_ERROR:the input name is too long
  534. */
  535. int db_disconnect(char *name)
  536. {
  537. int32_t len = 0;
  538. rt_mutex_release(db_mutex_lock);
  539. rt_strncpy(db_name, DEFAULT_DB_NAME, strlen(DEFAULT_DB_NAME));
  540. db_name[len] = '\0';
  541. return RT_EOK;
  542. }
  543. /**
  544. * This function will connect DB
  545. *
  546. * @param name the DB filename.
  547. * @return RT_EOK:success
  548. * -RT_ERROR:the input name is too long
  549. */
  550. int db_set_name(char *name)
  551. {
  552. int32_t len = 0;
  553. rt_mutex_take(db_mutex_lock, RT_WAITING_FOREVER);
  554. len = rt_strnlen(name, PKG_SQLITE_DB_NAME_MAX_LEN + 1);
  555. if (len >= PKG_SQLITE_DB_NAME_MAX_LEN + 1)
  556. {
  557. LOG_E("the database name '(%s)' lengh is too long(max:%d).", name, PKG_SQLITE_DB_NAME_MAX_LEN);
  558. rt_mutex_release(db_mutex_lock);
  559. return -RT_ERROR;
  560. }
  561. rt_strncpy(db_name, name, len);
  562. db_name[len] = '\0';
  563. rt_mutex_release(db_mutex_lock);
  564. return RT_EOK;
  565. }
  566. /**
  567. * This function will get the current DB filename
  568. *
  569. * @return the current DB filename
  570. *
  571. */
  572. char *db_get_name(void)
  573. {
  574. static char name[PKG_SQLITE_DB_NAME_MAX_LEN + 1];
  575. size_t len = rt_strlen(db_name);
  576. rt_strncpy(name, db_name, len);
  577. name[len] = '\0';
  578. return name;
  579. }