CppSQLite3.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. ////////////////////////////////////////////////////////////////////////////////
  2. // CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library.
  3. //
  4. // Copyright (c) 2004..2007 Rob Groves. All Rights Reserved. rob.groves@btinternet.com
  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. // V3.2 01/07/2005 -Fixed execScalar to handle a NULL result
  29. // 12/07/2007 -Added int64 functions to CppSQLite3Query
  30. // -Throw exception from CppSQLite3DB::close() if error
  31. // -Trap above exception in CppSQLite3DB::~CppSQLite3DB()
  32. // -Fix to CppSQLite3DB::compile() as provided by Dave Rollins.
  33. // -sqlite3_prepare replaced with sqlite3_prepare_v2
  34. // -Added Name based parameter binding to CppSQLite3Statement.
  35. ////////////////////////////////////////////////////////////////////////////////
  36. #include "CppSQLite3.h"
  37. #include <cstdlib>
  38. #include "windows.h"
  39. // Named constant for passing to CppSQLite3Exception when passing it a string
  40. // that cannot be deleted.
  41. static const bool DONT_DELETE_MSG=false;
  42. ////////////////////////////////////////////////////////////////////////////////
  43. // Prototypes for SQLite functions not included in SQLite DLL, but copied below
  44. // from SQLite encode.c
  45. ////////////////////////////////////////////////////////////////////////////////
  46. int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out);
  47. int sqlite3_decode_binary(const unsigned char *in, unsigned char *out);
  48. ////////////////////////////////////////////////////////////////////////////////
  49. ////////////////////////////////////////////////////////////////////////////////
  50. CppSQLite3Exception::CppSQLite3Exception(const int nErrCode,
  51. char* szErrMess,
  52. bool bDeleteMsg/*=true*/) :
  53. mnErrCode(nErrCode)
  54. {
  55. mpszErrMess = sqlite3_mprintf("%s[%d]: %s",
  56. errorCodeAsString(nErrCode),
  57. nErrCode,
  58. szErrMess ? szErrMess : "");
  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;
  68. if (e.mpszErrMess)
  69. {
  70. mpszErrMess = sqlite3_mprintf("%s", e.mpszErrMess);
  71. }
  72. }
  73. const char* CppSQLite3Exception::errorCodeAsString(int nErrCode)
  74. {
  75. switch (nErrCode)
  76. {
  77. case SQLITE_OK : return "SQLITE_OK";
  78. case SQLITE_ERROR : return "SQLITE_ERROR";
  79. case SQLITE_INTERNAL : return "SQLITE_INTERNAL";
  80. case SQLITE_PERM : return "SQLITE_PERM";
  81. case SQLITE_ABORT : return "SQLITE_ABORT";
  82. case SQLITE_BUSY : return "SQLITE_BUSY";
  83. case SQLITE_LOCKED : return "SQLITE_LOCKED";
  84. case SQLITE_NOMEM : return "SQLITE_NOMEM";
  85. case SQLITE_READONLY : return "SQLITE_READONLY";
  86. case SQLITE_INTERRUPT : return "SQLITE_INTERRUPT";
  87. case SQLITE_IOERR : return "SQLITE_IOERR";
  88. case SQLITE_CORRUPT : return "SQLITE_CORRUPT";
  89. case SQLITE_NOTFOUND : return "SQLITE_NOTFOUND";
  90. case SQLITE_FULL : return "SQLITE_FULL";
  91. case SQLITE_CANTOPEN : return "SQLITE_CANTOPEN";
  92. case SQLITE_PROTOCOL : return "SQLITE_PROTOCOL";
  93. case SQLITE_EMPTY : return "SQLITE_EMPTY";
  94. case SQLITE_SCHEMA : return "SQLITE_SCHEMA";
  95. case SQLITE_TOOBIG : return "SQLITE_TOOBIG";
  96. case SQLITE_CONSTRAINT : return "SQLITE_CONSTRAINT";
  97. case SQLITE_MISMATCH : return "SQLITE_MISMATCH";
  98. case SQLITE_MISUSE : return "SQLITE_MISUSE";
  99. case SQLITE_NOLFS : return "SQLITE_NOLFS";
  100. case SQLITE_AUTH : return "SQLITE_AUTH";
  101. case SQLITE_FORMAT : return "SQLITE_FORMAT";
  102. case SQLITE_RANGE : return "SQLITE_RANGE";
  103. case SQLITE_ROW : return "SQLITE_ROW";
  104. case SQLITE_DONE : return "SQLITE_DONE";
  105. case CPPSQLITE_ERROR : return "CPPSQLITE_ERROR";
  106. default: return "UNKNOWN_ERROR";
  107. }
  108. }
  109. CppSQLite3Exception::~CppSQLite3Exception()
  110. {
  111. if (mpszErrMess)
  112. {
  113. sqlite3_free(mpszErrMess);
  114. mpszErrMess = 0;
  115. }
  116. }
  117. ////////////////////////////////////////////////////////////////////////////////
  118. CppSQLite3Buffer::CppSQLite3Buffer()
  119. {
  120. mpBuf = 0;
  121. }
  122. CppSQLite3Buffer::~CppSQLite3Buffer()
  123. {
  124. clear();
  125. }
  126. void CppSQLite3Buffer::clear()
  127. {
  128. if (mpBuf)
  129. {
  130. sqlite3_free(mpBuf);
  131. mpBuf = 0;
  132. }
  133. }
  134. const char* CppSQLite3Buffer::format(const char* szFormat, ...)
  135. {
  136. clear();
  137. va_list va;
  138. va_start(va, szFormat);
  139. mpBuf = sqlite3_vmprintf(szFormat, va);
  140. va_end(va);
  141. return mpBuf;
  142. }
  143. ////////////////////////////////////////////////////////////////////////////////
  144. CppSQLite3Binary::CppSQLite3Binary() :
  145. mpBuf(0),
  146. mnBinaryLen(0),
  147. mnBufferLen(0),
  148. mnEncodedLen(0),
  149. mbEncoded(false)
  150. {
  151. }
  152. CppSQLite3Binary::~CppSQLite3Binary()
  153. {
  154. clear();
  155. }
  156. void CppSQLite3Binary::setBinary(const unsigned char* pBuf, int nLen)
  157. {
  158. mpBuf = allocBuffer(nLen);
  159. memcpy(mpBuf, pBuf, nLen);
  160. }
  161. void CppSQLite3Binary::setEncoded(const unsigned char* pBuf)
  162. {
  163. clear();
  164. mnEncodedLen = strlen((const char*)pBuf);
  165. mnBufferLen = mnEncodedLen + 1; // Allow for NULL terminator
  166. mpBuf = (unsigned char*)malloc(mnBufferLen);
  167. if (!mpBuf)
  168. {
  169. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  170. "Cannot allocate memory",
  171. DONT_DELETE_MSG);
  172. }
  173. memcpy(mpBuf, pBuf, mnBufferLen);
  174. mbEncoded = true;
  175. }
  176. const unsigned char* CppSQLite3Binary::getEncoded()
  177. {
  178. if (!mbEncoded)
  179. {
  180. unsigned char* ptmp = (unsigned char*)malloc(mnBinaryLen);
  181. memcpy(ptmp, mpBuf, mnBinaryLen);
  182. mnEncodedLen = sqlite3_encode_binary(ptmp, mnBinaryLen, mpBuf);
  183. free(ptmp);
  184. mbEncoded = true;
  185. }
  186. return mpBuf;
  187. }
  188. const unsigned char* CppSQLite3Binary::getBinary()
  189. {
  190. if (mbEncoded)
  191. {
  192. // in/out buffers can be the same
  193. mnBinaryLen = sqlite3_decode_binary(mpBuf, mpBuf);
  194. if (mnBinaryLen == -1)
  195. {
  196. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  197. "Cannot decode binary",
  198. DONT_DELETE_MSG);
  199. }
  200. mbEncoded = false;
  201. }
  202. return mpBuf;
  203. }
  204. int CppSQLite3Binary::getBinaryLength()
  205. {
  206. getBinary();
  207. return mnBinaryLen;
  208. }
  209. unsigned char* CppSQLite3Binary::allocBuffer(int nLen)
  210. {
  211. clear();
  212. // Allow extra space for encoded binary as per comments in
  213. // SQLite encode.c See bottom of this file for implementation
  214. // of SQLite functions use 3 instead of 2 just to be sure ;-)
  215. mnBinaryLen = nLen;
  216. mnBufferLen = 3 + (257*nLen)/254;
  217. mpBuf = (unsigned char*)malloc(mnBufferLen);
  218. if (!mpBuf)
  219. {
  220. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  221. "Cannot allocate memory",
  222. DONT_DELETE_MSG);
  223. }
  224. mbEncoded = false;
  225. return mpBuf;
  226. }
  227. void CppSQLite3Binary::clear()
  228. {
  229. if (mpBuf)
  230. {
  231. mnBinaryLen = 0;
  232. mnBufferLen = 0;
  233. free(mpBuf);
  234. mpBuf = 0;
  235. }
  236. }
  237. ////////////////////////////////////////////////////////////////////////////////
  238. CppSQLite3Query::CppSQLite3Query()
  239. {
  240. mpVM = 0;
  241. mbEof = true;
  242. mnCols = 0;
  243. mbOwnVM = false;
  244. }
  245. CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query& rQuery)
  246. {
  247. mpVM = rQuery.mpVM;
  248. // Only one object can own the VM
  249. const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
  250. mbEof = rQuery.mbEof;
  251. mnCols = rQuery.mnCols;
  252. mbOwnVM = rQuery.mbOwnVM;
  253. }
  254. CppSQLite3Query::CppSQLite3Query(sqlite3* pDB,
  255. sqlite3_stmt* pVM,
  256. bool bEof,
  257. bool bOwnVM/*=true*/)
  258. {
  259. mpDB = pDB;
  260. mpVM = pVM;
  261. mbEof = bEof;
  262. mnCols = sqlite3_column_count(mpVM);
  263. mbOwnVM = bOwnVM;
  264. }
  265. CppSQLite3Query::~CppSQLite3Query()
  266. {
  267. try
  268. {
  269. finalize();
  270. }
  271. catch (...)
  272. {
  273. }
  274. }
  275. CppSQLite3Query& CppSQLite3Query::operator=(const CppSQLite3Query& rQuery)
  276. {
  277. try
  278. {
  279. finalize();
  280. }
  281. catch (...)
  282. {
  283. }
  284. mpVM = rQuery.mpVM;
  285. // Only one object can own the VM
  286. const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
  287. mbEof = rQuery.mbEof;
  288. mnCols = rQuery.mnCols;
  289. mbOwnVM = rQuery.mbOwnVM;
  290. return *this;
  291. }
  292. int CppSQLite3Query::numFields()
  293. {
  294. checkVM();
  295. return mnCols;
  296. }
  297. const char* CppSQLite3Query::fieldValue(int nField)
  298. {
  299. checkVM();
  300. if (nField < 0 || nField > mnCols-1)
  301. {
  302. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  303. "Invalid field index requested",
  304. DONT_DELETE_MSG);
  305. }
  306. return (const char*)sqlite3_column_text(mpVM, nField);
  307. }
  308. const char* CppSQLite3Query::fieldValue(const char* szField)
  309. {
  310. int nField = fieldIndex(szField);
  311. return (const char*)sqlite3_column_text(mpVM, nField);
  312. }
  313. int CppSQLite3Query::getIntField(int nField, int nNullValue/*=0*/)
  314. {
  315. if (fieldDataType(nField) == SQLITE_NULL)
  316. {
  317. return nNullValue;
  318. }
  319. else
  320. {
  321. return sqlite3_column_int(mpVM, nField);
  322. }
  323. }
  324. int CppSQLite3Query::getIntField(const char* szField, int nNullValue/*=0*/)
  325. {
  326. int nField = fieldIndex(szField);
  327. return getIntField(nField, nNullValue);
  328. }
  329. sqlite_int64 CppSQLite3Query::getInt64Field(int nField, sqlite_int64 nNullValue/*=0*/)
  330. {
  331. if (fieldDataType(nField) == SQLITE_NULL)
  332. {
  333. return nNullValue;
  334. }
  335. else
  336. {
  337. return sqlite3_column_int64(mpVM, nField);
  338. }
  339. }
  340. sqlite_int64 CppSQLite3Query::getInt64Field(const char* szField, sqlite_int64 nNullValue/*=0*/)
  341. {
  342. int nField = fieldIndex(szField);
  343. return getInt64Field(nField, nNullValue);
  344. }
  345. double CppSQLite3Query::getFloatField(int nField, double fNullValue/*=0.0*/)
  346. {
  347. if (fieldDataType(nField) == SQLITE_NULL)
  348. {
  349. return fNullValue;
  350. }
  351. else
  352. {
  353. return sqlite3_column_double(mpVM, nField);
  354. }
  355. }
  356. double CppSQLite3Query::getFloatField(const char* szField, double fNullValue/*=0.0*/)
  357. {
  358. int nField = fieldIndex(szField);
  359. return getFloatField(nField, fNullValue);
  360. }
  361. const char* CppSQLite3Query::getStringField(int nField, const char* szNullValue/*=""*/)
  362. {
  363. if (fieldDataType(nField) == SQLITE_NULL)
  364. {
  365. return szNullValue;
  366. }
  367. else
  368. {
  369. return (const char*)sqlite3_column_text(mpVM, nField);
  370. }
  371. }
  372. const char* CppSQLite3Query::getStringField(const char* szField, const char* szNullValue/*=""*/)
  373. {
  374. int nField = fieldIndex(szField);
  375. return getStringField(nField, szNullValue);
  376. }
  377. const unsigned char* CppSQLite3Query::getBlobField(int nField, int& nLen)
  378. {
  379. checkVM();
  380. if (nField < 0 || nField > mnCols-1)
  381. {
  382. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  383. "Invalid field index requested",
  384. DONT_DELETE_MSG);
  385. }
  386. nLen = sqlite3_column_bytes(mpVM, nField);
  387. return (const unsigned char*)sqlite3_column_blob(mpVM, nField);
  388. }
  389. const unsigned char* CppSQLite3Query::getBlobField(const char* szField, int& nLen)
  390. {
  391. int nField = fieldIndex(szField);
  392. return getBlobField(nField, nLen);
  393. }
  394. bool CppSQLite3Query::fieldIsNull(int nField)
  395. {
  396. return (fieldDataType(nField) == SQLITE_NULL);
  397. }
  398. bool CppSQLite3Query::fieldIsNull(const char* szField)
  399. {
  400. int nField = fieldIndex(szField);
  401. return (fieldDataType(nField) == SQLITE_NULL);
  402. }
  403. int CppSQLite3Query::fieldIndex(const char* szField)
  404. {
  405. checkVM();
  406. if (szField)
  407. {
  408. for (int nField = 0; nField < mnCols; nField++)
  409. {
  410. const char* szTemp = sqlite3_column_name(mpVM, nField);
  411. if (strcmp(szField, szTemp) == 0)
  412. {
  413. return nField;
  414. }
  415. }
  416. }
  417. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  418. "Invalid field name requested",
  419. DONT_DELETE_MSG);
  420. }
  421. const char* CppSQLite3Query::fieldName(int nCol)
  422. {
  423. checkVM();
  424. if (nCol < 0 || nCol > mnCols-1)
  425. {
  426. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  427. "Invalid field index requested",
  428. DONT_DELETE_MSG);
  429. }
  430. return sqlite3_column_name(mpVM, nCol);
  431. }
  432. const char* CppSQLite3Query::fieldDeclType(int nCol)
  433. {
  434. checkVM();
  435. if (nCol < 0 || nCol > mnCols-1)
  436. {
  437. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  438. "Invalid field index requested",
  439. DONT_DELETE_MSG);
  440. }
  441. return sqlite3_column_decltype(mpVM, nCol);
  442. }
  443. int CppSQLite3Query::fieldDataType(int nCol)
  444. {
  445. checkVM();
  446. if (nCol < 0 || nCol > mnCols-1)
  447. {
  448. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  449. "Invalid field index requested",
  450. DONT_DELETE_MSG);
  451. }
  452. return sqlite3_column_type(mpVM, nCol);
  453. }
  454. bool CppSQLite3Query::eof()
  455. {
  456. checkVM();
  457. return mbEof;
  458. }
  459. void CppSQLite3Query::nextRow()
  460. {
  461. checkVM();
  462. int nRet = sqlite3_step(mpVM);
  463. if (nRet == SQLITE_DONE)
  464. {
  465. // no rows
  466. mbEof = true;
  467. }
  468. else if (nRet == SQLITE_ROW)
  469. {
  470. // more rows, nothing to do
  471. }
  472. else
  473. {
  474. nRet = sqlite3_finalize(mpVM);
  475. mpVM = 0;
  476. const char* szError = sqlite3_errmsg(mpDB);
  477. throw CppSQLite3Exception(nRet,
  478. (char*)szError,
  479. DONT_DELETE_MSG);
  480. }
  481. }
  482. void CppSQLite3Query::finalize()
  483. {
  484. if (mpVM && mbOwnVM)
  485. {
  486. int nRet = sqlite3_finalize(mpVM);
  487. mpVM = 0;
  488. if (nRet != SQLITE_OK)
  489. {
  490. const char* szError = sqlite3_errmsg(mpDB);
  491. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  492. }
  493. }
  494. }
  495. void CppSQLite3Query::checkVM()
  496. {
  497. if (mpVM == 0)
  498. {
  499. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  500. "Null Virtual Machine pointer",
  501. DONT_DELETE_MSG);
  502. }
  503. }
  504. ////////////////////////////////////////////////////////////////////////////////
  505. CppSQLite3Table::CppSQLite3Table()
  506. {
  507. mpaszResults = 0;
  508. mnRows = 0;
  509. mnCols = 0;
  510. mnCurrentRow = 0;
  511. }
  512. CppSQLite3Table::CppSQLite3Table(const CppSQLite3Table& rTable)
  513. {
  514. mpaszResults = rTable.mpaszResults;
  515. // Only one object can own the results
  516. const_cast<CppSQLite3Table&>(rTable).mpaszResults = 0;
  517. mnRows = rTable.mnRows;
  518. mnCols = rTable.mnCols;
  519. mnCurrentRow = rTable.mnCurrentRow;
  520. }
  521. CppSQLite3Table::CppSQLite3Table(char** paszResults, int nRows, int nCols)
  522. {
  523. mpaszResults = paszResults;
  524. mnRows = nRows;
  525. mnCols = nCols;
  526. mnCurrentRow = 0;
  527. }
  528. CppSQLite3Table::~CppSQLite3Table()
  529. {
  530. try
  531. {
  532. finalize();
  533. }
  534. catch (...)
  535. {
  536. }
  537. }
  538. CppSQLite3Table& CppSQLite3Table::operator=(const CppSQLite3Table& rTable)
  539. {
  540. try
  541. {
  542. finalize();
  543. }
  544. catch (...)
  545. {
  546. }
  547. mpaszResults = rTable.mpaszResults;
  548. // Only one object can own the results
  549. const_cast<CppSQLite3Table&>(rTable).mpaszResults = 0;
  550. mnRows = rTable.mnRows;
  551. mnCols = rTable.mnCols;
  552. mnCurrentRow = rTable.mnCurrentRow;
  553. return *this;
  554. }
  555. void CppSQLite3Table::finalize()
  556. {
  557. if (mpaszResults)
  558. {
  559. sqlite3_free_table(mpaszResults);
  560. mpaszResults = 0;
  561. }
  562. }
  563. int CppSQLite3Table::numFields()
  564. {
  565. checkResults();
  566. return mnCols;
  567. }
  568. int CppSQLite3Table::numRows()
  569. {
  570. checkResults();
  571. return mnRows;
  572. }
  573. const char* CppSQLite3Table::fieldValue(int nField)
  574. {
  575. checkResults();
  576. if (nField < 0 || nField > mnCols-1)
  577. {
  578. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  579. "Invalid field index requested",
  580. DONT_DELETE_MSG);
  581. }
  582. int nIndex = (mnCurrentRow*mnCols) + mnCols + nField;
  583. return mpaszResults[nIndex];
  584. }
  585. const char* CppSQLite3Table::fieldValue(const char* szField)
  586. {
  587. checkResults();
  588. if (szField)
  589. {
  590. for (int nField = 0; nField < mnCols; nField++)
  591. {
  592. if (strcmp(szField, mpaszResults[nField]) == 0)
  593. {
  594. int nIndex = (mnCurrentRow*mnCols) + mnCols + nField;
  595. return mpaszResults[nIndex];
  596. }
  597. }
  598. }
  599. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  600. "Invalid field name requested",
  601. DONT_DELETE_MSG);
  602. }
  603. int CppSQLite3Table::getIntField(int nField, int nNullValue/*=0*/)
  604. {
  605. if (fieldIsNull(nField))
  606. {
  607. return nNullValue;
  608. }
  609. else
  610. {
  611. return atoi(fieldValue(nField));
  612. }
  613. }
  614. int CppSQLite3Table::getIntField(const char* szField, int nNullValue/*=0*/)
  615. {
  616. if (fieldIsNull(szField))
  617. {
  618. return nNullValue;
  619. }
  620. else
  621. {
  622. return atoi(fieldValue(szField));
  623. }
  624. }
  625. double CppSQLite3Table::getFloatField(int nField, double fNullValue/*=0.0*/)
  626. {
  627. if (fieldIsNull(nField))
  628. {
  629. return fNullValue;
  630. }
  631. else
  632. {
  633. return atof(fieldValue(nField));
  634. }
  635. }
  636. double CppSQLite3Table::getFloatField(const char* szField, double fNullValue/*=0.0*/)
  637. {
  638. if (fieldIsNull(szField))
  639. {
  640. return fNullValue;
  641. }
  642. else
  643. {
  644. return atof(fieldValue(szField));
  645. }
  646. }
  647. const char* CppSQLite3Table::getStringField(int nField, const char* szNullValue/*=""*/)
  648. {
  649. if (fieldIsNull(nField))
  650. {
  651. return szNullValue;
  652. }
  653. else
  654. {
  655. return fieldValue(nField);
  656. }
  657. }
  658. const char* CppSQLite3Table::getStringField(const char* szField, const char* szNullValue/*=""*/)
  659. {
  660. if (fieldIsNull(szField))
  661. {
  662. return szNullValue;
  663. }
  664. else
  665. {
  666. return fieldValue(szField);
  667. }
  668. }
  669. bool CppSQLite3Table::fieldIsNull(int nField)
  670. {
  671. checkResults();
  672. return (fieldValue(nField) == 0);
  673. }
  674. bool CppSQLite3Table::fieldIsNull(const char* szField)
  675. {
  676. checkResults();
  677. return (fieldValue(szField) == 0);
  678. }
  679. const char* CppSQLite3Table::fieldName(int nCol)
  680. {
  681. checkResults();
  682. if (nCol < 0 || nCol > mnCols-1)
  683. {
  684. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  685. "Invalid field index requested",
  686. DONT_DELETE_MSG);
  687. }
  688. return mpaszResults[nCol];
  689. }
  690. void CppSQLite3Table::setRow(int nRow)
  691. {
  692. checkResults();
  693. if (nRow < 0 || nRow > mnRows-1)
  694. {
  695. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  696. "Invalid row index requested",
  697. DONT_DELETE_MSG);
  698. }
  699. mnCurrentRow = nRow;
  700. }
  701. void CppSQLite3Table::checkResults()
  702. {
  703. if (mpaszResults == 0)
  704. {
  705. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  706. "Null Results pointer",
  707. DONT_DELETE_MSG);
  708. }
  709. }
  710. ////////////////////////////////////////////////////////////////////////////////
  711. CppSQLite3Statement::CppSQLite3Statement()
  712. {
  713. mpDB = 0;
  714. mpVM = 0;
  715. }
  716. CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement& rStatement)
  717. {
  718. mpDB = rStatement.mpDB;
  719. mpVM = rStatement.mpVM;
  720. // Only one object can own VM
  721. const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
  722. }
  723. CppSQLite3Statement::CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM)
  724. {
  725. mpDB = pDB;
  726. mpVM = pVM;
  727. }
  728. CppSQLite3Statement::~CppSQLite3Statement()
  729. {
  730. try
  731. {
  732. finalize();
  733. }
  734. catch (...)
  735. {
  736. }
  737. }
  738. CppSQLite3Statement& CppSQLite3Statement::operator=(const CppSQLite3Statement& rStatement)
  739. {
  740. mpDB = rStatement.mpDB;
  741. mpVM = rStatement.mpVM;
  742. // Only one object can own VM
  743. const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
  744. return *this;
  745. }
  746. int CppSQLite3Statement::execDML()
  747. {
  748. checkDB();
  749. checkVM();
  750. const char* szError=0;
  751. int nRet = sqlite3_step(mpVM);
  752. if (nRet == SQLITE_DONE)
  753. {
  754. int nRowsChanged = sqlite3_changes(mpDB);
  755. nRet = sqlite3_reset(mpVM);
  756. if (nRet != SQLITE_OK)
  757. {
  758. szError = sqlite3_errmsg(mpDB);
  759. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  760. }
  761. return nRowsChanged;
  762. }
  763. else
  764. {
  765. nRet = sqlite3_reset(mpVM);
  766. szError = sqlite3_errmsg(mpDB);
  767. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  768. }
  769. }
  770. CppSQLite3Query CppSQLite3Statement::execQuery()
  771. {
  772. checkDB();
  773. checkVM();
  774. int nRet = sqlite3_step(mpVM);
  775. if (nRet == SQLITE_DONE)
  776. {
  777. // no rows
  778. return CppSQLite3Query(mpDB, mpVM, true/*eof*/, false);
  779. }
  780. else if (nRet == SQLITE_ROW)
  781. {
  782. // at least 1 row
  783. return CppSQLite3Query(mpDB, mpVM, false/*eof*/, false);
  784. }
  785. else
  786. {
  787. nRet = sqlite3_reset(mpVM);
  788. const char* szError = sqlite3_errmsg(mpDB);
  789. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  790. }
  791. }
  792. void CppSQLite3Statement::bind(int nParam, const char* szValue)
  793. {
  794. checkVM();
  795. int nRes = sqlite3_bind_text(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT);
  796. if (nRes != SQLITE_OK)
  797. {
  798. throw CppSQLite3Exception(nRes,
  799. "Error binding string param",
  800. DONT_DELETE_MSG);
  801. }
  802. }
  803. void CppSQLite3Statement::bind( int nParam, const sqlite3_int64 dwValue )
  804. {
  805. checkVM();
  806. int nRes = sqlite3_bind_int64(mpVM, nParam, dwValue);
  807. if (nRes != SQLITE_OK)
  808. {
  809. throw CppSQLite3Exception(nRes,
  810. "Error binding int param",
  811. DONT_DELETE_MSG);
  812. }
  813. }
  814. void CppSQLite3Statement::bind(int nParam, const int nValue)
  815. {
  816. checkVM();
  817. int nRes = sqlite3_bind_int(mpVM, nParam, nValue);
  818. if (nRes != SQLITE_OK)
  819. {
  820. throw CppSQLite3Exception(nRes,
  821. "Error binding int param",
  822. DONT_DELETE_MSG);
  823. }
  824. }
  825. void CppSQLite3Statement::bind(int nParam, const double dValue)
  826. {
  827. checkVM();
  828. int nRes = sqlite3_bind_double(mpVM, nParam, dValue);
  829. if (nRes != SQLITE_OK)
  830. {
  831. throw CppSQLite3Exception(nRes,
  832. "Error binding double param",
  833. DONT_DELETE_MSG);
  834. }
  835. }
  836. void CppSQLite3Statement::bind(int nParam, const unsigned char* blobValue, int nLen)
  837. {
  838. checkVM();
  839. int nRes = sqlite3_bind_blob(mpVM, nParam,
  840. (const void*)blobValue, nLen, SQLITE_TRANSIENT);
  841. if (nRes != SQLITE_OK)
  842. {
  843. throw CppSQLite3Exception(nRes,
  844. "Error binding blob param",
  845. DONT_DELETE_MSG);
  846. }
  847. }
  848. void CppSQLite3Statement::bindNull(int nParam)
  849. {
  850. checkVM();
  851. int nRes = sqlite3_bind_null(mpVM, nParam);
  852. if (nRes != SQLITE_OK)
  853. {
  854. throw CppSQLite3Exception(nRes,
  855. "Error binding NULL param",
  856. DONT_DELETE_MSG);
  857. }
  858. }
  859. int CppSQLite3Statement::bindParameterIndex(const char* szParam)
  860. {
  861. checkVM();
  862. int nParam = sqlite3_bind_parameter_index(mpVM, szParam);
  863. int nn = sqlite3_bind_parameter_count(mpVM);
  864. const char* sz1 = sqlite3_bind_parameter_name(mpVM, 1);
  865. const char* sz2 = sqlite3_bind_parameter_name(mpVM, 2);
  866. if (!nParam)
  867. {
  868. char buf[128];
  869. sprintf(buf, "Parameter '%s' is not valid for this statement", szParam);
  870. throw CppSQLite3Exception(CPPSQLITE_ERROR, buf, DONT_DELETE_MSG);
  871. }
  872. return nParam;
  873. }
  874. void CppSQLite3Statement::bind(const char* szParam, const char* szValue)
  875. {
  876. int nParam = bindParameterIndex(szParam);
  877. bind(nParam, szValue);
  878. }
  879. void CppSQLite3Statement::bind(const char* szParam, const int nValue)
  880. {
  881. int nParam = bindParameterIndex(szParam);
  882. bind(nParam, nValue);
  883. }
  884. void CppSQLite3Statement::bind(const char* szParam, const sqlite3_int64 dwValue)
  885. {
  886. int nParam = bindParameterIndex(szParam);
  887. bind(nParam, dwValue);
  888. }
  889. void CppSQLite3Statement::bind(const char* szParam, const double dwValue)
  890. {
  891. int nParam = bindParameterIndex(szParam);
  892. bind(nParam, dwValue);
  893. }
  894. void CppSQLite3Statement::bind(const char* szParam, const unsigned char* blobValue, int nLen)
  895. {
  896. int nParam = bindParameterIndex(szParam);
  897. bind(nParam, blobValue, nLen);
  898. }
  899. void CppSQLite3Statement::bindNull(const char* szParam)
  900. {
  901. int nParam = bindParameterIndex(szParam);
  902. bindNull(nParam);
  903. }
  904. void CppSQLite3Statement::reset()
  905. {
  906. if (mpVM)
  907. {
  908. int nRet = sqlite3_reset(mpVM);
  909. if (nRet != SQLITE_OK)
  910. {
  911. const char* szError = sqlite3_errmsg(mpDB);
  912. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  913. }
  914. }
  915. }
  916. void CppSQLite3Statement::finalize()
  917. {
  918. if (mpVM)
  919. {
  920. int nRet = sqlite3_finalize(mpVM);
  921. mpVM = 0;
  922. if (nRet != SQLITE_OK)
  923. {
  924. const char* szError = sqlite3_errmsg(mpDB);
  925. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  926. }
  927. }
  928. }
  929. void CppSQLite3Statement::checkDB()
  930. {
  931. if (mpDB == 0)
  932. {
  933. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  934. "Database not open",
  935. DONT_DELETE_MSG);
  936. }
  937. }
  938. void CppSQLite3Statement::checkVM()
  939. {
  940. if (mpVM == 0)
  941. {
  942. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  943. "Null Virtual Machine pointer",
  944. DONT_DELETE_MSG);
  945. }
  946. }
  947. ////////////////////////////////////////////////////////////////////////////////
  948. CppSQLite3DB::CppSQLite3DB()
  949. {
  950. mpDB = 0;
  951. mnBusyTimeoutMs = 60000; // 60 seconds
  952. }
  953. CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB& db)
  954. {
  955. mpDB = db.mpDB;
  956. mnBusyTimeoutMs = 60000; // 60 seconds
  957. }
  958. CppSQLite3DB::~CppSQLite3DB()
  959. {
  960. try
  961. {
  962. close();
  963. }
  964. catch (...)
  965. {
  966. }
  967. }
  968. CppSQLite3DB& CppSQLite3DB::operator=(const CppSQLite3DB& db)
  969. {
  970. mpDB = db.mpDB;
  971. mnBusyTimeoutMs = 60000; // 60 seconds
  972. return *this;
  973. }
  974. int callback_db(void* ptr, int count)
  975. {
  976. Sleep(200);
  977. return 1;
  978. }
  979. void CppSQLite3DB::open(const char* szFile)
  980. {
  981. //int nRet = sqlite3_open(szFile, &mpDB);
  982. int nRet = sqlite3_open_v2(szFile, &mpDB,SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE|SQLITE_OPEN_FULLMUTEX,NULL);
  983. if (nRet != SQLITE_OK)
  984. {
  985. const char* szError = sqlite3_errmsg(mpDB);
  986. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  987. }
  988. m_strDbPath = szFile;
  989. //setBusyTimeout(mnBusyTimeoutMs);
  990. sqlite3_busy_handler(mpDB, callback_db, (void*)mpDB);
  991. }
  992. void CppSQLite3DB::close()
  993. {
  994. if (mpDB)
  995. {
  996. if (sqlite3_close(mpDB) == SQLITE_OK)
  997. {
  998. mpDB = 0;
  999. }
  1000. else
  1001. {
  1002. const char* szError = sqlite3_errmsg(mpDB);
  1003. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  1004. "Unable to close database",
  1005. DONT_DELETE_MSG);
  1006. }
  1007. }
  1008. }
  1009. CppSQLite3Statement CppSQLite3DB::compileStatement(const char* szSQL)
  1010. {
  1011. checkDB();
  1012. sqlite3_stmt* pVM = compile(szSQL);
  1013. return CppSQLite3Statement(mpDB, pVM);
  1014. }
  1015. bool CppSQLite3DB::tableExists(const char* szTable)
  1016. {
  1017. char szSQL[256];
  1018. sprintf(szSQL,
  1019. "select count(*) from sqlite_master where type='table' and name='%s'",
  1020. szTable);
  1021. int nRet = execScalar(szSQL);
  1022. return (nRet > 0);
  1023. }
  1024. int CppSQLite3DB::execDML(const char* szSQL)
  1025. {
  1026. checkDB();
  1027. char* szError=0;
  1028. int nRet = sqlite3_exec(mpDB, szSQL, 0, 0, &szError);
  1029. if (nRet == SQLITE_OK)
  1030. {
  1031. return sqlite3_changes(mpDB);
  1032. }
  1033. else
  1034. {
  1035. throw CppSQLite3Exception(nRet, szError);
  1036. }
  1037. }
  1038. CppSQLite3Query CppSQLite3DB::execQuery(const char* szSQL)
  1039. {
  1040. checkDB();
  1041. sqlite3_stmt* pVM = compile(szSQL);
  1042. int nRet = sqlite3_step(pVM);
  1043. if (nRet == SQLITE_DONE)
  1044. {
  1045. // no rows
  1046. return CppSQLite3Query(mpDB, pVM, true/*eof*/);
  1047. }
  1048. else if (nRet == SQLITE_ROW)
  1049. {
  1050. // at least 1 row
  1051. return CppSQLite3Query(mpDB, pVM, false/*eof*/);
  1052. }
  1053. else
  1054. {
  1055. nRet = sqlite3_finalize(pVM);
  1056. const char* szError= sqlite3_errmsg(mpDB);
  1057. throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
  1058. }
  1059. }
  1060. int CppSQLite3DB::execScalar(const char* szSQL, int nNullValue/*=0*/)
  1061. {
  1062. CppSQLite3Query q = execQuery(szSQL);
  1063. if (q.eof() || q.numFields() < 1)
  1064. {
  1065. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  1066. "Invalid scalar query",
  1067. DONT_DELETE_MSG);
  1068. }
  1069. return q.getIntField(0, nNullValue);
  1070. }
  1071. CppSQLite3Table CppSQLite3DB::getTable(const char* szSQL)
  1072. {
  1073. checkDB();
  1074. char* szError=0;
  1075. char** paszResults=0;
  1076. int nRet;
  1077. int nRows(0);
  1078. int nCols(0);
  1079. nRet = sqlite3_get_table(mpDB, szSQL, &paszResults, &nRows, &nCols, &szError);
  1080. if (nRet == SQLITE_OK)
  1081. {
  1082. return CppSQLite3Table(paszResults, nRows, nCols);
  1083. }
  1084. else
  1085. {
  1086. throw CppSQLite3Exception(nRet, szError);
  1087. }
  1088. }
  1089. sqlite_int64 CppSQLite3DB::lastRowId()
  1090. {
  1091. return sqlite3_last_insert_rowid(mpDB);
  1092. }
  1093. void CppSQLite3DB::setBusyTimeout(int nMillisecs)
  1094. {
  1095. mnBusyTimeoutMs = nMillisecs;
  1096. sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs);
  1097. }
  1098. void CppSQLite3DB::checkDB()
  1099. {
  1100. if (!mpDB)
  1101. {
  1102. throw CppSQLite3Exception(CPPSQLITE_ERROR,
  1103. "Database not open",
  1104. DONT_DELETE_MSG);
  1105. }
  1106. }
  1107. sqlite3_stmt* CppSQLite3DB::compile(const char* szSQL)
  1108. {
  1109. checkDB();
  1110. const char* szTail=0;
  1111. sqlite3_stmt* pVM;
  1112. int nRet = sqlite3_prepare_v2(mpDB, szSQL, -1, &pVM, &szTail);
  1113. if (nRet != SQLITE_OK)
  1114. {
  1115. const char* szError = sqlite3_errmsg(mpDB);
  1116. throw CppSQLite3Exception(nRet,
  1117. (char*)szError,
  1118. DONT_DELETE_MSG);
  1119. }
  1120. return pVM;
  1121. }
  1122. bool CppSQLite3DB::IsAutoCommitOn()
  1123. {
  1124. checkDB();
  1125. return sqlite3_get_autocommit(mpDB) ? true : false;
  1126. }
  1127. ////////////////////////////////////////////////////////////////////////////////
  1128. // SQLite encode.c reproduced here, containing implementation notes and source
  1129. // for sqlite3_encode_binary() and sqlite3_decode_binary()
  1130. ////////////////////////////////////////////////////////////////////////////////
  1131. /*
  1132. ** 2002 April 25
  1133. **
  1134. ** The author disclaims copyright to this source code. In place of
  1135. ** a legal notice, here is a blessing:
  1136. **
  1137. ** May you do good and not evil.
  1138. ** May you find forgiveness for yourself and forgive others.
  1139. ** May you share freely, never taking more than you give.
  1140. **
  1141. *************************************************************************
  1142. ** This file contains helper routines used to translate binary data into
  1143. ** a null-terminated string (suitable for use in SQLite) and back again.
  1144. ** These are convenience routines for use by people who want to store binary
  1145. ** data in an SQLite database. The code in this file is not used by any other
  1146. ** part of the SQLite library.
  1147. **
  1148. ** $Id: encode.c,v 1.10 2004/01/14 21:59:23 drh Exp $
  1149. */
  1150. /*
  1151. ** How This Encoder Works
  1152. **
  1153. ** The output is allowed to contain any character except 0x27 (') and
  1154. ** 0x00. This is accomplished by using an escape character to encode
  1155. ** 0x27 and 0x00 as a two-byte sequence. The escape character is always
  1156. ** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The
  1157. ** 0x27 character is encoded as the two byte sequence 0x01 0x03. Finally,
  1158. ** the escape character itself is encoded as the two-character sequence
  1159. ** 0x01 0x02.
  1160. **
  1161. ** To summarize, the encoder works by using an escape sequences as follows:
  1162. **
  1163. ** 0x00 -> 0x01 0x01
  1164. ** 0x01 -> 0x01 0x02
  1165. ** 0x27 -> 0x01 0x03
  1166. **
  1167. ** If that were all the encoder did, it would work, but in certain cases
  1168. ** it could double the size of the encoded string. For example, to
  1169. ** encode a string of 100 0x27 characters would require 100 instances of
  1170. ** the 0x01 0x03 escape sequence resulting in a 200-character output.
  1171. ** We would prefer to keep the size of the encoded string smaller than
  1172. ** this.
  1173. **
  1174. ** To minimize the encoding size, we first add a fixed offset value to each
  1175. ** byte in the sequence. The addition is modulo 256. (That is to say, if
  1176. ** the sum of the original character value and the offset exceeds 256, then
  1177. ** the higher order bits are truncated.) The offset is chosen to minimize
  1178. ** the number of characters in the string that need to be escaped. For
  1179. ** example, in the case above where the string was composed of 100 0x27
  1180. ** characters, the offset might be 0x01. Each of the 0x27 characters would
  1181. ** then be converted into an 0x28 character which would not need to be
  1182. ** escaped at all and so the 100 character input string would be converted
  1183. ** into just 100 characters of output. Actually 101 characters of output -
  1184. ** we have to record the offset used as the first byte in the sequence so
  1185. ** that the string can be decoded. Since the offset value is stored as
  1186. ** part of the output string and the output string is not allowed to contain
  1187. ** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
  1188. **
  1189. ** Here, then, are the encoding steps:
  1190. **
  1191. ** (1) Choose an offset value and make it the first character of
  1192. ** output.
  1193. **
  1194. ** (2) Copy each input character into the output buffer, one by
  1195. ** one, adding the offset value as you copy.
  1196. **
  1197. ** (3) If the value of an input character plus offset is 0x00, replace
  1198. ** that one character by the two-character sequence 0x01 0x01.
  1199. ** If the sum is 0x01, replace it with 0x01 0x02. If the sum
  1200. ** is 0x27, replace it with 0x01 0x03.
  1201. **
  1202. ** (4) Put a 0x00 terminator at the end of the output.
  1203. **
  1204. ** Decoding is obvious:
  1205. **
  1206. ** (5) Copy encoded characters except the first into the decode
  1207. ** buffer. Set the first encoded character aside for use as
  1208. ** the offset in step 7 below.
  1209. **
  1210. ** (6) Convert each 0x01 0x01 sequence into a single character 0x00.
  1211. ** Convert 0x01 0x02 into 0x01. Convert 0x01 0x03 into 0x27.
  1212. **
  1213. ** (7) Subtract the offset value that was the first character of
  1214. ** the encoded buffer from all characters in the output buffer.
  1215. **
  1216. ** The only tricky part is step (1) - how to compute an offset value to
  1217. ** minimize the size of the output buffer. This is accomplished by testing
  1218. ** all offset values and picking the one that results in the fewest number
  1219. ** of escapes. To do that, we first scan the entire input and count the
  1220. ** number of occurances of each character value in the input. Suppose
  1221. ** the number of 0x00 characters is N(0), the number of occurances of 0x01
  1222. ** is N(1), and so forth up to the number of occurances of 0xff is N(255).
  1223. ** An offset of 0 is not allowed so we don't have to test it. The number
  1224. ** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number
  1225. ** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth.
  1226. ** In this way we find the offset that gives the minimum number of escapes,
  1227. ** and thus minimizes the length of the output string.
  1228. */
  1229. /*
  1230. ** Encode a binary buffer "in" of size n bytes so that it contains
  1231. ** no instances of characters '\'' or '\000'. The output is
  1232. ** null-terminated and can be used as a string value in an INSERT
  1233. ** or UPDATE statement. Use sqlite3_decode_binary() to convert the
  1234. ** string back into its original binary.
  1235. **
  1236. ** The result is written into a preallocated output buffer "out".
  1237. ** "out" must be able to hold at least 2 +(257*n)/254 bytes.
  1238. ** In other words, the output will be expanded by as much as 3
  1239. ** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
  1240. ** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
  1241. **
  1242. ** The return value is the number of characters in the encoded
  1243. ** string, excluding the "\000" terminator.
  1244. */
  1245. int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){
  1246. int i, j, e, m;
  1247. int cnt[256];
  1248. if( n<=0 ){
  1249. out[0] = 'x';
  1250. out[1] = 0;
  1251. return 1;
  1252. }
  1253. memset(cnt, 0, sizeof(cnt));
  1254. for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
  1255. m = n;
  1256. for(i=1; i<256; i++){
  1257. int sum;
  1258. if( i=='\'' ) continue;
  1259. sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
  1260. if( sum<m ){
  1261. m = sum;
  1262. e = i;
  1263. if( m==0 ) break;
  1264. }
  1265. }
  1266. out[0] = e;
  1267. j = 1;
  1268. for(i=0; i<n; i++){
  1269. int c = (in[i] - e)&0xff;
  1270. if( c==0 ){
  1271. out[j++] = 1;
  1272. out[j++] = 1;
  1273. }else if( c==1 ){
  1274. out[j++] = 1;
  1275. out[j++] = 2;
  1276. }else if( c=='\'' ){
  1277. out[j++] = 1;
  1278. out[j++] = 3;
  1279. }else{
  1280. out[j++] = c;
  1281. }
  1282. }
  1283. out[j] = 0;
  1284. return j;
  1285. }
  1286. /*
  1287. ** Decode the string "in" into binary data and write it into "out".
  1288. ** This routine reverses the encoding created by sqlite3_encode_binary().
  1289. ** The output will always be a few bytes less than the input. The number
  1290. ** of bytes of output is returned. If the input is not a well-formed
  1291. ** encoding, -1 is returned.
  1292. **
  1293. ** The "in" and "out" parameters may point to the same buffer in order
  1294. ** to decode a string in place.
  1295. */
  1296. int sqlite3_decode_binary(const unsigned char *in, unsigned char *out){
  1297. int i, c, e;
  1298. e = *(in++);
  1299. i = 0;
  1300. while( (c = *(in++))!=0 ){
  1301. if( c==1 ){
  1302. c = *(in++);
  1303. if( c==1 ){
  1304. c = 0;
  1305. }else if( c==2 ){
  1306. c = 1;
  1307. }else if( c==3 ){
  1308. c = '\'';
  1309. }else{
  1310. return -1;
  1311. }
  1312. }
  1313. out[i++] = (c + e)&0xff;
  1314. }
  1315. return i;
  1316. }