CppSQLite3.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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, std::regex::flag_type::icase)))
  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. sqlite3_enable_load_extension(mpDB, 1);
  655. char* e;
  656. sqlite3_load_extension(mpDB, "ICU_Loader.dll", "sqlite3_icu_init", &e);
  657. }
  658. void CppSQLite3DB::SetRegexCaseInsensitive(bool insensitive)
  659. {
  660. auto h = ::LoadLibrary(_T("ICU_Loader.dll"));
  661. if (h != NULL)
  662. {
  663. void(__cdecl * SetRegexFlags)(int flags);
  664. SetRegexFlags = (void(__cdecl*)(int flags))GetProcAddress(h, "sqlite3_icu_regex_flags");
  665. if (SetRegexFlags != NULL)
  666. {
  667. if (insensitive)
  668. {
  669. SetRegexFlags(2); // 2 is the enum URegexpFlag::UREGEX_CASE_INSENSITIVE
  670. }
  671. else
  672. {
  673. SetRegexFlags(0);
  674. }
  675. }
  676. }
  677. }
  678. bool CppSQLite3DB::close()
  679. {
  680. bool bRet = true;
  681. if (mpDB)
  682. {
  683. int nClose = sqlite3_close(mpDB);
  684. if(nClose != SQLITE_OK)
  685. {
  686. ASSERT(!"Error closing sqlite db");
  687. bRet = false;
  688. }
  689. mpDB = 0;
  690. }
  691. return bRet;
  692. }
  693. CppSQLite3Statement CppSQLite3DB::compileStatement(const TCHAR* szSQL)
  694. {
  695. checkDB();
  696. sqlite3_stmt* pVM = compile(szSQL);
  697. return CppSQLite3Statement(mpDB, pVM);
  698. }
  699. bool CppSQLite3DB::tableExists(const TCHAR* szTable)
  700. {
  701. TCHAR szSQL[128];
  702. SPRINTF(szSQL,
  703. _T("select count(*) from sqlite_master where type='table' and name='%s'"),
  704. szTable);
  705. int nRet = execScalar(szSQL);
  706. return (nRet > 0);
  707. }
  708. int CppSQLite3DB::execDMLEx(LPCTSTR szSQL,...)
  709. {
  710. CString csText;
  711. va_list vlist;
  712. ASSERT(AfxIsValidString(szSQL));
  713. va_start(vlist,szSQL);
  714. csText.FormatV(szSQL,vlist);
  715. va_end(vlist);
  716. return execDML(csText);
  717. }
  718. int CppSQLite3DB::execDML(const TCHAR* szSQL)
  719. {
  720. checkDB();
  721. sqlite3_stmt* pVM = compile(szSQL);
  722. int nRet = sqlite3_step(pVM);
  723. if (nRet == SQLITE_DONE)
  724. {
  725. nRet = sqlite3_changes(mpDB);
  726. sqlite3_finalize(pVM);
  727. }
  728. else
  729. {
  730. nRet = sqlite3_finalize(pVM);
  731. SQLITE3_ERRMSG(mpDB);
  732. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  733. }
  734. return nRet;
  735. }
  736. CppSQLite3Query CppSQLite3DB::execQueryEx(LPCTSTR szSQL,...)
  737. {
  738. CString csText;
  739. va_list vlist;
  740. ASSERT(AfxIsValidString(szSQL));
  741. va_start(vlist,szSQL);
  742. csText.FormatV(szSQL,vlist);
  743. va_end(vlist);
  744. return execQuery(csText);
  745. }
  746. CppSQLite3Query CppSQLite3DB::execQuery(const TCHAR* szSQL)
  747. {
  748. checkDB();
  749. sqlite3_stmt* pVM = compile(szSQL);
  750. int nRet = sqlite3_step(pVM);
  751. if (nRet == SQLITE_DONE)
  752. {
  753. // no rows
  754. return CppSQLite3Query(mpDB, pVM, true/*eof*/);
  755. }
  756. else if (nRet == SQLITE_ROW)
  757. {
  758. // at least 1 row
  759. return CppSQLite3Query(mpDB, pVM, false/*eof*/);
  760. }
  761. else
  762. {
  763. nRet = sqlite3_finalize(pVM);
  764. SQLITE3_ERRMSG(mpDB);
  765. throw CppSQLite3Exception(nRet, (TCHAR*)szError, DONT_DELETE_MSG);
  766. }
  767. }
  768. int CppSQLite3DB::execScalarEx(LPCTSTR szSQL,...)
  769. {
  770. CString csText;
  771. va_list vlist;
  772. ASSERT(AfxIsValidString(szSQL));
  773. va_start(vlist, szSQL);
  774. csText.FormatV(szSQL,vlist);
  775. va_end(vlist);
  776. return execScalar(csText);
  777. }
  778. int CppSQLite3DB::execScalar(const TCHAR* szSQL)
  779. {
  780. CppSQLite3Query q = execQuery(szSQL);
  781. if (q.eof() || q.numFields() < 1)
  782. {
  783. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  784. _T("Invalid scalar query"),
  785. DONT_DELETE_MSG);
  786. }
  787. return ATOI(q.fieldValue(0));
  788. }
  789. sqlite_int64 CppSQLite3DB::lastRowId()
  790. {
  791. return sqlite3_last_insert_rowid(mpDB);
  792. }
  793. void CppSQLite3DB::setBusyTimeout(int nMillisecs)
  794. {
  795. mnBusyTimeoutMs = nMillisecs;
  796. sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs);
  797. }
  798. void CppSQLite3DB::checkDB()
  799. {
  800. if (!mpDB)
  801. {
  802. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  803. _T("Database not open"),
  804. DONT_DELETE_MSG);
  805. }
  806. }
  807. sqlite3_stmt* CppSQLite3DB::compile(const TCHAR* szSQL)
  808. {
  809. checkDB();
  810. TCHAR* szError=0;
  811. const TCHAR* szTail=0;
  812. sqlite3_stmt* pVM;
  813. #ifdef _UNICODE
  814. int nRet = sqlite3_prepare16_v2(mpDB, szSQL, -1, &pVM, (const void**)szTail);
  815. #else
  816. int nRet = sqlite3_prepare_v2(mpDB, szSQL, -1, &pVM, &szTail);
  817. #endif
  818. if (nRet != SQLITE_OK)
  819. {
  820. throw CppSQLite3Exception(nRet, (TCHAR*)szError);
  821. }
  822. return pVM;
  823. }
  824. ////////////////////////////////////////////////////////////////////////////////
  825. // SQLite encode.c reproduced here, containing implementation notes and source
  826. // for sqlite3_encode_binary() and sqlite3_decode_binary()
  827. ////////////////////////////////////////////////////////////////////////////////
  828. /*
  829. ** 2002 April 25
  830. **
  831. ** The author disclaims copyright to this source code. In place of
  832. ** a legal notice, here is a blessing:
  833. **
  834. ** May you do good and not evil.
  835. ** May you find forgiveness for yourself and forgive others.
  836. ** May you share freely, never taking more than you give.
  837. **
  838. *************************************************************************
  839. ** This file contains helper routines used to translate binary data into
  840. ** a null-terminated string (suitable for use in SQLite) and back again.
  841. ** These are convenience routines for use by people who want to store binary
  842. ** data in an SQLite database. The code in this file is not used by any other
  843. ** part of the SQLite library.
  844. **
  845. ** $Id: CppSQLite3.cpp,v 1.2 2006-09-14 04:56:10 sabrogden Exp $
  846. */
  847. /*
  848. ** How This Encoder Works
  849. **
  850. ** The output is allowed to contain any character except 0x27 (') and
  851. ** 0x00. This is accomplished by using an escape character to encode
  852. ** 0x27 and 0x00 as a two-byte sequence. The escape character is always
  853. ** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The
  854. ** 0x27 character is encoded as the two byte sequence 0x01 0x03. Finally,
  855. ** the escape character itself is encoded as the two-character sequence
  856. ** 0x01 0x02.
  857. **
  858. ** To summarize, the encoder works by using an escape sequences as follows:
  859. **
  860. ** 0x00 -> 0x01 0x01
  861. ** 0x01 -> 0x01 0x02
  862. ** 0x27 -> 0x01 0x03
  863. **
  864. ** If that were all the encoder did, it would work, but in certain cases
  865. ** it could double the size of the encoded string. For example, to
  866. ** encode a string of 100 0x27 characters would require 100 instances of
  867. ** the 0x01 0x03 escape sequence resulting in a 200-character output.
  868. ** We would prefer to keep the size of the encoded string smaller than
  869. ** this.
  870. **
  871. ** To minimize the encoding size, we first add a fixed offset value to each
  872. ** byte in the sequence. The addition is modulo 256. (That is to say, if
  873. ** the sum of the original character value and the offset exceeds 256, then
  874. ** the higher order bits are truncated.) The offset is chosen to minimize
  875. ** the number of characters in the string that need to be escaped. For
  876. ** example, in the case above where the string was composed of 100 0x27
  877. ** characters, the offset might be 0x01. Each of the 0x27 characters would
  878. ** then be converted into an 0x28 character which would not need to be
  879. ** escaped at all and so the 100 character input string would be converted
  880. ** into just 100 characters of output. Actually 101 characters of output -
  881. ** we have to record the offset used as the first byte in the sequence so
  882. ** that the string can be decoded. Since the offset value is stored as
  883. ** part of the output string and the output string is not allowed to contain
  884. ** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
  885. **
  886. ** Here, then, are the encoding steps:
  887. **
  888. ** (1) Choose an offset value and make it the first character of
  889. ** output.
  890. **
  891. ** (2) Copy each input character into the output buffer, one by
  892. ** one, adding the offset value as you copy.
  893. **
  894. ** (3) If the value of an input character plus offset is 0x00, replace
  895. ** that one character by the two-character sequence 0x01 0x01.
  896. ** If the sum is 0x01, replace it with 0x01 0x02. If the sum
  897. ** is 0x27, replace it with 0x01 0x03.
  898. **
  899. ** (4) Put a 0x00 terminator at the end of the output.
  900. **
  901. ** Decoding is obvious:
  902. **
  903. ** (5) Copy encoded characters except the first into the decode
  904. ** buffer. Set the first encoded character aside for use as
  905. ** the offset in step 7 below.
  906. **
  907. ** (6) Convert each 0x01 0x01 sequence into a single character 0x00.
  908. ** Convert 0x01 0x02 into 0x01. Convert 0x01 0x03 into 0x27.
  909. **
  910. ** (7) Subtract the offset value that was the first character of
  911. ** the encoded buffer from all characters in the output buffer.
  912. **
  913. ** The only tricky part is step (1) - how to compute an offset value to
  914. ** minimize the size of the output buffer. This is accomplished by testing
  915. ** all offset values and picking the one that results in the fewest number
  916. ** of escapes. To do that, we first scan the entire input and count the
  917. ** number of occurances of each character value in the input. Suppose
  918. ** the number of 0x00 characters is N(0), the number of occurances of 0x01
  919. ** is N(1), and so forth up to the number of occurances of 0xff is N(255).
  920. ** An offset of 0 is not allowed so we don't have to test it. The number
  921. ** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number
  922. ** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth.
  923. ** In this way we find the offset that gives the minimum number of escapes,
  924. ** and thus minimizes the length of the output string.
  925. */
  926. /*
  927. ** Encode a binary buffer "in" of size n bytes so that it contains
  928. ** no instances of characters '\'' or '\000'. The output is
  929. ** null-terminated and can be used as a string value in an INSERT
  930. ** or UPDATE statement. Use sqlite3_decode_binary() to convert the
  931. ** string back into its original binary.
  932. **
  933. ** The result is written into a preallocated output buffer "out".
  934. ** "out" must be able to hold at least 2 +(257*n)/254 bytes.
  935. ** In other words, the output will be expanded by as much as 3
  936. ** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
  937. ** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
  938. **
  939. ** The return value is the number of characters in the encoded
  940. ** string, excluding the "\000" terminator.
  941. */
  942. int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){
  943. int i, j, e, m;
  944. int cnt[256];
  945. if( n<=0 ){
  946. out[0] = 'x';
  947. out[1] = 0;
  948. return 1;
  949. }
  950. memset(cnt, 0, sizeof(cnt));
  951. for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
  952. m = n;
  953. for(i=1; i<256; i++){
  954. int sum;
  955. if( i=='\'' ) continue;
  956. sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
  957. if( sum<m ){
  958. m = sum;
  959. e = i;
  960. if( m==0 ) break;
  961. }
  962. }
  963. out[0] = e;
  964. j = 1;
  965. for(i=0; i<n; i++){
  966. int c = (in[i] - e)&0xff;
  967. if( c==0 ){
  968. out[j++] = 1;
  969. out[j++] = 1;
  970. }else if( c==1 ){
  971. out[j++] = 1;
  972. out[j++] = 2;
  973. }else if( c=='\'' ){
  974. out[j++] = 1;
  975. out[j++] = 3;
  976. }else{
  977. out[j++] = c;
  978. }
  979. }
  980. out[j] = 0;
  981. return j;
  982. }
  983. /*
  984. ** Decode the string "in" into binary data and write it into "out".
  985. ** This routine reverses the encoding created by sqlite3_encode_binary().
  986. ** The output will always be a few bytes less than the input. The number
  987. ** of bytes of output is returned. If the input is not a well-formed
  988. ** encoding, -1 is returned.
  989. **
  990. ** The "in" and "out" parameters may point to the same buffer in order
  991. ** to decode a string in place.
  992. */
  993. int sqlite3_decode_binary(const unsigned char *in, unsigned char *out){
  994. int i, c, e;
  995. e = *(in++);
  996. i = 0;
  997. while( (c = *(in++))!=0 ){
  998. if( c==1 ){
  999. c = *(in++);
  1000. if( c==1 ){
  1001. c = 0;
  1002. }else if( c==2 ){
  1003. c = 1;
  1004. }else if( c==3 ){
  1005. c = '\'';
  1006. }else{
  1007. return -1;
  1008. }
  1009. }
  1010. out[i++] = (c + e)&0xff;
  1011. }
  1012. return i;
  1013. }