]> Creatis software - creaImageIO.git/blob - src/CppSQLite3.cpp
#3185 creaImageIO Feature New Normal - Clean code
[creaImageIO.git] / src / CppSQLite3.cpp
1 ////////////////////////////////////////////////////////////////////////////////
2
3 // CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library.
4
5 //
6
7 // Copyright (c) 2004 Rob Groves. All Rights Reserved. rob.groves@btinternet.com
8
9 // 
10
11 // Permission to use, copy, modify, and distribute this software and its
12
13 // documentation for any purpose, without fee, and without a written
14
15 // agreement, is hereby granted, provided that the above copyright notice, 
16
17 // this paragraph and the following two paragraphs appear in all copies, 
18
19 // modifications, and distributions.
20
21 //
22
23 // IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
24
25 // INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
26
27 // PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
28
29 // EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 //
32
33 // THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
34
35 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
36
37 // PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
38
39 // ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
40
41 // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
42
43 //
44
45 // V3.0         03/08/2004      -Initial Version for sqlite3
46
47 //
48
49 // V3.1         16/09/2004      -Implemented getXXXXField using sqlite3 functions
50
51 //                                              -Added CppSQLiteDB3::tableExists()
52
53 ////////////////////////////////////////////////////////////////////////////////
54
55 #include "CppSQLite3.h"
56
57 #include <cstdlib>
58
59
60
61
62
63 // Named constant for passing to CppSQLite3Exception when passing it a string
64
65 // that cannot be deleted.
66
67 static const bool DONT_DELETE_MSG=false;
68
69
70
71 ////////////////////////////////////////////////////////////////////////////////
72
73 // Prototypes for SQLite functions not included in SQLite DLL, but copied below
74
75 // from SQLite encode.c
76
77 ////////////////////////////////////////////////////////////////////////////////
78
79 int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out);
80
81 int sqlite3_decode_binary(const unsigned char *in, unsigned char *out);
82
83
84
85 ////////////////////////////////////////////////////////////////////////////////
86
87
88
89 ////////////////////////////////////////////////////////////////////////////////
90
91
92
93 CppSQLite3Exception::CppSQLite3Exception(const int nErrCode,
94
95                                          const char* szErrMess,
96
97                                          bool bDeleteMsg/*=true*/) :
98
99   mnErrCode(nErrCode)
100
101 {
102
103   mpszErrMess = sqlite3_mprintf("%s[%d]: %s",
104
105                                 errorCodeAsString(nErrCode),
106
107                                 nErrCode,
108
109                                 szErrMess ? szErrMess : "");
110
111   /*
112
113   if (bDeleteMsg && szErrMess)
114
115     {
116
117       sqlite3_free(szErrMess);
118
119     }
120
121   */
122
123 }
124
125
126
127 CppSQLite3Exception::CppSQLite3Exception(const int nErrCode,
128
129                                          char* szErrMess,
130
131                                          bool bDeleteMsg/*=true*/) :
132
133   mnErrCode(nErrCode)
134
135 {
136
137   mpszErrMess = sqlite3_mprintf("%s[%d]: %s",
138
139                                 errorCodeAsString(nErrCode),
140
141                                 nErrCode,
142
143                                 szErrMess ? szErrMess : "");
144
145   
146
147   if (bDeleteMsg && szErrMess)
148
149     {
150
151       sqlite3_free(szErrMess);
152
153     }
154
155 }
156
157                                                                         
158
159 CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception&  e) :
160
161                                                                         mnErrCode(e.mnErrCode)
162
163 {
164
165         mpszErrMess = 0;
166
167         if (e.mpszErrMess)
168
169         {
170
171                 mpszErrMess = sqlite3_mprintf("%s", e.mpszErrMess);
172
173         }
174
175 }
176
177
178
179
180
181 const char* CppSQLite3Exception::errorCodeAsString(int nErrCode)
182
183 {
184
185         switch (nErrCode)
186
187         {
188
189                 case SQLITE_OK          : return "SQLITE_OK";
190
191                 case SQLITE_ERROR       : return "SQLITE_ERROR";
192
193                 case SQLITE_INTERNAL    : return "SQLITE_INTERNAL";
194
195                 case SQLITE_PERM        : return "SQLITE_PERM";
196
197                 case SQLITE_ABORT       : return "SQLITE_ABORT";
198
199                 case SQLITE_BUSY        : return "SQLITE_BUSY";
200
201                 case SQLITE_LOCKED      : return "SQLITE_LOCKED";
202
203                 case SQLITE_NOMEM       : return "SQLITE_NOMEM";
204
205                 case SQLITE_READONLY    : return "SQLITE_READONLY";
206
207                 case SQLITE_INTERRUPT   : return "SQLITE_INTERRUPT";
208
209                 case SQLITE_IOERR       : return "SQLITE_IOERR";
210
211                 case SQLITE_CORRUPT     : return "SQLITE_CORRUPT";
212
213                 case SQLITE_NOTFOUND    : return "SQLITE_NOTFOUND";
214
215                 case SQLITE_FULL        : return "SQLITE_FULL";
216
217                 case SQLITE_CANTOPEN    : return "SQLITE_CANTOPEN";
218
219                 case SQLITE_PROTOCOL    : return "SQLITE_PROTOCOL";
220
221                 case SQLITE_EMPTY       : return "SQLITE_EMPTY";
222
223                 case SQLITE_SCHEMA      : return "SQLITE_SCHEMA";
224
225                 case SQLITE_TOOBIG      : return "SQLITE_TOOBIG";
226
227                 case SQLITE_CONSTRAINT  : return "SQLITE_CONSTRAINT";
228
229                 case SQLITE_MISMATCH    : return "SQLITE_MISMATCH";
230
231                 case SQLITE_MISUSE      : return "SQLITE_MISUSE";
232
233                 case SQLITE_NOLFS       : return "SQLITE_NOLFS";
234
235                 case SQLITE_AUTH        : return "SQLITE_AUTH";
236
237                 case SQLITE_FORMAT      : return "SQLITE_FORMAT";
238
239                 case SQLITE_RANGE       : return "SQLITE_RANGE";
240
241                 case SQLITE_ROW         : return "SQLITE_ROW";
242
243                 case SQLITE_DONE        : return "SQLITE_DONE";
244
245                 case CPPSQLITE_ERROR    : return "CPPSQLITE_ERROR";
246
247                 default: return "UNKNOWN_ERROR";
248
249         }
250
251 }
252
253
254
255
256
257 CppSQLite3Exception::~CppSQLite3Exception()
258
259 {
260
261         if (mpszErrMess)
262
263         {
264
265                 sqlite3_free(mpszErrMess);
266
267                 mpszErrMess = 0;
268
269         }
270
271 }
272
273
274
275
276
277 ////////////////////////////////////////////////////////////////////////////////
278
279
280
281 CppSQLite3Buffer::CppSQLite3Buffer()
282
283 {
284
285         mpBuf = 0;
286
287 }
288
289
290
291
292
293 CppSQLite3Buffer::~CppSQLite3Buffer()
294
295 {
296
297         clear();
298
299 }
300
301
302
303
304
305 void CppSQLite3Buffer::clear()
306
307 {
308
309         if (mpBuf)
310
311         {
312
313                 sqlite3_free(mpBuf);
314
315                 mpBuf = 0;
316
317         }
318
319
320
321 }
322
323
324
325
326
327 const char* CppSQLite3Buffer::format(const char* szFormat, ...)
328
329 {
330
331         clear();
332
333         va_list va;
334
335         va_start(va, szFormat);
336
337         mpBuf = sqlite3_vmprintf(szFormat, va);
338
339         va_end(va);
340
341         return mpBuf;
342
343 }
344
345
346
347
348
349 ////////////////////////////////////////////////////////////////////////////////
350
351
352
353 CppSQLite3Binary::CppSQLite3Binary() :
354
355                                                 mpBuf(0),
356
357                                                 mnBinaryLen(0),
358
359                                                 mnBufferLen(0),
360
361                                                 mnEncodedLen(0),
362
363                                                 mbEncoded(false)
364
365 {
366
367 }
368
369
370
371
372
373 CppSQLite3Binary::~CppSQLite3Binary()
374
375 {
376
377         clear();
378
379 }
380
381
382
383
384
385 void CppSQLite3Binary::setBinary(const unsigned char* pBuf, int nLen)
386
387 {
388
389         mpBuf = allocBuffer(nLen);
390
391         memcpy(mpBuf, pBuf, nLen);
392
393 }
394
395
396
397
398
399 void CppSQLite3Binary::setEncoded(const unsigned char* pBuf)
400
401 {
402
403         clear();
404
405
406
407         mnEncodedLen = strlen((const char*)pBuf);
408
409         mnBufferLen = mnEncodedLen + 1; // Allow for NULL terminator
410
411
412
413         mpBuf = (unsigned char*)malloc(mnBufferLen);
414
415
416
417         if (!mpBuf)
418
419         {
420
421                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
422
423                                                                 "Cannot allocate memory",
424
425                                                                 DONT_DELETE_MSG);
426
427         }
428
429
430
431         memcpy(mpBuf, pBuf, mnBufferLen);
432
433         mbEncoded = true;
434
435 }
436
437
438
439
440
441 const unsigned char* CppSQLite3Binary::getEncoded()
442
443 {
444
445         if (!mbEncoded)
446
447         {
448
449                 unsigned char* ptmp = (unsigned char*)malloc(mnBinaryLen);
450
451                 memcpy(ptmp, mpBuf, mnBinaryLen);
452
453                 mnEncodedLen = sqlite3_encode_binary(ptmp, mnBinaryLen, mpBuf);
454
455                 free(ptmp);
456
457                 mbEncoded = true;
458
459         }
460
461
462
463         return mpBuf;
464
465 }
466
467
468
469
470
471 const unsigned char* CppSQLite3Binary::getBinary()
472
473 {
474
475         if (mbEncoded)
476
477         {
478
479                 // in/out buffers can be the same
480
481                 mnBinaryLen = sqlite3_decode_binary(mpBuf, mpBuf);
482
483
484
485                 if (mnBinaryLen == -1)
486
487                 {
488
489                         throw CppSQLite3Exception(CPPSQLITE_ERROR,
490
491                                                                         "Cannot decode binary",
492
493                                                                         DONT_DELETE_MSG);
494
495                 }
496
497
498
499                 mbEncoded = false;
500
501         }
502
503
504
505         return mpBuf;
506
507 }
508
509
510
511
512
513 int CppSQLite3Binary::getBinaryLength()
514
515 {
516
517         getBinary();
518
519         return mnBinaryLen;
520
521 }
522
523
524
525
526
527 unsigned char* CppSQLite3Binary::allocBuffer(int nLen)
528
529 {
530
531         clear();
532
533
534
535         // Allow extra space for encoded binary as per comments in
536
537         // SQLite encode.c See bottom of this file for implementation
538
539         // of SQLite functions use 3 instead of 2 just to be sure ;-)
540
541         mnBinaryLen = nLen;
542
543         mnBufferLen = 3 + (257*nLen)/254;
544
545
546
547         mpBuf = (unsigned char*)malloc(mnBufferLen);
548
549
550
551         if (!mpBuf)
552
553         {
554
555                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
556
557                                                                 "Cannot allocate memory",
558
559                                                                 DONT_DELETE_MSG);
560
561         }
562
563
564
565         mbEncoded = false;
566
567
568
569         return mpBuf;
570
571 }
572
573
574
575
576
577 void CppSQLite3Binary::clear()
578
579 {
580
581         if (mpBuf)
582
583         {
584
585                 mnBinaryLen = 0;
586
587                 mnBufferLen = 0;
588
589                 free(mpBuf);
590
591                 mpBuf = 0;
592
593         }
594
595 }
596
597
598
599
600
601 ////////////////////////////////////////////////////////////////////////////////
602
603
604
605 CppSQLite3Query::CppSQLite3Query()
606
607 {
608
609         mpVM = 0;
610
611         mbEof = true;
612
613         mnCols = 0;
614
615         mbOwnVM = false;
616
617 }
618
619
620
621
622
623 CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query& rQuery)
624
625 {
626
627         mpVM = rQuery.mpVM;
628
629         // Only one object can own the VM
630
631         const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
632
633         mbEof = rQuery.mbEof;
634
635         mnCols = rQuery.mnCols;
636
637         mbOwnVM = rQuery.mbOwnVM;
638
639 }
640
641
642
643
644
645 CppSQLite3Query::CppSQLite3Query(sqlite3* pDB,
646
647                                                         sqlite3_stmt* pVM,
648
649                                                         bool bEof,
650
651                                                         bool bOwnVM/*=true*/)
652
653 {
654
655         mpDB = pDB;
656
657         mpVM = pVM;
658
659         mbEof = bEof;
660
661         mnCols = sqlite3_column_count(mpVM);
662
663         mbOwnVM = bOwnVM;
664
665 }
666
667
668
669
670
671 CppSQLite3Query::~CppSQLite3Query()
672
673 {
674
675         try
676
677         {
678
679                 finalize();
680
681         }
682
683         catch (...)
684
685         {
686
687         }
688
689 }
690
691
692
693
694
695 CppSQLite3Query& CppSQLite3Query::operator=(const CppSQLite3Query& rQuery)
696
697 {
698
699         try
700
701         {
702
703                 finalize();
704
705         }
706
707         catch (...)
708
709         {
710
711         }
712
713         mpVM = rQuery.mpVM;
714
715         // Only one object can own the VM
716
717         const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
718
719         mbEof = rQuery.mbEof;
720
721         mnCols = rQuery.mnCols;
722
723         mbOwnVM = rQuery.mbOwnVM;
724
725         return *this;
726
727 }
728
729
730
731
732
733 int CppSQLite3Query::numFields()
734
735 {
736
737         checkVM();
738
739         return mnCols;
740
741 }
742
743
744
745
746
747 const char* CppSQLite3Query::fieldValue(int nField)
748
749 {
750
751         checkVM();
752
753
754
755         if (nField < 0 || nField > mnCols-1)
756
757         {
758
759                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
760
761                                                                 "Invalid field index requested",
762
763                                                                 DONT_DELETE_MSG);
764
765         }
766
767
768
769         return (const char*)sqlite3_column_text(mpVM, nField);
770
771 }
772
773
774
775
776
777 const char* CppSQLite3Query::fieldValue(const char* szField)
778
779 {
780
781         int nField = fieldIndex(szField);
782
783         return (const char*)sqlite3_column_text(mpVM, nField);
784
785 }
786
787
788
789
790
791 int CppSQLite3Query::getIntField(int nField, int nNullValue/*=0*/)
792
793 {
794
795         if (fieldDataType(nField) == SQLITE_NULL)
796
797         {
798
799                 return nNullValue;
800
801         }
802
803         else
804
805         {
806
807                 return sqlite3_column_int(mpVM, nField);
808
809         }
810
811 }
812
813
814
815
816
817 int CppSQLite3Query::getIntField(const char* szField, int nNullValue/*=0*/)
818
819 {
820
821         int nField = fieldIndex(szField);
822
823         return getIntField(nField, nNullValue);
824
825 }
826
827
828
829
830
831 double CppSQLite3Query::getFloatField(int nField, double fNullValue/*=0.0*/)
832
833 {
834
835         if (fieldDataType(nField) == SQLITE_NULL)
836
837         {
838
839                 return fNullValue;
840
841         }
842
843         else
844
845         {
846
847                 return sqlite3_column_double(mpVM, nField);
848
849         }
850
851 }
852
853
854
855
856
857 double CppSQLite3Query::getFloatField(const char* szField, double fNullValue/*=0.0*/)
858
859 {
860
861         int nField = fieldIndex(szField);
862
863         return getFloatField(nField, fNullValue);
864
865 }
866
867
868
869
870
871 const char* CppSQLite3Query::getStringField(int nField, const char* szNullValue/*=""*/)
872
873 {
874
875         if (fieldDataType(nField) == SQLITE_NULL)
876
877         {
878
879                 return szNullValue;
880
881         }
882
883         else
884
885         {
886
887                 return (const char*)sqlite3_column_text(mpVM, nField);
888
889         }
890
891 }
892
893
894
895
896
897 const char* CppSQLite3Query::getStringField(const char* szField, const char* szNullValue/*=""*/)
898
899 {
900
901         int nField = fieldIndex(szField);
902
903         return getStringField(nField, szNullValue);
904
905 }
906
907
908
909
910
911 const unsigned char* CppSQLite3Query::getBlobField(int nField, int& nLen)
912
913 {
914
915         checkVM();
916
917
918
919         if (nField < 0 || nField > mnCols-1)
920
921         {
922
923                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
924
925                                                                 "Invalid field index requested",
926
927                                                                 DONT_DELETE_MSG);
928
929         }
930
931
932
933         nLen = sqlite3_column_bytes(mpVM, nField);
934
935         return (const unsigned char*)sqlite3_column_blob(mpVM, nField);
936
937 }
938
939
940
941
942
943 const unsigned char* CppSQLite3Query::getBlobField(const char* szField, int& nLen)
944
945 {
946
947         int nField = fieldIndex(szField);
948
949         return getBlobField(nField, nLen);
950
951 }
952
953
954
955
956
957 bool CppSQLite3Query::fieldIsNull(int nField)
958
959 {
960
961         return (fieldDataType(nField) == SQLITE_NULL);
962
963 }
964
965
966
967
968
969 bool CppSQLite3Query::fieldIsNull(const char* szField)
970
971 {
972
973         int nField = fieldIndex(szField);
974
975         return (fieldDataType(nField) == SQLITE_NULL);
976
977 }
978
979
980
981
982
983 int CppSQLite3Query::fieldIndex(const char* szField)
984
985 {
986
987         checkVM();
988
989
990
991         if (szField)
992
993         {
994
995                 for (int nField = 0; nField < mnCols; nField++)
996
997                 {
998
999                         const char* szTemp = sqlite3_column_name(mpVM, nField);
1000
1001
1002
1003                         if (strcmp(szField, szTemp) == 0)
1004
1005                         {
1006
1007                                 return nField;
1008
1009                         }
1010
1011                 }
1012
1013         }
1014
1015
1016
1017         throw CppSQLite3Exception(CPPSQLITE_ERROR,
1018
1019                                                         "Invalid field name requested",
1020
1021                                                         DONT_DELETE_MSG);
1022
1023 }
1024
1025
1026
1027
1028
1029 const char* CppSQLite3Query::fieldName(int nCol)
1030
1031 {
1032
1033         checkVM();
1034
1035
1036
1037         if (nCol < 0 || nCol > mnCols-1)
1038
1039         {
1040
1041                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1042
1043                                                                 "Invalid field index requested",
1044
1045                                                                 DONT_DELETE_MSG);
1046
1047         }
1048
1049
1050
1051         return sqlite3_column_name(mpVM, nCol);
1052
1053 }
1054
1055
1056
1057
1058
1059 const char* CppSQLite3Query::fieldDeclType(int nCol)
1060
1061 {
1062
1063         checkVM();
1064
1065
1066
1067         if (nCol < 0 || nCol > mnCols-1)
1068
1069         {
1070
1071                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1072
1073                                                                 "Invalid field index requested",
1074
1075                                                                 DONT_DELETE_MSG);
1076
1077         }
1078
1079
1080
1081         return sqlite3_column_decltype(mpVM, nCol);
1082
1083 }
1084
1085
1086
1087
1088
1089 int CppSQLite3Query::fieldDataType(int nCol)
1090
1091 {
1092
1093         checkVM();
1094
1095
1096
1097         if (nCol < 0 || nCol > mnCols-1)
1098
1099         {
1100
1101                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1102
1103                                                                 "Invalid field index requested",
1104
1105                                                                 DONT_DELETE_MSG);
1106
1107         }
1108
1109
1110
1111         return sqlite3_column_type(mpVM, nCol);
1112
1113 }
1114
1115
1116
1117
1118
1119 bool CppSQLite3Query::eof()
1120
1121 {
1122
1123         checkVM();
1124
1125         return mbEof;
1126
1127 }
1128
1129
1130
1131
1132
1133 void CppSQLite3Query::nextRow()
1134
1135 {
1136
1137         checkVM();
1138
1139
1140
1141         int nRet = sqlite3_step(mpVM);
1142
1143
1144
1145         if (nRet == SQLITE_DONE)
1146
1147         {
1148
1149                 // no rows
1150
1151                 mbEof = true;
1152
1153         }
1154
1155         else if (nRet == SQLITE_ROW)
1156
1157         {
1158
1159                 // more rows, nothing to do
1160
1161         }
1162
1163         else
1164
1165         {
1166
1167                 nRet = sqlite3_finalize(mpVM);
1168
1169                 mpVM = 0;
1170
1171                 const char* szError = sqlite3_errmsg(mpDB);
1172
1173                 throw CppSQLite3Exception(nRet,
1174
1175                                                                 (char*)szError,
1176
1177                                                                 DONT_DELETE_MSG);
1178
1179         }
1180
1181 }
1182
1183
1184
1185
1186
1187 void CppSQLite3Query::finalize()
1188
1189 {
1190
1191         if (mpVM && mbOwnVM)
1192
1193         {
1194
1195                 int nRet = sqlite3_finalize(mpVM);
1196
1197                 mpVM = 0;
1198
1199                 if (nRet != SQLITE_OK)
1200
1201                 {
1202
1203                         const char* szError = sqlite3_errmsg(mpDB);
1204
1205                         throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
1206
1207                 }
1208
1209         }
1210
1211 }
1212
1213
1214
1215
1216
1217 void CppSQLite3Query::checkVM()
1218
1219 {
1220
1221         if (mpVM == 0)
1222
1223         {
1224
1225                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1226
1227                                                                 "Null Virtual Machine pointer",
1228
1229                                                                 DONT_DELETE_MSG);
1230
1231         }
1232
1233 }
1234
1235
1236
1237
1238
1239 ////////////////////////////////////////////////////////////////////////////////
1240
1241
1242
1243 CppSQLite3Table::CppSQLite3Table()
1244
1245 {
1246
1247         mpaszResults = 0;
1248
1249         mnRows = 0;
1250
1251         mnCols = 0;
1252
1253         mnCurrentRow = 0;
1254
1255 }
1256
1257
1258
1259
1260
1261 CppSQLite3Table::CppSQLite3Table(const CppSQLite3Table& rTable)
1262
1263 {
1264
1265         mpaszResults = rTable.mpaszResults;
1266
1267         // Only one object can own the results
1268
1269         const_cast<CppSQLite3Table&>(rTable).mpaszResults = 0;
1270
1271         mnRows = rTable.mnRows;
1272
1273         mnCols = rTable.mnCols;
1274
1275         mnCurrentRow = rTable.mnCurrentRow;
1276
1277 }
1278
1279
1280
1281
1282
1283 CppSQLite3Table::CppSQLite3Table(char** paszResults, int nRows, int nCols)
1284
1285 {
1286
1287         mpaszResults = paszResults;
1288
1289         mnRows = nRows;
1290
1291         mnCols = nCols;
1292
1293         mnCurrentRow = 0;
1294
1295 }
1296
1297
1298
1299
1300
1301 CppSQLite3Table::~CppSQLite3Table()
1302
1303 {
1304
1305         try
1306
1307         {
1308
1309                 finalize();
1310
1311         }
1312
1313         catch (...)
1314
1315         {
1316
1317         }
1318
1319 }
1320
1321
1322
1323
1324
1325 CppSQLite3Table& CppSQLite3Table::operator=(const CppSQLite3Table& rTable)
1326
1327 {
1328
1329         try
1330
1331         {
1332
1333                 finalize();
1334
1335         }
1336
1337         catch (...)
1338
1339         {
1340
1341         }
1342
1343         mpaszResults = rTable.mpaszResults;
1344
1345         // Only one object can own the results
1346
1347         const_cast<CppSQLite3Table&>(rTable).mpaszResults = 0;
1348
1349         mnRows = rTable.mnRows;
1350
1351         mnCols = rTable.mnCols;
1352
1353         mnCurrentRow = rTable.mnCurrentRow;
1354
1355         return *this;
1356
1357 }
1358
1359
1360
1361
1362
1363 void CppSQLite3Table::finalize()
1364
1365 {
1366
1367         if (mpaszResults)
1368
1369         {
1370
1371                 sqlite3_free_table(mpaszResults);
1372
1373                 mpaszResults = 0;
1374
1375         }
1376
1377 }
1378
1379
1380
1381
1382
1383 int CppSQLite3Table::numFields()
1384
1385 {
1386
1387         checkResults();
1388
1389         return mnCols;
1390
1391 }
1392
1393
1394
1395
1396
1397 int CppSQLite3Table::numRows()
1398
1399 {
1400
1401         checkResults();
1402
1403         return mnRows;
1404
1405 }
1406
1407
1408
1409
1410
1411 const char* CppSQLite3Table::fieldValue(int nField)
1412
1413 {
1414
1415         checkResults();
1416
1417
1418
1419         if (nField < 0 || nField > mnCols-1)
1420
1421         {
1422
1423                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1424
1425                                                                 "Invalid field index requested",
1426
1427                                                                 DONT_DELETE_MSG);
1428
1429         }
1430
1431
1432
1433         int nIndex = (mnCurrentRow*mnCols) + mnCols + nField;
1434
1435         return mpaszResults[nIndex];
1436
1437 }
1438
1439
1440
1441
1442
1443 const char* CppSQLite3Table::fieldValue(const char* szField)
1444
1445 {
1446
1447         checkResults();
1448
1449
1450
1451         if (szField)
1452
1453         {
1454
1455                 for (int nField = 0; nField < mnCols; nField++)
1456
1457                 {
1458
1459                         if (strcmp(szField, mpaszResults[nField]) == 0)
1460
1461                         {
1462
1463                                 int nIndex = (mnCurrentRow*mnCols) + mnCols + nField;
1464
1465                                 return mpaszResults[nIndex];
1466
1467                         }
1468
1469                 }
1470
1471         }
1472
1473
1474
1475         throw CppSQLite3Exception(CPPSQLITE_ERROR,
1476
1477                                                         "Invalid field name requested",
1478
1479                                                         DONT_DELETE_MSG);
1480
1481 }
1482
1483
1484
1485
1486
1487 int CppSQLite3Table::getIntField(int nField, int nNullValue/*=0*/)
1488
1489 {
1490
1491         if (fieldIsNull(nField))
1492
1493         {
1494
1495                 return nNullValue;
1496
1497         }
1498
1499         else
1500
1501         {
1502
1503                 return atoi(fieldValue(nField));
1504
1505         }
1506
1507 }
1508
1509
1510
1511
1512
1513 int CppSQLite3Table::getIntField(const char* szField, int nNullValue/*=0*/)
1514
1515 {
1516
1517         if (fieldIsNull(szField))
1518
1519         {
1520
1521                 return nNullValue;
1522
1523         }
1524
1525         else
1526
1527         {
1528
1529                 return atoi(fieldValue(szField));
1530
1531         }
1532
1533 }
1534
1535
1536
1537
1538
1539 double CppSQLite3Table::getFloatField(int nField, double fNullValue/*=0.0*/)
1540
1541 {
1542
1543         if (fieldIsNull(nField))
1544
1545         {
1546
1547                 return fNullValue;
1548
1549         }
1550
1551         else
1552
1553         {
1554
1555                 return atof(fieldValue(nField));
1556
1557         }
1558
1559 }
1560
1561
1562
1563
1564
1565 double CppSQLite3Table::getFloatField(const char* szField, double fNullValue/*=0.0*/)
1566
1567 {
1568
1569         if (fieldIsNull(szField))
1570
1571         {
1572
1573                 return fNullValue;
1574
1575         }
1576
1577         else
1578
1579         {
1580
1581                 return atof(fieldValue(szField));
1582
1583         }
1584
1585 }
1586
1587
1588
1589
1590
1591 const char* CppSQLite3Table::getStringField(int nField, const char* szNullValue/*=""*/)
1592
1593 {
1594
1595         if (fieldIsNull(nField))
1596
1597         {
1598
1599                 return szNullValue;
1600
1601         }
1602
1603         else
1604
1605         {
1606
1607                 return fieldValue(nField);
1608
1609         }
1610
1611 }
1612
1613
1614
1615
1616
1617 const char* CppSQLite3Table::getStringField(const char* szField, const char* szNullValue/*=""*/)
1618
1619 {
1620
1621         if (fieldIsNull(szField))
1622
1623         {
1624
1625                 return szNullValue;
1626
1627         }
1628
1629         else
1630
1631         {
1632
1633                 return fieldValue(szField);
1634
1635         }
1636
1637 }
1638
1639
1640
1641
1642
1643 bool CppSQLite3Table::fieldIsNull(int nField)
1644
1645 {
1646
1647         checkResults();
1648
1649         return (fieldValue(nField) == 0);
1650
1651 }
1652
1653
1654
1655
1656
1657 bool CppSQLite3Table::fieldIsNull(const char* szField)
1658
1659 {
1660
1661         checkResults();
1662
1663         return (fieldValue(szField) == 0);
1664
1665 }
1666
1667
1668
1669
1670
1671 const char* CppSQLite3Table::fieldName(int nCol)
1672
1673 {
1674
1675         checkResults();
1676
1677
1678
1679         if (nCol < 0 || nCol > mnCols-1)
1680
1681         {
1682
1683                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1684
1685                                                                 "Invalid field index requested",
1686
1687                                                                 DONT_DELETE_MSG);
1688
1689         }
1690
1691
1692
1693         return mpaszResults[nCol];
1694
1695 }
1696
1697
1698
1699
1700
1701 void CppSQLite3Table::setRow(int nRow)
1702
1703 {
1704
1705         checkResults();
1706
1707
1708
1709         if (nRow < 0 || nRow > mnRows-1)
1710
1711         {
1712
1713                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1714
1715                                                                 "Invalid row index requested",
1716
1717                                                                 DONT_DELETE_MSG);
1718
1719         }
1720
1721
1722
1723         mnCurrentRow = nRow;
1724
1725 }
1726
1727
1728
1729
1730
1731 void CppSQLite3Table::checkResults()
1732
1733 {
1734
1735         if (mpaszResults == 0)
1736
1737         {
1738
1739                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
1740
1741                                                                 "Null Results pointer",
1742
1743                                                                 DONT_DELETE_MSG);
1744
1745         }
1746
1747 }
1748
1749
1750
1751
1752
1753 ////////////////////////////////////////////////////////////////////////////////
1754
1755
1756
1757 CppSQLite3Statement::CppSQLite3Statement()
1758
1759 {
1760
1761         mpDB = 0;
1762
1763         mpVM = 0;
1764
1765 }
1766
1767
1768
1769
1770
1771 CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement& rStatement)
1772
1773 {
1774
1775         mpDB = rStatement.mpDB;
1776
1777         mpVM = rStatement.mpVM;
1778
1779         // Only one object can own VM
1780
1781         const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
1782
1783 }
1784
1785
1786
1787
1788
1789 CppSQLite3Statement::CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM)
1790
1791 {
1792
1793         mpDB = pDB;
1794
1795         mpVM = pVM;
1796
1797 }
1798
1799
1800
1801
1802
1803 CppSQLite3Statement::~CppSQLite3Statement()
1804
1805 {
1806
1807         try
1808
1809         {
1810
1811                 finalize();
1812
1813         }
1814
1815         catch (...)
1816
1817         {
1818
1819         }
1820
1821 }
1822
1823
1824
1825
1826
1827 CppSQLite3Statement& CppSQLite3Statement::operator=(const CppSQLite3Statement& rStatement)
1828
1829 {
1830
1831         mpDB = rStatement.mpDB;
1832
1833         mpVM = rStatement.mpVM;
1834
1835         // Only one object can own VM
1836
1837         const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
1838
1839         return *this;
1840
1841 }
1842
1843
1844
1845
1846
1847 int CppSQLite3Statement::execDML()
1848
1849 {
1850
1851         checkDB();
1852
1853         checkVM();
1854
1855
1856
1857         const char* szError=0;
1858
1859
1860
1861         int nRet = sqlite3_step(mpVM);
1862
1863
1864
1865         if (nRet == SQLITE_DONE)
1866
1867         {
1868
1869                 int nRowsChanged = sqlite3_changes(mpDB);
1870
1871
1872
1873                 nRet = sqlite3_reset(mpVM);
1874
1875
1876
1877                 if (nRet != SQLITE_OK)
1878
1879                 {
1880
1881                         szError = sqlite3_errmsg(mpDB);
1882
1883                         throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
1884
1885                 }
1886
1887
1888
1889                 return nRowsChanged;
1890
1891         }
1892
1893         else
1894
1895         {
1896
1897                 nRet = sqlite3_reset(mpVM);
1898
1899                 szError = sqlite3_errmsg(mpDB);
1900
1901                 throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
1902
1903         }
1904
1905 }
1906
1907
1908
1909
1910
1911 CppSQLite3Query CppSQLite3Statement::execQuery()
1912
1913 {
1914
1915         checkDB();
1916
1917         checkVM();
1918
1919
1920
1921         int nRet = sqlite3_step(mpVM);
1922
1923
1924
1925         if (nRet == SQLITE_DONE)
1926
1927         {
1928
1929                 // no rows
1930
1931                 return CppSQLite3Query(mpDB, mpVM, true/*eof*/, false);
1932
1933         }
1934
1935         else if (nRet == SQLITE_ROW)
1936
1937         {
1938
1939                 // at least 1 row
1940
1941                 return CppSQLite3Query(mpDB, mpVM, false/*eof*/, false);
1942
1943         }
1944
1945         else
1946
1947         {
1948
1949                 nRet = sqlite3_reset(mpVM);
1950
1951                 const char* szError = sqlite3_errmsg(mpDB);
1952
1953                 throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
1954
1955         }
1956
1957 }
1958
1959
1960
1961
1962
1963 void CppSQLite3Statement::bind(int nParam, const char* szValue)
1964
1965 {
1966
1967         checkVM();
1968
1969         int nRes = sqlite3_bind_text(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT);
1970
1971
1972
1973         if (nRes != SQLITE_OK)
1974
1975         {
1976
1977                 throw CppSQLite3Exception(nRes,
1978
1979                                                                 "Error binding string param",
1980
1981                                                                 DONT_DELETE_MSG);
1982
1983         }
1984
1985 }
1986
1987
1988
1989
1990
1991 void CppSQLite3Statement::bind(int nParam, const int nValue)
1992
1993 {
1994
1995         checkVM();
1996
1997         int nRes = sqlite3_bind_int(mpVM, nParam, nValue);
1998
1999
2000
2001         if (nRes != SQLITE_OK)
2002
2003         {
2004
2005                 throw CppSQLite3Exception(nRes,
2006
2007                                                                 "Error binding int param",
2008
2009                                                                 DONT_DELETE_MSG);
2010
2011         }
2012
2013 }
2014
2015
2016
2017
2018
2019 void CppSQLite3Statement::bind(int nParam, const double dValue)
2020
2021 {
2022
2023         checkVM();
2024
2025         int nRes = sqlite3_bind_double(mpVM, nParam, dValue);
2026
2027
2028
2029         if (nRes != SQLITE_OK)
2030
2031         {
2032
2033                 throw CppSQLite3Exception(nRes,
2034
2035                                                                 "Error binding double param",
2036
2037                                                                 DONT_DELETE_MSG);
2038
2039         }
2040
2041 }
2042
2043
2044
2045
2046
2047 void CppSQLite3Statement::bind(int nParam, const unsigned char* blobValue, int nLen)
2048
2049 {
2050
2051         checkVM();
2052
2053         int nRes = sqlite3_bind_blob(mpVM, nParam,
2054
2055                                                                 (const void*)blobValue, nLen, SQLITE_TRANSIENT);
2056
2057
2058
2059         if (nRes != SQLITE_OK)
2060
2061         {
2062
2063                 throw CppSQLite3Exception(nRes,
2064
2065                                                                 "Error binding blob param",
2066
2067                                                                 DONT_DELETE_MSG);
2068
2069         }
2070
2071 }
2072
2073
2074
2075         
2076
2077 void CppSQLite3Statement::bindNull(int nParam)
2078
2079 {
2080
2081         checkVM();
2082
2083         int nRes = sqlite3_bind_null(mpVM, nParam);
2084
2085
2086
2087         if (nRes != SQLITE_OK)
2088
2089         {
2090
2091                 throw CppSQLite3Exception(nRes,
2092
2093                                                                 "Error binding NULL param",
2094
2095                                                                 DONT_DELETE_MSG);
2096
2097         }
2098
2099 }
2100
2101
2102
2103
2104
2105 void CppSQLite3Statement::reset()
2106
2107 {
2108
2109         if (mpVM)
2110
2111         {
2112
2113                 int nRet = sqlite3_reset(mpVM);
2114
2115
2116
2117                 if (nRet != SQLITE_OK)
2118
2119                 {
2120
2121                         const char* szError = sqlite3_errmsg(mpDB);
2122
2123                         throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
2124
2125                 }
2126
2127         }
2128
2129 }
2130
2131
2132
2133
2134
2135 void CppSQLite3Statement::finalize()
2136
2137 {
2138
2139         if (mpVM)
2140
2141         {
2142
2143                 int nRet = sqlite3_finalize(mpVM);
2144
2145                 mpVM = 0;
2146
2147
2148
2149                 if (nRet != SQLITE_OK)
2150
2151                 {
2152
2153                         const char* szError = sqlite3_errmsg(mpDB);
2154
2155                         throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
2156
2157                 }
2158
2159         }
2160
2161 }
2162
2163
2164
2165
2166
2167 void CppSQLite3Statement::checkDB()
2168
2169 {
2170
2171         if (mpDB == 0)
2172
2173         {
2174
2175                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
2176
2177                                                                 "Database not open",
2178
2179                                                                 DONT_DELETE_MSG);
2180
2181         }
2182
2183 }
2184
2185
2186
2187
2188
2189 void CppSQLite3Statement::checkVM()
2190
2191 {
2192
2193         if (mpVM == 0)
2194
2195         {
2196
2197                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
2198
2199                                                                 "Null Virtual Machine pointer",
2200
2201                                                                 DONT_DELETE_MSG);
2202
2203         }
2204
2205 }
2206
2207
2208
2209
2210
2211 ////////////////////////////////////////////////////////////////////////////////
2212
2213
2214
2215 CppSQLite3DB::CppSQLite3DB()
2216
2217 {
2218
2219         mpDB = 0;
2220
2221         mnBusyTimeoutMs = 60000; // 60 seconds
2222
2223 }
2224
2225
2226
2227
2228
2229 CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB& db)
2230
2231 {
2232
2233         mpDB = db.mpDB;
2234
2235         mnBusyTimeoutMs = 60000; // 60 seconds
2236
2237 }
2238
2239
2240
2241
2242
2243 CppSQLite3DB::~CppSQLite3DB()
2244
2245 {
2246
2247         close();
2248
2249 }
2250
2251
2252
2253
2254
2255 CppSQLite3DB& CppSQLite3DB::operator=(const CppSQLite3DB& db)
2256
2257 {
2258
2259         mpDB = db.mpDB;
2260
2261         mnBusyTimeoutMs = 60000; // 60 seconds
2262
2263         return *this;
2264
2265 }
2266
2267
2268
2269
2270
2271 void CppSQLite3DB::open(const char* szFile)
2272
2273 {
2274
2275         int nRet = sqlite3_open(szFile, &mpDB);
2276
2277
2278
2279         if (nRet != SQLITE_OK)
2280
2281         {
2282
2283                 const char* szError = sqlite3_errmsg(mpDB);
2284
2285                 throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
2286
2287         }
2288
2289
2290
2291         setBusyTimeout(mnBusyTimeoutMs);
2292
2293 }
2294
2295
2296
2297
2298
2299 void CppSQLite3DB::close()
2300
2301 {
2302
2303         if (mpDB)
2304
2305         {
2306
2307                 sqlite3_close(mpDB);
2308
2309                 mpDB = 0;
2310
2311         }
2312
2313 }
2314
2315
2316
2317
2318
2319 CppSQLite3Statement CppSQLite3DB::compileStatement(const char* szSQL)
2320
2321 {
2322
2323         checkDB();
2324
2325
2326
2327         sqlite3_stmt* pVM = compile(szSQL);
2328
2329         return CppSQLite3Statement(mpDB, pVM);
2330
2331 }
2332
2333
2334
2335
2336
2337 bool CppSQLite3DB::tableExists(const char* szTable)
2338
2339 {
2340
2341         char szSQL[128];
2342
2343         sprintf(szSQL,
2344
2345                         "select count(*) from sqlite_master where type='table' and name='%s'",
2346
2347                         szTable);
2348
2349         int nRet = execScalar(szSQL);
2350
2351         return (nRet > 0);
2352
2353 }
2354
2355
2356
2357
2358
2359 int CppSQLite3DB::execDML(const char* szSQL)
2360
2361 {
2362
2363         checkDB();
2364
2365
2366
2367         char* szError=0;
2368
2369
2370
2371         int nRet = sqlite3_exec(mpDB, szSQL, 0, 0, &szError);
2372
2373
2374
2375         if (nRet == SQLITE_OK)
2376
2377         {
2378
2379                 return sqlite3_changes(mpDB);
2380
2381         }
2382
2383         else
2384
2385         {
2386
2387                 throw CppSQLite3Exception(nRet, szError);
2388
2389         }
2390
2391 }
2392
2393
2394
2395
2396
2397 CppSQLite3Query CppSQLite3DB::execQuery(const char* szSQL)
2398
2399 {
2400
2401         checkDB();
2402
2403
2404
2405         sqlite3_stmt* pVM = compile(szSQL);
2406
2407
2408
2409         int nRet = sqlite3_step(pVM);
2410
2411
2412
2413         if (nRet == SQLITE_DONE)
2414
2415         {
2416
2417                 // no rows
2418
2419                 return CppSQLite3Query(mpDB, pVM, true/*eof*/);
2420
2421         }
2422
2423         else if (nRet == SQLITE_ROW)
2424
2425         {
2426
2427                 // at least 1 row
2428
2429                 return CppSQLite3Query(mpDB, pVM, false/*eof*/);
2430
2431         }
2432
2433         else
2434
2435         {
2436
2437                 nRet = sqlite3_finalize(pVM);
2438
2439                 const char* szError= sqlite3_errmsg(mpDB);
2440
2441                 throw CppSQLite3Exception(nRet, (char*)szError, DONT_DELETE_MSG);
2442
2443         }
2444
2445 }
2446
2447
2448
2449
2450
2451 int CppSQLite3DB::execScalar(const char* szSQL)
2452
2453 {
2454
2455         CppSQLite3Query q = execQuery(szSQL);
2456
2457
2458
2459         if (q.eof() || q.numFields() < 1)
2460
2461         {
2462
2463                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
2464
2465                                                                 "Invalid scalar query",
2466
2467                                                                 DONT_DELETE_MSG);
2468
2469         }
2470
2471
2472
2473         return atoi(q.fieldValue(0));
2474
2475 }
2476
2477
2478
2479
2480
2481 CppSQLite3Table CppSQLite3DB::getTable(const char* szSQL)
2482
2483 {
2484
2485         checkDB();
2486
2487
2488
2489         char* szError=0;
2490
2491         char** paszResults=0;
2492
2493         int nRet;
2494
2495         int nRows(0);
2496
2497         int nCols(0);
2498
2499
2500
2501         nRet = sqlite3_get_table(mpDB, szSQL, &paszResults, &nRows, &nCols, &szError);
2502
2503
2504
2505         if (nRet == SQLITE_OK)
2506
2507         {
2508
2509                 return CppSQLite3Table(paszResults, nRows, nCols);
2510
2511         }
2512
2513         else
2514
2515         {
2516
2517                 throw CppSQLite3Exception(nRet, szError);
2518
2519         }
2520
2521 }
2522
2523
2524
2525
2526
2527 sqlite_int64 CppSQLite3DB::lastRowId()
2528
2529 {
2530
2531         return sqlite3_last_insert_rowid(mpDB);
2532
2533 }
2534
2535
2536
2537
2538
2539 void CppSQLite3DB::setBusyTimeout(int nMillisecs)
2540
2541 {
2542
2543         mnBusyTimeoutMs = nMillisecs;
2544
2545         sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs);
2546
2547 }
2548
2549
2550
2551
2552
2553 void CppSQLite3DB::checkDB()
2554
2555 {
2556
2557         if (!mpDB)
2558
2559         {
2560
2561                 throw CppSQLite3Exception(CPPSQLITE_ERROR,
2562
2563                                                                 "Database not open",
2564
2565                                                                 DONT_DELETE_MSG);
2566
2567         }
2568
2569 }
2570
2571
2572
2573
2574
2575 sqlite3_stmt* CppSQLite3DB::compile(const char* szSQL)
2576
2577 {
2578
2579         checkDB();
2580
2581
2582
2583         char* szError=0;
2584
2585         const char* szTail=0;
2586
2587         sqlite3_stmt* pVM;
2588
2589
2590
2591         int nRet = sqlite3_prepare(mpDB, szSQL, -1, &pVM, &szTail);
2592
2593
2594
2595         if (nRet != SQLITE_OK)
2596
2597         {
2598
2599                 throw CppSQLite3Exception(nRet, szError);
2600
2601         }
2602
2603
2604
2605         return pVM;
2606
2607 }
2608
2609
2610
2611
2612
2613 ////////////////////////////////////////////////////////////////////////////////
2614
2615 // SQLite encode.c reproduced here, containing implementation notes and source
2616
2617 // for sqlite3_encode_binary() and sqlite3_decode_binary() 
2618
2619 ////////////////////////////////////////////////////////////////////////////////
2620
2621
2622
2623 /*
2624
2625 ** 2002 April 25
2626
2627 **
2628
2629 ** The author disclaims copyright to this source code.  In place of
2630
2631 ** a legal notice, here is a blessing:
2632
2633 **
2634
2635 **    May you do good and not evil.
2636
2637 **    May you find forgiveness for yourself and forgive others.
2638
2639 **    May you share freely, never taking more than you give.
2640
2641 **
2642
2643 *************************************************************************
2644
2645 ** This file contains helper routines used to translate binary data into
2646
2647 ** a null-terminated string (suitable for use in SQLite) and back again.
2648
2649 ** These are convenience routines for use by people who want to store binary
2650
2651 ** data in an SQLite database.  The code in this file is not used by any other
2652
2653 ** part of the SQLite library.
2654
2655 **
2656
2657 ** $Id: CppSQLite3.cpp,v 1.4 2010/03/16 15:46:13 cervenansky Exp $
2658
2659 */
2660
2661
2662
2663 /*
2664
2665 ** How This Encoder Works
2666
2667 **
2668
2669 ** The output is allowed to contain any character except 0x27 (') and
2670
2671 ** 0x00.  This is accomplished by using an escape character to encode
2672
2673 ** 0x27 and 0x00 as a two-byte sequence.  The escape character is always
2674
2675 ** 0x01.  An 0x00 is encoded as the two byte sequence 0x01 0x01.  The
2676
2677 ** 0x27 character is encoded as the two byte sequence 0x01 0x03.  Finally,
2678
2679 ** the escape character itself is encoded as the two-character sequence
2680
2681 ** 0x01 0x02.
2682
2683 **
2684
2685 ** To summarize, the encoder works by using an escape sequences as follows:
2686
2687 **
2688
2689 **       0x00  ->  0x01 0x01
2690
2691 **       0x01  ->  0x01 0x02
2692
2693 **       0x27  ->  0x01 0x03
2694
2695 **
2696
2697 ** If that were all the encoder did, it would work, but in certain cases
2698
2699 ** it could double the size of the encoded string.  For example, to
2700
2701 ** encode a string of 100 0x27 characters would require 100 instances of
2702
2703 ** the 0x01 0x03 escape sequence resulting in a 200-character output.
2704
2705 ** We would prefer to keep the size of the encoded string smaller than
2706
2707 ** this.
2708
2709 **
2710
2711 ** To minimize the encoding size, we first add a fixed offset value to each 
2712
2713 ** byte in the sequence.  The addition is modulo 256.  (That is to say, if
2714
2715 ** the sum of the original character value and the offset exceeds 256, then
2716
2717 ** the higher order bits are truncated.)  The offset is chosen to minimize
2718
2719 ** the number of characters in the string that need to be escaped.  For
2720
2721 ** example, in the case above where the string was composed of 100 0x27
2722
2723 ** characters, the offset might be 0x01.  Each of the 0x27 characters would
2724
2725 ** then be converted into an 0x28 character which would not need to be
2726
2727 ** escaped at all and so the 100 character input string would be converted
2728
2729 ** into just 100 characters of output.  Actually 101 characters of output - 
2730
2731 ** we have to record the offset used as the first byte in the sequence so
2732
2733 ** that the string can be decoded.  Since the offset value is stored as
2734
2735 ** part of the output string and the output string is not allowed to contain
2736
2737 ** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
2738
2739 **
2740
2741 ** Here, then, are the encoding steps:
2742
2743 **
2744
2745 **     (1)   Choose an offset value and make it the first character of
2746
2747 **           output.
2748
2749 **
2750
2751 **     (2)   Copy each input character into the output buffer, one by
2752
2753 **           one, adding the offset value as you copy.
2754
2755 **
2756
2757 **     (3)   If the value of an input character plus offset is 0x00, replace
2758
2759 **           that one character by the two-character sequence 0x01 0x01.
2760
2761 **           If the sum is 0x01, replace it with 0x01 0x02.  If the sum
2762
2763 **           is 0x27, replace it with 0x01 0x03.
2764
2765 **
2766
2767 **     (4)   Put a 0x00 terminator at the end of the output.
2768
2769 **
2770
2771 ** Decoding is obvious:
2772
2773 **
2774
2775 **     (5)   Copy encoded characters except the first into the decode 
2776
2777 **           buffer.  Set the first encoded character aside for use as
2778
2779 **           the offset in step 7 below.
2780
2781 **
2782
2783 **     (6)   Convert each 0x01 0x01 sequence into a single character 0x00.
2784
2785 **           Convert 0x01 0x02 into 0x01.  Convert 0x01 0x03 into 0x27.
2786
2787 **
2788
2789 **     (7)   Subtract the offset value that was the first character of
2790
2791 **           the encoded buffer from all characters in the output buffer.
2792
2793 **
2794
2795 ** The only tricky part is step (1) - how to compute an offset value to
2796
2797 ** minimize the size of the output buffer.  This is accomplished by testing
2798
2799 ** all offset values and picking the one that results in the fewest number
2800
2801 ** of escapes.  To do that, we first scan the entire input and count the
2802
2803 ** number of occurances of each character value in the input.  Suppose
2804
2805 ** the number of 0x00 characters is N(0), the number of occurances of 0x01
2806
2807 ** is N(1), and so forth up to the number of occurances of 0xff is N(255).
2808
2809 ** An offset of 0 is not allowed so we don't have to test it.  The number
2810
2811 ** of escapes required for an offset of 1 is N(1)+N(2)+N(40).  The number
2812
2813 ** of escapes required for an offset of 2 is N(2)+N(3)+N(41).  And so forth.
2814
2815 ** In this way we find the offset that gives the minimum number of escapes,
2816
2817 ** and thus minimizes the length of the output string.
2818
2819 */
2820
2821
2822
2823 /*
2824
2825 ** Encode a binary buffer "in" of size n bytes so that it contains
2826
2827 ** no instances of characters '\'' or '\000'.  The output is 
2828
2829 ** null-terminated and can be used as a string value in an INSERT
2830
2831 ** or UPDATE statement.  Use sqlite3_decode_binary() to convert the
2832
2833 ** string back into its original binary.
2834
2835 **
2836
2837 ** The result is written into a preallocated output buffer "out".
2838
2839 ** "out" must be able to hold at least 2 +(257*n)/254 bytes.
2840
2841 ** In other words, the output will be expanded by as much as 3
2842
2843 ** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
2844
2845 ** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
2846
2847 **
2848
2849 ** The return value is the number of characters in the encoded
2850
2851 ** string, excluding the "\000" terminator.
2852
2853 */
2854
2855 int sqlite3_encode_binary(const unsigned char *in, int n, unsigned char *out){
2856
2857   int i, j, e, m;
2858
2859   int cnt[256];
2860
2861   if( n<=0 ){
2862
2863     out[0] = 'x';
2864
2865     out[1] = 0;
2866
2867     return 1;
2868
2869   }
2870
2871   memset(cnt, 0, sizeof(cnt));
2872
2873   for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
2874
2875   m = n;
2876
2877   for(i=1; i<256; i++){
2878
2879     int sum;
2880
2881     if( i=='\'' ) continue;
2882
2883     sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
2884
2885     if( sum<m ){
2886
2887       m = sum;
2888
2889       e = i;
2890
2891       if( m==0 ) break;
2892
2893     }
2894
2895   }
2896
2897   out[0] = e;
2898
2899   j = 1;
2900
2901   for(i=0; i<n; i++){
2902
2903     int c = (in[i] - e)&0xff;
2904
2905     if( c==0 ){
2906
2907       out[j++] = 1;
2908
2909       out[j++] = 1;
2910
2911     }else if( c==1 ){
2912
2913       out[j++] = 1;
2914
2915       out[j++] = 2;
2916
2917     }else if( c=='\'' ){
2918
2919       out[j++] = 1;
2920
2921       out[j++] = 3;
2922
2923     }else{
2924
2925       out[j++] = c;
2926
2927     }
2928
2929   }
2930
2931   out[j] = 0;
2932
2933   return j;
2934
2935 }
2936
2937
2938
2939 /*
2940
2941 ** Decode the string "in" into binary data and write it into "out".
2942
2943 ** This routine reverses the encoding created by sqlite3_encode_binary().
2944
2945 ** The output will always be a few bytes less than the input.  The number
2946
2947 ** of bytes of output is returned.  If the input is not a well-formed
2948
2949 ** encoding, -1 is returned.
2950
2951 **
2952
2953 ** The "in" and "out" parameters may point to the same buffer in order
2954
2955 ** to decode a string in place.
2956
2957 */
2958
2959 int sqlite3_decode_binary(const unsigned char *in, unsigned char *out){
2960
2961   int i, c, e;
2962
2963   e = *(in++);
2964
2965   i = 0;
2966
2967   while( (c = *(in++))!=0 ){
2968
2969     if( c==1 ){
2970
2971       c = *(in++);
2972
2973       if( c==1 ){
2974
2975         c = 0;
2976
2977       }else if( c==2 ){
2978
2979         c = 1;
2980
2981       }else if( c==3 ){
2982
2983         c = '\'';
2984
2985       }else{
2986
2987         return -1;
2988
2989       }
2990
2991     }
2992
2993     out[i++] = (c + e)&0xff;
2994
2995   }
2996
2997   return i;
2998
2999 }
3000