CppSQLite3.cpp 33 KB

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