CppSQLite3.cpp 27 KB

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