CppSQLite3.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. ////////////////////////////////////////////////////////////////////////////////
  2. // CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library.
  3. //
  4. // Copyright (c) 2004 Rob Groves. All Rights Reserved. [email protected]
  5. //
  6. // Permission to use, copy, modify, and distribute this software and its
  7. // documentation for any purpose, without fee, and without a written
  8. // agreement, is hereby granted, provided that the above copyright notice,
  9. // this paragraph and the following two paragraphs appear in all copies,
  10. // modifications, and distributions.
  11. //
  12. // IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
  13. // INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
  14. // PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
  15. // EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16. //
  17. // THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  18. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  19. // PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
  20. // ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
  21. // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  22. //
  23. // V3.0 03/08/2004 -Initial Version for sqlite3
  24. //
  25. // V3.1 16/09/2004 -Implemented getXXXXField using sqlite3 functions
  26. // -Added CppSQLiteDB3::tableExists()
  27. ////////////////////////////////////////////////////////////////////////////////
  28. #include "StdAfx.h"
  29. #include "CppSQLite3.h"
  30. #include <cstdlib>
  31. #include "..\UnicodeMacros.h"
  32. #include <regex>
  33. // Named constant for passing to CppSQLite3Exception when passing it a string
  34. // that cannot be deleted.
  35. static const bool DONT_DELETE_MSG=false;
  36. ////////////////////////////////////////////////////////////////////////////////
  37. // Prototypes for SQLite functions not included in SQLite DLL, but copied below
  38. // from SQLite encode.c
  39. ////////////////////////////////////////////////////////////////////////////////
  40. int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out);
  41. int sqlite3_decode_binary(const unsigned char *in, unsigned char *out);
  42. ////////////////////////////////////////////////////////////////////////////////
  43. ////////////////////////////////////////////////////////////////////////////////
  44. CppSQLite3Exception::CppSQLite3Exception(const int nErrCode,
  45. TCHAR* szErrMess,
  46. bool bDeleteMsg/*=true*/) :
  47. mnErrCode(nErrCode)
  48. {
  49. #ifdef _UNICODE
  50. swprintf(mpszErrMess, _T("%s[%d]: %s"),
  51. errorCodeAsString(nErrCode),
  52. nErrCode,
  53. szErrMess ? szErrMess : _T(""));
  54. #else
  55. sprintf(mpszErrMess, "%s[%d]: %s",
  56. errorCodeAsString(nErrCode),
  57. nErrCode,
  58. szErrMess ? szErrMess : "");
  59. #endif
  60. // if (bDeleteMsg && szErrMess)
  61. // {
  62. // sqlite3_free(szErrMess);
  63. // }
  64. }
  65. CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception& e) :
  66. mnErrCode(e.mnErrCode)
  67. {
  68. mpszErrMess[0] = 0;
  69. if(e.mpszErrMess)
  70. {
  71. #ifdef _UNICODE
  72. swprintf(mpszErrMess, _T("%s"), e.mpszErrMess);
  73. #else
  74. sprintf(mpszErrMess, "%s", e.mpszErrMess);
  75. #endif
  76. }
  77. }
  78. const TCHAR* CppSQLite3Exception::errorCodeAsString(int nErrCode)
  79. {
  80. switch (nErrCode)
  81. {
  82. case SQLITE_OK : return _T("SQLITE_OK");
  83. case SQLITE_ERROR : return _T("SQLITE_ERROR");
  84. case SQLITE_INTERNAL : return _T("SQLITE_INTERNAL");
  85. case SQLITE_PERM : return _T("SQLITE_PERM");
  86. case SQLITE_ABORT : return _T("SQLITE_ABORT");
  87. case SQLITE_BUSY : return _T("SQLITE_BUSY");
  88. case SQLITE_LOCKED : return _T("SQLITE_LOCKED");
  89. case SQLITE_NOMEM : return _T("SQLITE_NOMEM");
  90. case SQLITE_READONLY : return _T("SQLITE_READONLY");
  91. case SQLITE_INTERRUPT : return _T("SQLITE_INTERRUPT");
  92. case SQLITE_IOERR : return _T("SQLITE_IOERR");
  93. case SQLITE_CORRUPT : return _T("SQLITE_CORRUPT");
  94. case SQLITE_NOTFOUND : return _T("SQLITE_NOTFOUND");
  95. case SQLITE_FULL : return _T("SQLITE_FULL");
  96. case SQLITE_CANTOPEN : return _T("SQLITE_CANTOPEN");
  97. case SQLITE_PROTOCOL : return _T("SQLITE_PROTOCOL");
  98. case SQLITE_EMPTY : return _T("SQLITE_EMPTY");
  99. case SQLITE_SCHEMA : return _T("SQLITE_SCHEMA");
  100. case SQLITE_TOOBIG : return _T("SQLITE_TOOBIG");
  101. case SQLITE_CONSTRAINT : return _T("SQLITE_CONSTRAINT");
  102. case SQLITE_MISMATCH : return _T("SQLITE_MISMATCH");
  103. case SQLITE_MISUSE : return _T("SQLITE_MISUSE");
  104. case SQLITE_NOLFS : return _T("SQLITE_NOLFS");
  105. case SQLITE_AUTH : return _T("SQLITE_AUTH");
  106. case SQLITE_FORMAT : return _T("SQLITE_FORMAT");
  107. case SQLITE_RANGE : return _T("SQLITE_RANGE");
  108. case SQLITE_ROW : return _T("SQLITE_ROW");
  109. case SQLITE_DONE : return _T("SQLITE_DONE");
  110. case CPPSQLITE_ERROR : return _T("CPPSQLITE_ERROR");
  111. default: return _T("UNKNOWN_ERROR");
  112. }
  113. }
  114. CppSQLite3Exception::~CppSQLite3Exception()
  115. {
  116. }
  117. ////////////////////////////////////////////////////////////////////////////////
  118. CppSQLite3Query::CppSQLite3Query()
  119. {
  120. mpVM = 0;
  121. mbEof = true;
  122. mnCols = 0;
  123. mbOwnVM = false;
  124. }
  125. CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query& rQuery)
  126. {
  127. mpVM = rQuery.mpVM;
  128. // Only one object can own the VM
  129. const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
  130. mbEof = rQuery.mbEof;
  131. mnCols = rQuery.mnCols;
  132. mbOwnVM = rQuery.mbOwnVM;
  133. }
  134. CppSQLite3Query::CppSQLite3Query(sqlite3* pDB,
  135. sqlite3_stmt* pVM,
  136. bool bEof,
  137. bool bOwnVM/*=true*/)
  138. {
  139. mpDB = pDB;
  140. mpVM = pVM;
  141. mbEof = bEof;
  142. mnCols = sqlite3_column_count(mpVM);
  143. mbOwnVM = bOwnVM;
  144. }
  145. CppSQLite3Query::~CppSQLite3Query()
  146. {
  147. try
  148. {
  149. finalize();
  150. }
  151. catch (...)
  152. {
  153. }
  154. }
  155. CppSQLite3Query& CppSQLite3Query::operator=(const CppSQLite3Query& rQuery)
  156. {
  157. try
  158. {
  159. finalize();
  160. }
  161. catch (...)
  162. {
  163. }
  164. mpVM = rQuery.mpVM;
  165. // Only one object can own the VM
  166. const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
  167. mbEof = rQuery.mbEof;
  168. mnCols = rQuery.mnCols;
  169. mbOwnVM = rQuery.mbOwnVM;
  170. return *this;
  171. }
  172. int CppSQLite3Query::numFields()
  173. {
  174. checkVM();
  175. return mnCols;
  176. }
  177. const TCHAR* CppSQLite3Query::fieldValue(int nField)
  178. {
  179. checkVM();
  180. if (nField < 0 || nField > mnCols-1)
  181. {
  182. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  183. _T("Invalid field index requested"),
  184. DONT_DELETE_MSG);
  185. }
  186. #ifdef _UNICODE
  187. return (const TCHAR*)sqlite3_column_text16(mpVM, nField);
  188. #else
  189. return (const TCHAR*)sqlite3_column_text(mpVM, nField);
  190. #endif
  191. }
  192. const TCHAR* CppSQLite3Query::fieldValue(const TCHAR* szField)
  193. {
  194. int nField = fieldIndex(szField);
  195. #ifdef _UNICODE
  196. return (const TCHAR*)sqlite3_column_text16(mpVM, nField);
  197. #else
  198. return (const TCHAR*)sqlite3_column_text(mpVM, nField);
  199. #endif
  200. }
  201. int CppSQLite3Query::getIntField(int nField, int nNullValue/*=0*/)
  202. {
  203. if (fieldDataType(nField) == SQLITE_NULL)
  204. {
  205. return nNullValue;
  206. }
  207. else
  208. {
  209. return sqlite3_column_int(mpVM, nField);
  210. }
  211. }
  212. int CppSQLite3Query::getIntField(const TCHAR* szField, int nNullValue/*=0*/)
  213. {
  214. int nField = fieldIndex(szField);
  215. return getIntField(nField, nNullValue);
  216. }
  217. double CppSQLite3Query::getFloatField(int nField, double fNullValue/*=0.0*/)
  218. {
  219. if (fieldDataType(nField) == SQLITE_NULL)
  220. {
  221. return fNullValue;
  222. }
  223. else
  224. {
  225. return sqlite3_column_double(mpVM, nField);
  226. }
  227. }
  228. double CppSQLite3Query::getFloatField(const TCHAR* szField, double fNullValue/*=0.0*/)
  229. {
  230. int nField = fieldIndex(szField);
  231. return getFloatField(nField, fNullValue);
  232. }
  233. const TCHAR* CppSQLite3Query::getStringField(int nField, const TCHAR* szNullValue/*=""*/)
  234. {
  235. if (fieldDataType(nField) == SQLITE_NULL)
  236. {
  237. return szNullValue;
  238. }
  239. else
  240. {
  241. #ifdef _UNICODE
  242. return (const TCHAR*)sqlite3_column_text16(mpVM, nField);
  243. #else
  244. return (const TCHAR*)sqlite3_column_text(mpVM, nField);
  245. #endif
  246. }
  247. }
  248. const TCHAR* CppSQLite3Query::getStringField(const TCHAR* szField, const TCHAR* szNullValue/*=""*/)
  249. {
  250. int nField = fieldIndex(szField);
  251. return getStringField(nField, szNullValue);
  252. }
  253. int CppSQLite3Query::getBlobFieldSize(int nField)
  254. {
  255. checkVM();
  256. if (nField < 0 || nField > mnCols-1)
  257. {
  258. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  259. _T("Invalid field index requested"),
  260. DONT_DELETE_MSG);
  261. }
  262. int nLen = sqlite3_column_bytes(mpVM, nField);
  263. return nLen;
  264. }
  265. const unsigned char* CppSQLite3Query::getBlobField(int nField, int& nLen)
  266. {
  267. checkVM();
  268. if (nField < 0 || nField > mnCols-1)
  269. {
  270. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  271. _T("Invalid field index requested"),
  272. DONT_DELETE_MSG);
  273. }
  274. nLen = sqlite3_column_bytes(mpVM, nField);
  275. return (const unsigned char*)sqlite3_column_blob(mpVM, nField);
  276. }
  277. int CppSQLite3Query::getBlobFieldSize(const TCHAR* szField)
  278. {
  279. int nField = fieldIndex(szField);
  280. return getBlobFieldSize(nField);
  281. }
  282. const unsigned char* CppSQLite3Query::getBlobField(const TCHAR* szField, int& nLen)
  283. {
  284. int nField = fieldIndex(szField);
  285. return getBlobField(nField, nLen);
  286. }
  287. bool CppSQLite3Query::fieldIsNull(int nField)
  288. {
  289. return (fieldDataType(nField) == SQLITE_NULL);
  290. }
  291. bool CppSQLite3Query::fieldIsNull(const TCHAR* szField)
  292. {
  293. int nField = fieldIndex(szField);
  294. return (fieldDataType(nField) == SQLITE_NULL);
  295. }
  296. int CppSQLite3Query::fieldIndex(const TCHAR* szField)
  297. {
  298. checkVM();
  299. if (szField)
  300. {
  301. for (int nField = 0; nField < mnCols; nField++)
  302. {
  303. #ifdef _UNICODE
  304. const TCHAR* szTemp = (const TCHAR*)sqlite3_column_name16(mpVM, nField);
  305. #else
  306. const TCHAR* szTemp = sqlite3_column_name(mpVM, nField);
  307. #endif
  308. if(STRCMP(szField, szTemp) == 0)
  309. {
  310. return nField;
  311. }
  312. }
  313. }
  314. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  315. _T("Invalid field name requested"),
  316. DONT_DELETE_MSG);
  317. }
  318. const TCHAR* CppSQLite3Query::fieldName(int nCol)
  319. {
  320. checkVM();
  321. if (nCol < 0 || nCol > mnCols-1)
  322. {
  323. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  324. _T("Invalid field index requested"),
  325. DONT_DELETE_MSG);
  326. }
  327. #ifdef _UNICODE
  328. return (const TCHAR*)sqlite3_column_name16(mpVM, nCol);
  329. #else
  330. return sqlite3_column_name(mpVM, nCol);
  331. #endif
  332. }
  333. const TCHAR* CppSQLite3Query::fieldDeclType(int nCol)
  334. {
  335. checkVM();
  336. if (nCol < 0 || nCol > mnCols-1)
  337. {
  338. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  339. _T("Invalid field index requested"),
  340. DONT_DELETE_MSG);
  341. }
  342. #ifdef _UNICODE
  343. return (const TCHAR*)sqlite3_column_decltype16(mpVM, nCol);
  344. #else
  345. return sqlite3_column_decltype(mpVM, nCol);
  346. #endif
  347. }
  348. int CppSQLite3Query::fieldDataType(int nCol)
  349. {
  350. checkVM();
  351. if (nCol < 0 || nCol > mnCols-1)
  352. {
  353. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  354. _T("Invalid field index requested"),
  355. DONT_DELETE_MSG);
  356. }
  357. return sqlite3_column_type(mpVM, nCol);
  358. }
  359. bool CppSQLite3Query::eof()
  360. {
  361. checkVM();
  362. return mbEof;
  363. }
  364. void CppSQLite3Query::nextRow()
  365. {
  366. checkVM();
  367. int nRet = sqlite3_step(mpVM);
  368. if (nRet == SQLITE_DONE)
  369. {
  370. // no rows
  371. mbEof = true;
  372. }
  373. else if (nRet == SQLITE_ROW)
  374. {
  375. // more rows, nothing to do
  376. }
  377. else
  378. {
  379. nRet = sqlite3_finalize(mpVM);
  380. mpVM = 0;
  381. SQLITE3_ERRMSG(mpDB);
  382. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  383. }
  384. }
  385. void CppSQLite3Query::finalize()
  386. {
  387. if (mpVM && mbOwnVM)
  388. {
  389. int nRet = sqlite3_finalize(mpVM);
  390. mpVM = 0;
  391. if (nRet != SQLITE_OK)
  392. {
  393. SQLITE3_ERRMSG(mpDB);
  394. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  395. }
  396. }
  397. }
  398. void CppSQLite3Query::checkVM()
  399. {
  400. if (mpVM == 0)
  401. {
  402. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  403. _T("Null Virtual Machine pointer"),
  404. DONT_DELETE_MSG);
  405. }
  406. }
  407. ////////////////////////////////////////////////////////////////////////////////
  408. CppSQLite3Statement::CppSQLite3Statement()
  409. {
  410. mpDB = 0;
  411. mpVM = 0;
  412. }
  413. CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement& rStatement)
  414. {
  415. mpDB = rStatement.mpDB;
  416. mpVM = rStatement.mpVM;
  417. // Only one object can own VM
  418. const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
  419. }
  420. CppSQLite3Statement::CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM)
  421. {
  422. mpDB = pDB;
  423. mpVM = pVM;
  424. }
  425. CppSQLite3Statement::~CppSQLite3Statement()
  426. {
  427. try
  428. {
  429. finalize();
  430. }
  431. catch (...)
  432. {
  433. }
  434. }
  435. CppSQLite3Statement& CppSQLite3Statement::operator=(const CppSQLite3Statement& rStatement)
  436. {
  437. mpDB = rStatement.mpDB;
  438. mpVM = rStatement.mpVM;
  439. // Only one object can own VM
  440. const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
  441. return *this;
  442. }
  443. int CppSQLite3Statement::execDML()
  444. {
  445. checkDB();
  446. checkVM();
  447. int nRet = sqlite3_step(mpVM);
  448. if (nRet == SQLITE_DONE)
  449. {
  450. int nRowsChanged = sqlite3_changes(mpDB);
  451. nRet = sqlite3_reset(mpVM);
  452. if (nRet != SQLITE_OK)
  453. {
  454. SQLITE3_ERRMSG(mpDB);
  455. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  456. }
  457. return nRowsChanged;
  458. }
  459. else
  460. {
  461. nRet = sqlite3_reset(mpVM);
  462. SQLITE3_ERRMSG(mpDB);
  463. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  464. }
  465. }
  466. CppSQLite3Query CppSQLite3Statement::execQuery()
  467. {
  468. checkDB();
  469. checkVM();
  470. int nRet = sqlite3_step(mpVM);
  471. if (nRet == SQLITE_DONE)
  472. {
  473. // no rows
  474. return CppSQLite3Query(mpDB, mpVM, true/*eof*/, false);
  475. }
  476. else if (nRet == SQLITE_ROW)
  477. {
  478. // at least 1 row
  479. return CppSQLite3Query(mpDB, mpVM, false/*eof*/, false);
  480. }
  481. else
  482. {
  483. nRet = sqlite3_reset(mpVM);
  484. SQLITE3_ERRMSG(mpDB);
  485. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  486. }
  487. }
  488. void CppSQLite3Statement::bind(int nParam, const TCHAR* szValue)
  489. {
  490. checkVM();
  491. #ifdef _UNICODE
  492. int nRes = sqlite3_bind_text16(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT);
  493. #else
  494. int nRes = sqlite3_bind_text(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT);
  495. #endif
  496. if (nRes != SQLITE_OK)
  497. {
  498. throw CppSQLite3Exception(nRes,
  499. _T("Error binding string param"),
  500. DONT_DELETE_MSG);
  501. }
  502. }
  503. void CppSQLite3Statement::bind(int nParam, const int nValue)
  504. {
  505. checkVM();
  506. int nRes = sqlite3_bind_int(mpVM, nParam, nValue);
  507. if (nRes != SQLITE_OK)
  508. {
  509. throw CppSQLite3Exception(nRes,
  510. _T("Error binding int param"),
  511. DONT_DELETE_MSG);
  512. }
  513. }
  514. void CppSQLite3Statement::bind(int nParam, const double dValue)
  515. {
  516. checkVM();
  517. int nRes = sqlite3_bind_double(mpVM, nParam, dValue);
  518. if (nRes != SQLITE_OK)
  519. {
  520. throw CppSQLite3Exception(nRes,
  521. _T("Error binding double param"),
  522. DONT_DELETE_MSG);
  523. }
  524. }
  525. void CppSQLite3Statement::bind(int nParam, const unsigned char* blobValue, int nLen)
  526. {
  527. checkVM();
  528. int nRes = sqlite3_bind_blob(mpVM, nParam,
  529. (const void*)blobValue, nLen, SQLITE_TRANSIENT);
  530. if (nRes != SQLITE_OK)
  531. {
  532. throw CppSQLite3Exception(nRes,
  533. _T("Error binding blob param"),
  534. DONT_DELETE_MSG);
  535. }
  536. }
  537. void CppSQLite3Statement::bindNull(int nParam)
  538. {
  539. checkVM();
  540. int nRes = sqlite3_bind_null(mpVM, nParam);
  541. if (nRes != SQLITE_OK)
  542. {
  543. throw CppSQLite3Exception(nRes,
  544. _T("Error binding NULL param"),
  545. DONT_DELETE_MSG);
  546. }
  547. }
  548. void CppSQLite3Statement::reset()
  549. {
  550. if (mpVM)
  551. {
  552. int nRet = sqlite3_reset(mpVM);
  553. if (nRet != SQLITE_OK)
  554. {
  555. SQLITE3_ERRMSG(mpDB);
  556. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  557. }
  558. }
  559. }
  560. void CppSQLite3Statement::finalize()
  561. {
  562. if (mpVM)
  563. {
  564. int nRet = sqlite3_finalize(mpVM);
  565. mpVM = 0;
  566. if (nRet != SQLITE_OK)
  567. {
  568. SQLITE3_ERRMSG(mpDB);
  569. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  570. }
  571. }
  572. }
  573. void CppSQLite3Statement::checkDB()
  574. {
  575. if (mpDB == 0)
  576. {
  577. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  578. _T("Database not open"),
  579. DONT_DELETE_MSG);
  580. }
  581. }
  582. void CppSQLite3Statement::checkVM()
  583. {
  584. if (mpVM == 0)
  585. {
  586. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  587. _T("Null Virtual Machine pointer"),
  588. DONT_DELETE_MSG);
  589. }
  590. }
  591. ////////////////////////////////////////////////////////////////////////////////
  592. CppSQLite3DB::CppSQLite3DB()
  593. {
  594. mpDB = 0;
  595. mnBusyTimeoutMs = 60000; // 60 seconds
  596. }
  597. CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB& db)
  598. {
  599. mpDB = db.mpDB;
  600. mnBusyTimeoutMs = 60000; // 60 seconds
  601. }
  602. CppSQLite3DB::~CppSQLite3DB()
  603. {
  604. close();
  605. }
  606. CppSQLite3DB& CppSQLite3DB::operator=(const CppSQLite3DB& db)
  607. {
  608. mpDB = db.mpDB;
  609. mnBusyTimeoutMs = 60000; // 60 seconds
  610. return *this;
  611. }
  612. void sqlite_regexp(sqlite3_context* context, int argc, sqlite3_value** values)
  613. {
  614. char* reg = (char*) sqlite3_value_text(values[0]);
  615. char* text = (char*) sqlite3_value_text(values[1]);
  616. if (argc != 2 || reg == 0 || text == 0)
  617. {
  618. //sqlite3_result_error(context, "SQL function regexp() called with invalid arguments.\n", -1);
  619. sqlite3_result_int(context, 0);
  620. return;
  621. }
  622. try
  623. {
  624. if (std::regex_search(text, std::regex(reg)))
  625. {
  626. sqlite3_result_int(context, 1);
  627. }
  628. else
  629. {
  630. sqlite3_result_int(context, 0);
  631. }
  632. }
  633. catch (std::regex_error& e)
  634. {
  635. CStringA r;
  636. r.Format("regex_search exception %d, reg: %s, str: %s", e.code(), reg, text);
  637. OutputDebugStringA(r);
  638. }
  639. }
  640. void CppSQLite3DB::open(const TCHAR* szFile)
  641. {
  642. #ifdef _UNICODE
  643. int nRet = sqlite3_open16(szFile, &mpDB);
  644. #else
  645. int nRet = sqlite3_open(szFile, &mpDB);
  646. #endif
  647. if (nRet != SQLITE_OK)
  648. {
  649. SQLITE3_ERRMSG(mpDB);
  650. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  651. }
  652. int ret = sqlite3_create_function(mpDB, "regexp", 2, SQLITE_ANY, 0, &sqlite_regexp, 0, 0);
  653. setBusyTimeout(mnBusyTimeoutMs);
  654. }
  655. bool CppSQLite3DB::close()
  656. {
  657. bool bRet = true;
  658. if (mpDB)
  659. {
  660. int nClose = sqlite3_close(mpDB);
  661. if(nClose != SQLITE_OK)
  662. {
  663. ASSERT(!"Error closing sqlite db");
  664. bRet = false;
  665. }
  666. mpDB = 0;
  667. }
  668. return bRet;
  669. }
  670. CppSQLite3Statement CppSQLite3DB::compileStatement(const TCHAR* szSQL)
  671. {
  672. checkDB();
  673. sqlite3_stmt* pVM = compile(szSQL);
  674. return CppSQLite3Statement(mpDB, pVM);
  675. }
  676. bool CppSQLite3DB::tableExists(const TCHAR* szTable)
  677. {
  678. TCHAR szSQL[128];
  679. SPRINTF(szSQL,
  680. _T("select count(*) from sqlite_master where type='table' and name='%s'"),
  681. szTable);
  682. int nRet = execScalar(szSQL);
  683. return (nRet > 0);
  684. }
  685. int CppSQLite3DB::execDMLEx(LPCTSTR szSQL,...)
  686. {
  687. CString csText;
  688. va_list vlist;
  689. ASSERT(AfxIsValidString(szSQL));
  690. va_start(vlist,szSQL);
  691. csText.FormatV(szSQL,vlist);
  692. va_end(vlist);
  693. return execDML(csText);
  694. }
  695. int CppSQLite3DB::execDML(const TCHAR* szSQL)
  696. {
  697. checkDB();
  698. sqlite3_stmt* pVM = compile(szSQL);
  699. int nRet = sqlite3_step(pVM);
  700. if (nRet == SQLITE_DONE)
  701. {
  702. nRet = sqlite3_changes(mpDB);
  703. sqlite3_finalize(pVM);
  704. }
  705. else
  706. {
  707. nRet = sqlite3_finalize(pVM);
  708. SQLITE3_ERRMSG(mpDB);
  709. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  710. }
  711. return nRet;
  712. }
  713. CppSQLite3Query CppSQLite3DB::execQueryEx(LPCTSTR szSQL,...)
  714. {
  715. CString csText;
  716. va_list vlist;
  717. ASSERT(AfxIsValidString(szSQL));
  718. va_start(vlist,szSQL);
  719. csText.FormatV(szSQL,vlist);
  720. va_end(vlist);
  721. return execQuery(csText);
  722. }
  723. CppSQLite3Query CppSQLite3DB::execQuery(const TCHAR* szSQL)
  724. {
  725. checkDB();
  726. sqlite3_stmt* pVM = compile(szSQL);
  727. int nRet = sqlite3_step(pVM);
  728. if (nRet == SQLITE_DONE)
  729. {
  730. // no rows
  731. return CppSQLite3Query(mpDB, pVM, true/*eof*/);
  732. }
  733. else if (nRet == SQLITE_ROW)
  734. {
  735. // at least 1 row
  736. return CppSQLite3Query(mpDB, pVM, false/*eof*/);
  737. }
  738. else
  739. {
  740. nRet = sqlite3_finalize(pVM);
  741. SQLITE3_ERRMSG(mpDB);
  742. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  743. }
  744. }
  745. int CppSQLite3DB::execScalarEx(LPCTSTR szSQL,...)
  746. {
  747. CString csText;
  748. va_list vlist;
  749. ASSERT(AfxIsValidString(szSQL));
  750. va_start(vlist, szSQL);
  751. csText.FormatV(szSQL,vlist);
  752. va_end(vlist);
  753. return execScalar(csText);
  754. }
  755. int CppSQLite3DB::execScalar(const TCHAR* szSQL)
  756. {
  757. CppSQLite3Query q = execQuery(szSQL);
  758. if (q.eof() || q.numFields() < 1)
  759. {
  760. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  761. _T("Invalid scalar query"),
  762. DONT_DELETE_MSG);
  763. }
  764. return ATOI(q.fieldValue(0));
  765. }
  766. sqlite_int64 CppSQLite3DB::lastRowId()
  767. {
  768. return sqlite3_last_insert_rowid(mpDB);
  769. }
  770. void CppSQLite3DB::setBusyTimeout(int nMillisecs)
  771. {
  772. mnBusyTimeoutMs = nMillisecs;
  773. sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs);
  774. }
  775. void CppSQLite3DB::checkDB()
  776. {
  777. if (!mpDB)
  778. {
  779. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  780. _T("Database not open"),
  781. DONT_DELETE_MSG);
  782. }
  783. }
  784. sqlite3_stmt* CppSQLite3DB::compile(const TCHAR* szSQL)
  785. {
  786. checkDB();
  787. TCHAR* szError=0;
  788. const TCHAR* szTail=0;
  789. sqlite3_stmt* pVM;
  790. #ifdef _UNICODE
  791. int nRet = sqlite3_prepare16_v2(mpDB, szSQL, -1, &pVM, (const void**)szTail);
  792. #else
  793. int nRet = sqlite3_prepare_v2(mpDB, szSQL, -1, &pVM, &szTail);
  794. #endif
  795. if (nRet != SQLITE_OK)
  796. {
  797. throw CppSQLite3Exception(nRet, (TCHAR*)szError);
  798. }
  799. return pVM;
  800. }
  801. ////////////////////////////////////////////////////////////////////////////////
  802. // SQLite encode.c reproduced here, containing implementation notes and source
  803. // for sqlite3_encode_binary() and sqlite3_decode_binary()
  804. ////////////////////////////////////////////////////////////////////////////////
  805. /*
  806. ** 2002 April 25
  807. **
  808. ** The author disclaims copyright to this source code. In place of
  809. ** a legal notice, here is a blessing:
  810. **
  811. ** May you do good and not evil.
  812. ** May you find forgiveness for yourself and forgive others.
  813. ** May you share freely, never taking more than you give.
  814. **
  815. *************************************************************************
  816. ** This file contains helper routines used to translate binary data into
  817. ** a null-terminated string (suitable for use in SQLite) and back again.
  818. ** These are convenience routines for use by people who want to store binary
  819. ** data in an SQLite database. The code in this file is not used by any other
  820. ** part of the SQLite library.
  821. **
  822. ** $Id: CppSQLite3.cpp,v 1.2 2006-09-14 04:56:10 sabrogden Exp $
  823. */
  824. /*
  825. ** How This Encoder Works
  826. **
  827. ** The output is allowed to contain any character except 0x27 (') and
  828. ** 0x00. This is accomplished by using an escape character to encode
  829. ** 0x27 and 0x00 as a two-byte sequence. The escape character is always
  830. ** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The
  831. ** 0x27 character is encoded as the two byte sequence 0x01 0x03. Finally,
  832. ** the escape character itself is encoded as the two-character sequence
  833. ** 0x01 0x02.
  834. **
  835. ** To summarize, the encoder works by using an escape sequences as follows:
  836. **
  837. ** 0x00 -> 0x01 0x01
  838. ** 0x01 -> 0x01 0x02
  839. ** 0x27 -> 0x01 0x03
  840. **
  841. ** If that were all the encoder did, it would work, but in certain cases
  842. ** it could double the size of the encoded string. For example, to
  843. ** encode a string of 100 0x27 characters would require 100 instances of
  844. ** the 0x01 0x03 escape sequence resulting in a 200-character output.
  845. ** We would prefer to keep the size of the encoded string smaller than
  846. ** this.
  847. **
  848. ** To minimize the encoding size, we first add a fixed offset value to each
  849. ** byte in the sequence. The addition is modulo 256. (That is to say, if
  850. ** the sum of the original character value and the offset exceeds 256, then
  851. ** the higher order bits are truncated.) The offset is chosen to minimize
  852. ** the number of characters in the string that need to be escaped. For
  853. ** example, in the case above where the string was composed of 100 0x27
  854. ** characters, the offset might be 0x01. Each of the 0x27 characters would
  855. ** then be converted into an 0x28 character which would not need to be
  856. ** escaped at all and so the 100 character input string would be converted
  857. ** into just 100 characters of output. Actually 101 characters of output -
  858. ** we have to record the offset used as the first byte in the sequence so
  859. ** that the string can be decoded. Since the offset value is stored as
  860. ** part of the output string and the output string is not allowed to contain
  861. ** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
  862. **
  863. ** Here, then, are the encoding steps:
  864. **
  865. ** (1) Choose an offset value and make it the first character of
  866. ** output.
  867. **
  868. ** (2) Copy each input character into the output buffer, one by
  869. ** one, adding the offset value as you copy.
  870. **
  871. ** (3) If the value of an input character plus offset is 0x00, replace
  872. ** that one character by the two-character sequence 0x01 0x01.
  873. ** If the sum is 0x01, replace it with 0x01 0x02. If the sum
  874. ** is 0x27, replace it with 0x01 0x03.
  875. **
  876. ** (4) Put a 0x00 terminator at the end of the output.
  877. **
  878. ** Decoding is obvious:
  879. **
  880. ** (5) Copy encoded characters except the first into the decode
  881. ** buffer. Set the first encoded character aside for use as
  882. ** the offset in step 7 below.
  883. **
  884. ** (6) Convert each 0x01 0x01 sequence into a single character 0x00.
  885. ** Convert 0x01 0x02 into 0x01. Convert 0x01 0x03 into 0x27.
  886. **
  887. ** (7) Subtract the offset value that was the first character of
  888. ** the encoded buffer from all characters in the output buffer.
  889. **
  890. ** The only tricky part is step (1) - how to compute an offset value to
  891. ** minimize the size of the output buffer. This is accomplished by testing
  892. ** all offset values and picking the one that results in the fewest number
  893. ** of escapes. To do that, we first scan the entire input and count the
  894. ** number of occurances of each character value in the input. Suppose
  895. ** the number of 0x00 characters is N(0), the number of occurances of 0x01
  896. ** is N(1), and so forth up to the number of occurances of 0xff is N(255).
  897. ** An offset of 0 is not allowed so we don't have to test it. The number
  898. ** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number
  899. ** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth.
  900. ** In this way we find the offset that gives the minimum number of escapes,
  901. ** and thus minimizes the length of the output string.
  902. */
  903. /*
  904. ** Encode a binary buffer "in" of size n bytes so that it contains
  905. ** no instances of characters '\'' or '\000'. The output is
  906. ** null-terminated and can be used as a string value in an INSERT
  907. ** or UPDATE statement. Use sqlite3_decode_binary() to convert the
  908. ** string back into its original binary.
  909. **
  910. ** The result is written into a preallocated output buffer "out".
  911. ** "out" must be able to hold at least 2 +(257*n)/254 bytes.
  912. ** In other words, the output will be expanded by as much as 3
  913. ** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
  914. ** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
  915. **
  916. ** The return value is the number of characters in the encoded
  917. ** string, excluding the "\000" terminator.
  918. */
  919. int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){
  920. int i, j, e, m;
  921. int cnt[256];
  922. if( n<=0 ){
  923. out[0] = 'x';
  924. out[1] = 0;
  925. return 1;
  926. }
  927. memset(cnt, 0, sizeof(cnt));
  928. for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
  929. m = n;
  930. for(i=1; i<256; i++){
  931. int sum;
  932. if( i=='\'' ) continue;
  933. sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
  934. if( sum<m ){
  935. m = sum;
  936. e = i;
  937. if( m==0 ) break;
  938. }
  939. }
  940. out[0] = e;
  941. j = 1;
  942. for(i=0; i<n; i++){
  943. int c = (in[i] - e)&0xff;
  944. if( c==0 ){
  945. out[j++] = 1;
  946. out[j++] = 1;
  947. }else if( c==1 ){
  948. out[j++] = 1;
  949. out[j++] = 2;
  950. }else if( c=='\'' ){
  951. out[j++] = 1;
  952. out[j++] = 3;
  953. }else{
  954. out[j++] = c;
  955. }
  956. }
  957. out[j] = 0;
  958. return j;
  959. }
  960. /*
  961. ** Decode the string "in" into binary data and write it into "out".
  962. ** This routine reverses the encoding created by sqlite3_encode_binary().
  963. ** The output will always be a few bytes less than the input. The number
  964. ** of bytes of output is returned. If the input is not a well-formed
  965. ** encoding, -1 is returned.
  966. **
  967. ** The "in" and "out" parameters may point to the same buffer in order
  968. ** to decode a string in place.
  969. */
  970. int sqlite3_decode_binary(const unsigned char *in, unsigned char *out){
  971. int i, c, e;
  972. e = *(in++);
  973. i = 0;
  974. while( (c = *(in++))!=0 ){
  975. if( c==1 ){
  976. c = *(in++);
  977. if( c==1 ){
  978. c = 0;
  979. }else if( c==2 ){
  980. c = 1;
  981. }else if( c==3 ){
  982. c = '\'';
  983. }else{
  984. return -1;
  985. }
  986. }
  987. out[i++] = (c + e)&0xff;
  988. }
  989. return i;
  990. }