CppSQLite3.cpp 33 KB

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