-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSQLite.cpp
729 lines (603 loc) · 16.6 KB
/
SQLite.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
/************************************************************************
created: 2007-08-17
updated: 2007-12-23
filename: SQLite.h
author: Daniel C. Gindi (danielgindi (at) gmail dot com)
purpose: Wrapper for SQLite3!
There are 2 "public" classes in here,
under the namspace SQLite:
Database : Which is the main wrapper for an SQLite3
database.
Table : Which is representing a table returned
from a query on CSQLite
I'm pretty sure that my classes fully support Unicode.
Legal notes: You are free you use these classes for whatever use
you have in mind, even commercial,
On one condition, don't ever claim you wrote it.
And if you wanna give me credits, I would like that... :-)
Contact notes: I can be contacted at (danielgindi (at) gmail dot com)
If you just wanna say thank you, or better, if you
think there's room for improvement for these
classes...
*************************************************************************/
#include "StdAfx.h"
#include "SQLite.h"
namespace SQLite
{
Database::Database(void)
{
m_sqlite3=0;
m_iLastError=SQLITE_OK;
}
Database::~Database(void)
{
Close();
}
int Database::Open( LPCTSTR strFileName )
{
Close();
int iErr=sqlite3_open(UTF8MBSTR(strFileName), &m_sqlite3);
if (iErr!=SQLITE_OK) m_iLastError=iErr;
return iErr;
}
void Database::Close()
{
if (m_sqlite3)
{
sqlite3_close(m_sqlite3);
m_sqlite3=0;
}
}
bool Database::IsOpen()
{
if (this==0) return false; // check for valid Database* pointer
return m_sqlite3!=0; // check for open database
}
Table Database::QuerySQL( LPCTSTR strSQL )
{
if (!IsOpen()) {
m_iLastError=SQLITE_ERROR;
return Table();
}
// I do not need to imlpement the whole sqlite3_get_table
// with callbacks and all myself, because it won't spare me anything,
// I'm converting the returned strings to TCHAR anyway,
// so I'm not really copying the strings into the Table class
char ** retStrings = 0;
char * errmsg = 0;
int iRows=0, iCols=0;
int iErr=sqlite3_get_table(m_sqlite3, UTF8MBSTR(strSQL), &retStrings,
&iRows, &iCols, &errmsg);
if (iErr!=SQLITE_OK) m_iLastError=iErr;
#ifdef DEBUG
if (errmsg) {
stdvstring errstr;
ConvertUTF8ToString(errmsg, errstr);
TRACE(_T("QuerySQL error: %s\r\n"), &errstr[0]);
}
#endif
// No need for string errors,
// too costly is the comparision of strings.
//
// BTW: sqlite3_free() already checks for null pointer,
// so I do not do double checking.
// And I can assume this for later versions, because
// that is generally the point of sqlite3_free()...
sqlite3_free(errmsg);
Table retTable;
if (iRows>0) retTable.m_iPos=0; // Put retTable's cursor on first row
retTable.m_iCols=iCols;
retTable.m_iRows=iRows;
// allocate the memory for the header
retTable.m_strlstCols.reserve(iCols);
int iPos=0;
for (; iPos<iCols; iPos++)
{
// Add a string element
retTable.m_strlstCols.push_back(stdvstring());
// Convert the UTF8 to TCHAR string
if (retStrings[iPos])
ConvertUTF8ToString( retStrings[iPos], retTable.m_strlstCols.back() );
else retTable.m_strlstCols.back().push_back(_T('\0'));
}
retTable.m_lstRows.resize(iRows);
for (int iRow=0; iRow<iRows; iRow++)
{
retTable.m_lstRows[iRow].reserve(iCols);
for (int iCol=0; iCol<iCols; iCol++)
{
// Add a string element
retTable.m_lstRows[iRow].push_back(stdvstring());
// Convert the UTF8 to TCHAR string
if (retStrings[iPos])
ConvertUTF8ToString( retStrings[iPos], retTable.m_lstRows[iRow].back() );
else retTable.m_lstRows[iRow].back().push_back(_T('\0'));
iPos++;
}
}
// sqlite3_free_table() also checks for null pointer...
sqlite3_free_table(retStrings);
return retTable;
}
TablePtr Database::QuerySQL2( LPCTSTR strSQL )
{
if (!IsOpen()) {
m_iLastError=SQLITE_ERROR;
return 0;
}
// I do not need to imlpement the whole sqlite3_get_table
// with callbacks and all myself, because it won't spare me anything,
// I'm converting the returned strings to TCHAR anyway,
// so I'm not really copying the strings into the Table class
char ** retStrings = 0;
char * errmsg = 0;
int iRows=0, iCols=0;
int iErr=sqlite3_get_table(m_sqlite3, UTF8MBSTR(strSQL), &retStrings,
&iRows, &iCols, &errmsg);
if (iErr!=SQLITE_OK) m_iLastError=iErr;
#ifdef DEBUG
if (errmsg) {
stdvstring errstr;
ConvertUTF8ToString(errmsg, errstr);
TRACE(_T("QuerySQL2 error: %s\r\n"), &errstr[0]);
}
#endif
// No need for string errors,
// too costly is the comparision of strings.
//
// BTW: sqlite3_free() already checks for null pointer,
// so I do not do double checking.
// And I can assume this for later versions, because
// that is generally the point of sqlite3_free()...
sqlite3_free(errmsg);
Table * retTable = new Table();
if (iRows>0) retTable->m_iPos=0; // Put retTable's cursor on first row
retTable->m_iCols=iCols;
retTable->m_iRows=iRows;
// allocate the memory for the header
retTable->m_strlstCols.reserve(iCols);
int iPos=0;
for (; iPos<iCols; iPos++)
{
// Add a string element
retTable->m_strlstCols.push_back(stdvstring());
// Convert the UTF8 to TCHAR string
if (retStrings[iPos])
ConvertUTF8ToString( retStrings[iPos], retTable->m_strlstCols.back() );
else retTable->m_strlstCols.back().push_back(_T('\0'));
}
retTable->m_lstRows.resize(iRows);
for (int iRow=0; iRow<iRows; iRow++)
{
retTable->m_lstRows[iRow].reserve(iCols);
for (int iCol=0; iCol<iCols; iCol++)
{
// Add a string element
retTable->m_lstRows[iRow].push_back(stdvstring());
// Convert the UTF8 to TCHAR string
if (retStrings[iPos])
ConvertUTF8ToString( retStrings[iPos], retTable->m_lstRows[iRow].back() );
else retTable->m_lstRows[iRow].back().push_back(_T('\0'));
iPos++;
}
}
// sqlite3_free_table() also checks for null pointer...
sqlite3_free_table(retStrings);
return TablePtr(retTable);
}
void Database::ConvertUTF8ToString( char * strInUTF8MB, stdvstring & strOut )
{
int len=(int)strlen(strInUTF8MB)+1;
strOut.resize(len, 0);
#ifdef UNICODE
MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, len, &strOut[0], len);
#else
WCHAR * wChar=new WCHAR[len];
wChar[0]=0;
MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, len, wChar, len);
WideCharToMultiByte(CP_ACP, 0, wChar, len, &strOut[0], len, 0, 0);
delete [] wChar;
#endif
}
int Database::ExecuteSQL( LPCTSTR strSQL )
{
if (!IsOpen()) {
m_iLastError=SQLITE_ERROR;
return SQLITE_ERROR;
}
char * errmsg = 0;
int iErr = sqlite3_exec( m_sqlite3, UTF8MBSTR(strSQL), 0, 0, &errmsg );
if (iErr!=SQLITE_OK) m_iLastError=iErr;
#ifdef DEBUG
if (errmsg) {
stdvstring errstr;
ConvertUTF8ToString(errmsg, errstr);
TRACE(_T("ExecuteSQL error: %s\r\n"), &errstr[0]);
}
#endif
// No need for string errors,
// too costly is the comparision of strings.
//
// BTW: sqlite3_free() already checks for null pointer,
// so I do not do double checking.
// And I can assume this for later versions, because
// that is generally the point of sqlite3_free()...
sqlite3_free(errmsg);
return iErr;
}
int Database::IsSQLComplete( LPCTSTR strSQL )
{
return sqlite3_complete( UTF8MBSTR(strSQL) );
}
int Database::GetLastChangesCount()
{
return sqlite3_changes(m_sqlite3);
}
int Database::ReadBlob( LPCTSTR strSQL, BYTE ** pData, int * iLenBlob )
{
if (!IsOpen() || !pData) {
m_iLastError=SQLITE_ERROR;
return SQLITE_ERROR;
}
sqlite3_stmt *pStmt;
int iErr = SQLITE_OK;
// In case an error occurs, set *pData and *iLenBlob to 0 now.
*pData = 0;
*iLenBlob = 0;
do {
// Compile the SELECT statement into a compiled statement.
iErr = sqlite3_prepare(m_sqlite3, UTF8MBSTR(strSQL), -1, &pStmt, 0);
if( iErr!=SQLITE_OK ){
m_iLastError=iErr;
return iErr;
}
// Run the compiled statement.
// We expect only 1 record, so we are only looking for SQLITE_ROW.
iErr = sqlite3_step(pStmt);
if( iErr==SQLITE_ROW ){
// The pointer returned by sqlite3_column_blob() points to memory
// that is owned by the statement handle (pStmt).
// It is only good until the next call to an sqlite3_XXX()
// function (e.g. the sqlite3_finalize() below) that involves
// the statement handle.
// So we need to make a copy of the blob into memory obtained from
// malloc() to return to the caller.
*iLenBlob = sqlite3_column_bytes(pStmt, 0);
*pData = (unsigned char *)malloc(*iLenBlob);
memcpy(*pData, sqlite3_column_blob(pStmt, 0), *iLenBlob);
}
// Finalize the statement ( this releases resources allocated by
// sqlite3_prepare() ).
iErr = sqlite3_finalize(pStmt);
// If sqlite3_finalize() returned SQLITE_SCHEMA, then try to execute
// the statement all over again.
// ( SQLITE_SCHEMA means that something in the structure of the
// table has changed, so the statement was not valid anymore )
} while( iErr==SQLITE_SCHEMA );
return iErr;
}
int Database::WriteBlob( LPCTSTR strSQL, BYTE * pData, int iLenBlob )
{
if (!IsOpen()) {
m_iLastError=SQLITE_ERROR;
return SQLITE_ERROR;
}
sqlite3_stmt *pStmt;
int iErr=SQLITE_OK;
do {
// Compile the SQL statement into a compiled statement.
iErr = sqlite3_prepare(m_sqlite3, UTF8MBSTR(strSQL), -1, &pStmt, 0);
if( iErr!=SQLITE_OK ){
m_iLastError=iErr;
return iErr;
}
// Bind the pData to the compiled statement
// (the ? characters in the sql statement)
sqlite3_bind_blob(pStmt, 1, pData, iLenBlob, SQLITE_STATIC);
// Call sqlite3_step() to run the compiled statement.
iErr = sqlite3_step(pStmt);
ASSERT( iErr!=SQLITE_ROW );
// Finalize the statement ( this releases resources allocated by
// sqlite3_prepare() ).
iErr = sqlite3_finalize(pStmt);
// If sqlite3_finalize() returned SQLITE_SCHEMA, then try to execute
// the statement all over again.
// ( SQLITE_SCHEMA means that something in the structure of the
// table has changed, so the statement was not valid anymore )
} while( iErr==SQLITE_SCHEMA );
return iErr;
}
sqlite_int64 Database::GetLastInsertRowID()
{
if (m_sqlite3==0) return 0; // RowID's starts with 1...
return sqlite3_last_insert_rowid(m_sqlite3);
}
bool Database::BeginTransaction()
{
if (!IsOpen())
{
m_iLastError=SQLITE_ERROR;
return false;
}
m_iLastError = ExecuteSQL(_T("BEGIN TRANSACTION"));
return m_iLastError==SQLITE_OK;
}
bool Database::CommitTransaction()
{
if (!IsOpen())
{
m_iLastError=SQLITE_ERROR;
return false;
}
m_iLastError = ExecuteSQL(_T("COMMIT TRANSACTION"));
return m_iLastError==SQLITE_OK;
}
bool Database::RollbackTransaction()
{
if (!IsOpen())
{
m_iLastError=SQLITE_ERROR;
return false;
}
m_iLastError = ExecuteSQL(_T("ROLLBACK TRANSACTION"));
return m_iLastError==SQLITE_OK;
}
LPCTSTR Table::GetColName( int iCol )
{
if (iCol>=0 && iCol<m_iCols)
{
return &m_strlstCols[iCol][0];
}
return 0;
}
bool Table::GoFirst()
{
if (this==0) return false;
if (m_lstRows.size())
{
m_iPos=0;
return true;
}
return false;
}
bool Table::GoLast()
{
if (m_lstRows.size())
{
m_iPos=(int)m_lstRows.size()-1;
return true;
}
return false;
}
bool Table::GoNext()
{
if (m_iPos+1<(int)m_lstRows.size())
{
m_iPos++;
return true;
}
return false;
}
bool Table::GoPrev()
{
if (m_iPos>0)
{
m_iPos--;
return true;
}
return false;
}
bool Table::GoRow(unsigned int iRow)
{
if (this==0) return false;
if (iRow<m_lstRows.size())
{
m_iPos=iRow;
return true;
}
return false;
}
LPCTSTR Table::GetValue(LPCTSTR lpColName)
{
if (!lpColName) return 0;
if (m_iPos<0) return 0;
for (int i=0; i<m_iCols; i++)
{
if (!_tcsicmp(&m_strlstCols[i][0],lpColName))
{
return &m_lstRows[m_iPos][i][0];
}
}
return 0;
}
LPCTSTR Table::GetValue(int iColIndex)
{
if (iColIndex<0 || iColIndex>=m_iCols) return 0;
if (m_iPos<0) return 0;
return &m_lstRows[m_iPos][iColIndex][0];
}
LPCTSTR Table::operator [] (LPCTSTR lpColName)
{
if (!lpColName) return 0;
if (m_iPos<0) return 0;
for (int i=0; i<m_iCols; i++)
{
if (!_tcsicmp(&m_strlstCols[i][0],lpColName))
{
return &m_lstRows[m_iPos][i][0];
}
}
return 0;
}
LPCTSTR Table::operator [] (int iColIndex)
{
if (iColIndex<0 || iColIndex>=m_iCols) return 0;
if (m_iPos<0) return 0;
return &m_lstRows[m_iPos][iColIndex][0];
}
void Table::JoinTable(Table & tblJoin)
{
if (m_iCols==0) {
*this=tblJoin;
return;
}
if (m_iCols!=tblJoin.m_iCols) return;
if (tblJoin.m_iRows>0)
{
m_iRows+=tblJoin.m_iRows;
for (std::vector<row>::iterator it=tblJoin.m_lstRows.begin();
it!=tblJoin.m_lstRows.end(); it++)
{
m_lstRows.push_back(*it);
}
}
}
TablePtr::TablePtr( )
{
m_pTable=0;
}
TablePtr::TablePtr( Table * pTable )
{
m_pTable = pTable;
}
TablePtr::TablePtr( const TablePtr& cTablePtr )
{
m_pTable=cTablePtr.m_pTable;
// Copy constructors and operators,
// for a good reason, must take const reference,
// but here, for a good reason, we must modify the referenced object,
// so it won't get freed by the original.
// I'm using a simple technique to bypass the const declaration
((TablePtr *)&cTablePtr)->m_pTable=0;
}
TablePtr::~TablePtr()
{
if (m_pTable) delete m_pTable;
}
void TablePtr::operator =( const TablePtr& cTablePtr )
{
if (m_pTable) delete m_pTable;
m_pTable=cTablePtr.m_pTable;
// Copy constructors and operators,
// for a good reason, must take const reference,
// but here, for a good reason, we must modify the referenced object,
// so it won't get freed by the original.
// I'm using a simple technique to bypass the const declaration
((TablePtr *)&cTablePtr)->m_pTable=0;
}
Table * TablePtr::Detach()
{
Table * pTable=m_pTable;
m_pTable=0;
return pTable;
}
void TablePtr::Attach( Table * pTable )
{
if (m_pTable) delete m_pTable;
m_pTable=pTable;
}
void TablePtr::Destroy()
{
if (m_pTable) delete m_pTable;
m_pTable=0;
}
UTF8MBSTR::UTF8MBSTR()
{
m_strUTF8_MultiByte=new char[1];
m_strUTF8_MultiByte[0]=0;
m_iLen=0;
}
UTF8MBSTR::UTF8MBSTR( LPCTSTR lpStr )
{
if (lpStr)
m_iLen=ConvertStringToUTF8(lpStr, m_strUTF8_MultiByte);
else {
m_strUTF8_MultiByte=new char[1];
m_strUTF8_MultiByte[0]=0;
m_iLen=0;
}
}
UTF8MBSTR::UTF8MBSTR( UTF8MBSTR& lpStr )
{
m_iLen=lpStr.m_iLen;
m_strUTF8_MultiByte=new char[m_iLen+1];
strncpy_s(m_strUTF8_MultiByte, m_iLen+1, lpStr.m_strUTF8_MultiByte, m_iLen+1);
}
UTF8MBSTR::~UTF8MBSTR()
{
if (m_strUTF8_MultiByte)
{
delete [] m_strUTF8_MultiByte;
}
}
void UTF8MBSTR::operator =( LPCTSTR lpStr )
{
if (m_strUTF8_MultiByte)
{
delete [] m_strUTF8_MultiByte;
}
if (lpStr)
m_iLen=ConvertStringToUTF8(lpStr, m_strUTF8_MultiByte);
else {
m_strUTF8_MultiByte=new char[1];
m_strUTF8_MultiByte[0]=0;
m_iLen=0;
}
}
void UTF8MBSTR::operator =( UTF8MBSTR& lpStr )
{
if (m_strUTF8_MultiByte)
{
delete [] m_strUTF8_MultiByte;
}
m_iLen=lpStr.m_iLen;
m_strUTF8_MultiByte=new char[m_iLen+1];
strncpy_s(m_strUTF8_MultiByte, m_iLen+1, lpStr.m_strUTF8_MultiByte, m_iLen+1);
}
UTF8MBSTR::operator char* ()
{
return m_strUTF8_MultiByte;
}
UTF8MBSTR::operator stdstring ()
{
TCHAR * strRet;
ConvertUTF8ToString(m_strUTF8_MultiByte, m_iLen+1, strRet);
stdstring cstrRet(strRet);
delete [] strRet;
return cstrRet;
}
size_t UTF8MBSTR::ConvertStringToUTF8( LPCTSTR strIn, char *& strOutUTF8MB )
{
size_t len=_tcslen(strIn);
#ifdef UNICODE
int iRequiredSize=WideCharToMultiByte(CP_UTF8, 0, strIn, (int)len+1, 0, 0, 0, 0);
strOutUTF8MB=new char[iRequiredSize];
strOutUTF8MB[0]=0;
WideCharToMultiByte(CP_UTF8, 0, strIn, (int)len+1, strOutUTF8MB, iRequiredSize, 0, 0);
#else
WCHAR * wChar=new WCHAR[len+1];
wChar[0]=0;
MultiByteToWideChar(CP_ACP, 0, strIn, (int)len+1, wChar, (int)len+1);
int iRequiredSize=WideCharToMultiByte(CP_UTF8, 0, wChar, (int)len+1, 0, 0, 0, 0);
strOutUTF8MB=new char[iRequiredSize];
strOutUTF8MB[0]=0;
WideCharToMultiByte(CP_UTF8, 0, wChar, (int)len+1, strOutUTF8MB, iRequiredSize, 0, 0);
delete [] wChar;
#endif
return len;
}
void UTF8MBSTR::ConvertUTF8ToString( char * strInUTF8MB, size_t len, LPTSTR & strOut )
{
strOut=new TCHAR[len];
strOut[0]=0;
#ifdef UNICODE
MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, (int)len, strOut, (int)len);
#else
WCHAR * wChar=new WCHAR[len];
wChar[0]=0;
MultiByteToWideChar(CP_UTF8, 0, strInUTF8MB, (int)len, wChar, (int)len);
WideCharToMultiByte(CP_ACP, 0, wChar, (int)len, strOut, (int)len, 0, 0);
delete [] wChar;
#endif
}
}