CppSQLite3.cpp 26 KB

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