CppSQLite3.cpp 26 KB

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