-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlibSqliteWrapped.h
685 lines (540 loc) · 18.3 KB
/
libSqliteWrapped.h
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
/**
* IError.h
*
* Rewritten / author: 2016-02-19 / [email protected]
* Published / author: 2005-08-12 / [email protected]
* Copyright (C) 2015-2018 Michael Griffin
* Copyright (C) 2001-2006 Anders Hedstrom
* This program is made available under the terms of the GNU GPL.
*/
#ifndef _IERROR_H_SQLITE
#define _IERROR_H_SQLITE
#include <string>
namespace SQLW
{
class Database;
class Query;
/** Log class interface. */
class IError
{
public:
virtual void databaseError(Database&, const std::string&) = 0;
virtual void databaseError(Database&, Query&, const std::string&) = 0;
};
} // namespace SQLW {
#endif // _IERROR_H
/**
* StderrLog.h
*
* Rewritten / author: 2016-02-19 / [email protected]
* Published / author: 2005-08-12 / [email protected]
* Copyright (C) 2015-2018 Michael Griffin
* Copyright (C) 2001-2006 Anders Hedstrom
* This program is made available under the terms of the GNU GPL.
*/
#ifndef _STDERRLOG_H_SQLITE
#define _STDERRLOG_H_SQLITE
#include "IError.h"
#include <string>
namespace SQLW
{
class Database;
/** Log class writing to standard error. */
class StderrLog : public IError
{
public:
void databaseError(Database&, const std::string&);
void databaseError(Database&, Query&, const std::string&);
};
} // namespace SQLW {
#endif // _STDERRLOG_H
/**
* SysLog.h
*
* Rewritten / author: 2016-02-19 / [email protected]
* Published / author: 2005-08-12 / [email protected]
* Copyright (C) 2015-2018 Michael Griffin
* Copyright (C) 2001-2006 Anders Hedstrom
* This program is made available under the terms of the GNU GPL.
*/
#ifndef _SYSLOG_H_SQLITE
#define _SYSLOG_H_SQLITE
#ifndef _WIN32
#include <syslog.h>
namespace SQLW
{
/** Log class writing to syslog. */
class SysLog : public IError
{
public:
SysLog(const std::string& = "database", int = LOG_PID, int = LOG_USER);
virtual ~SysLog();
void databaseError(Database&, const std::string&);
void databaseError(Database&, Query&, const std::string&);
};
} // namespace SQLW {
#endif // WIN32
#endif // _SYSLOG_H
/**
* Database.h
*
* Rewritten / author: 2016-02-19 / [email protected]
* Published / author: 2005-08-12 / [email protected]
* Copyright (C) 2015-2018 Michael Griffin
* Copyright (C) 2001-2006 Anders Hedstrom
* This program is made available under the terms of the GNU GPL.
*/
#ifndef _DATABASE_H_SQLITE
#define _DATABASE_H_SQLITE
#include <sqlite3.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <pthread.h>
#endif
#include <string>
#include <list>
#include <stdint.h>
namespace SQLW
{
// handle unused paramters for template funcations.
#define UNUSED(x) [&x]{}()
// Forward Declarations
class IError;
class Query;
class Mutex;
/** Connection information and pool. */
class Database
{
public:
/** Mutex container class, used by Lock. ingroup threading */
class Mutex
{
public:
Mutex();
~Mutex();
void MutexLock();
void Unlock();
private:
// Replace this with std::mutex!
#ifdef _WIN32
HANDLE m_mutex;
#else
pthread_mutex_t m_mutex;
#endif
};
private:
// Mutex helper class.
class MutexLock
{
public:
MutexLock(Mutex& mutex, bool use);
~MutexLock();
private:
Mutex& m_mutex;
bool m_is_inuse;
};
public:
// Connection pool struct.
struct DatabasePool
{
DatabasePool()
: db(nullptr)
, busy(false)
{ }
~DatabasePool()
{
if (db)
{
sqlite3_close_v2(db);
}
}
sqlite3 *db;
bool busy;
};
typedef std::list<DatabasePool *> m_database_pool;
public:
// use file
Database(const std::string& database, IError *databaseError = nullptr);
// Use file + thread safe
Database(Mutex&, const std::string& database, IError *databaseError = nullptr);
virtual ~Database();
/** try to establish connection with given host */
bool isConnected();
void errorHandler(IError *);
void databaseError(Query&,const char *format, ...);
void databaseError(Query&,const std::string&);
/** Request a database connection.
The "grabdb" method is used by the Query class, so that each object instance of Query gets a unique
database connection. I will re-implement your connection check logic in the Query class, as that's where
the database connection is really used.
It should be used something like this.
{
Query q(db);
if (!q.isConnected())
{
return false;
}
q.execute("delete * from user"); // well maybe not
}
When the Query object is deleted, then "freeDatabasePool" is called - the database connection stays open in the
m_opendbs vector. New Query objects can then reuse old connections.
*/
DatabasePool *addDatabasePool();
void freeDatabasePool(DatabasePool *odb);
// Escape string - change all ' to ''.
std::string safeString(const std::string& );
// Make string xml safe.
std::string xmlSafeString(const std::string&);
// Convert string to 64-bit integer.
int64_t alphaToBigInt(const std::string&);
// Convert string to unsigned 64-bit integer.
uint64_t alphaToUnsignedBitInt(const std::string&);
private:
void databaseError(const char *format, ...);
std::string m_database;
m_database_pool m_opendbs;
IError *m_errhandler;
Mutex& m_mutex;
bool m_is_mutex;
};
} // namespace SQLW
#endif // _DATABASE_H
/**
* Query.h
*
* Rewritten / author: 2016-02-19 / [email protected]
* Published / author: 2005-08-12 / [email protected]
* Copyright (C) 2015-2018 Michael Griffin
* Copyright (C) 2001-2006 Anders Hedstrom
* This program is made available under the terms of the GNU GPL.
*/
#ifndef _QUERY_H_SQLITE
#define _QUERY_H_SQLITE
#include <sqlite3.h>
#include <iostream>
#include <ctime>
#include <string>
#include <map>
#include <vector>
#include <memory>
#include <stdint.h>
#include <sstream>
namespace SQLW
{
/** SQL Statement execute / result. */
class Query
{
public:
/** Constructor accepting reference to database object. */
Query(Database& dbin);
/** Constructor accepting reference to database object
and query string to execute. */
Query(Database& dbin,const std::string& sql);
~Query();
/** Check if database object is connectable. */
bool isConnected();
/** Return reference to database object. */
Database& getDatabase() const;
/** Return string containing last query executed. */
const std::string& getLastQuery();
/** execute() returns true if query is successful,
does not store result. */
bool execute(const std::string& sql);
/** Execute query and store result. */
sqlite3_stmt *getResult(const std::string& sql);
/** Free stored result, must be called after get_result() before calling
execute()/get_result() again. */
void freeResult();
/** Fetch next result row.
\return false if there was no row to fetch (end of rows) */
// Fill the Resource with the current row, also incriments to next row.
bool fetchRow();
/** Get id of last insert. */
sqlite_int64 getInsertId();
/** Returns 0 if there are no rows to fetch. */
long getNumRows();
/** Number of columns in current result. */
int getNumCols();
/** Last error string. */
std::string getError();
/** Last error code. */
int getErrorCode();
/** Check if column x in current row is null. */
bool isNull(int x);
/**
* @brief Execute Query and Get first Result as the following.
*/
/** Execute query and return first result as a string. */
const char *exeGetCharString(const std::string& sql);
/** Execute query and return first result as a long integer. */
long exeGetResultLong(const std::string& sql);
/** Execute query and return first result as a double. */
double exeGetResultDouble(const std::string& sql);
/**
* @brief On FetchRow, get the current column values as.
*/
/** Return column named x as a string value. */
const char *getString(const std::string& x);
/** Return column x as a string value. */
const char *getString(int x);
/** Return next column as a string value - see rowcount. */
const char *getString();
/**
* @brief On FetchRow, get the current column values as.
*/
/** Return column named x as a long integer. */
long getValue(const std::string& x);
/** Return column x as a long integer. */
long getValue(int x);
/** Return next column as a long integer - see rowcount. */
long getValue();
/**
* @brief On FetchRow, get the current column values as.
*/
/** Return column named x as an unsigned long integer. */
unsigned long getUnsignedValue(const std::string& x);
/** Return column x as an unsigned long integer. */
unsigned long getUnsignedValue(int x);
/** Return next column as an unsigned long integer. */
unsigned long getUnsignedValue();
/**
* @brief On FetchRow, get the current column values as.
*/
/** Return column named x as a 64-bit integer value. */
int64_t getBigInt(const std::string& x);
/** Return column x as a 64-bit integer value. */
int64_t getBigInt(int x);
/** Return next column as a 64-bit integer value. */
int64_t getBigInt();
/** Return column named x as an unsigned 64-bit integer value. */
uint64_t getUnsignedBitInt(const std::string& x);
/** Return column x as an unsigned 64-bit integer value. */
uint64_t getUnsignedBitInt(int x);
/** Return next column as an unsigned 64-bit integer value. */
uint64_t getUnsignedBitInt();
/**
* @brief On FetchRow, get the current column values as.
*/
/** Return column named x as a double. */
double getNumber(const std::string& x);
/** Return column x as a double. */
double getNumber(int x);
/** Return next column as a double. */
double getNumber();
/**
* @brief On FetchRow, Get Field Value by Column Name and Type
*/
// Unsigned Int 32 bit
void getFieldValue(uint32_t &type, int index)
{
//UNUSED(type);
type = static_cast<uint32_t>(sqlite3_column_int(res, index));
}
// Int
void getFieldValue(int &type, int index)
{
//UNUSED(type);
type = static_cast<int>(sqlite3_column_int(res, index));
}
// Long or Time_T for Date/Time.
void getFieldValue(long &type, int index)
{
type = static_cast<long>(sqlite3_column_int64(res, index));
}
// Long Long
void getFieldValue(long long &type, int index)
{
type = static_cast<long long>(sqlite3_column_int64(res, index));
}
// Double
void getFieldValue(double &type, int index)
{
type = static_cast<double>(sqlite3_column_double(res, index));
}
// Float
void getFieldValue(float &type, int index)
{
type = static_cast<float>(sqlite3_column_double(res, index));
}
// Long Double
void getFieldValue(long double &type, int index)
{
type = static_cast<long double>(sqlite3_column_double(res, index));
}
// Std::String
void getFieldValue(std::string &type, int index)
{
const char *text_result = reinterpret_cast<const char *>(sqlite3_column_text(res , index));
type = text_result;
}
// Single Character
void getFieldValue(char &type, int index)
{
const char *result = reinterpret_cast<const char *>(sqlite3_column_text(res , index));
type = result[0];
}
// Char *
const char *getFieldValue(char *, int index)
{
const char *result = reinterpret_cast<const char *>(sqlite3_column_text(res , index));
return result;
}
/*
// Char *, or BLOB. sqlite3_column_blob ? test this lateron!
const char *getFieldValue(char *type, int index)
{
if (strcmp(type, "BLOB") == 0)
{
// Test if we need to get len in bytes then cutoff!
const char *result = reinterpret_cast<const char *>(sqlite3_column_blob(res , index));
return result;
}
const char *result = reinterpret_cast<const char *>(sqlite3_column_text(res , index));
return result;
}*/
// Handle Boolean Values.
void getFieldValue(bool &type, int index)
{
int result = static_cast<int>(sqlite3_column_int(res , index));
if (result == 1)
type = true;
else
type = false;
}
/**
* @brief Template to Get Field Value by Column Name and Populate Type passed.
*/
template <typename TT, typename T>
T getFieldByName(const TT &tt, T &t)
{
// Grab the index of the Matching Field Name
std::map<std::string, int>::iterator it;
int index = 0;
if (m_nmap.empty())
{
return t;
}
it = m_nmap.find(tt);
if (it != m_nmap.end())
{
index = it->second;
--index;
}
else
{
return t;
}
if (index >= 0)
{
switch(sqlite3_column_type(res, index))
{
case SQLITE_NULL:
break;
default :
// Template to pull field value dynamically from overloads.
getFieldValue(t, index);
return t;
}
}
return t;
}
std::string getFieldType(float &)
{
std::string result("%f");
return result;
}
std::string getFieldType(double &)
{
std::string result("%d");
return result;
}
std::string getFieldType(long long &)
{
// %llu or lld ?!?
std::string result("%llu");
return result;
}
std::string getFieldType(char &)
{
std::string result("%Q");
return result;
}
std::string getFieldType(bool &)
{
std::string result("%d");
return result;
}
std::string getFieldType(char *)
{
std::string result("%Q");
return result;
}
std::string getFieldType(std::string &)
{
std::string result("%Q");
return result;
}
std::string getFieldType(long &)
{
std::string result("%ld");
return result;
}
std::string getFieldType(int &)
{
std::string result("%d");
return result;
}
std::string getFieldType(uint32_t &)
{
std::string result("%d");
return result;
}
/**
* @brief This takes a Description, and a Type, for translation inserts statements (Column) VALUES (TYPE)
*/
template <typename TT, typename T>
std::pair<std::string, std::string> translateFieldName(const TT &tt, T &t)
{
std::pair<std::string, std::string> pair;
// Template to pull field type, int = %d, text = '%q' etc..
pair = std::make_pair(tt, getFieldType(t));
return pair;
}
/**
* Create a new Executate Transaction
*/
bool executeTransaction(const std::vector<std::string> &statements);
private:
/** Hide the copy constructor. */
/*
Query(const Query& q)
: m_db(q.getDatabase())
{
std::cout << "Query Constructor: q.getDatabase()" << std::endl;
*this = q;
}*/
/** Hide the assignment operator. */
/*
Query& operator=(const Query&)
{
std::cout << "Query Constructor: return *this" << std::endl;
return *this;
}*/
/** Print error to debug class. */
void queryError(const std::string&);
Database& m_db; ///< Reference to database object
Database::DatabasePool *odb; ///< Connection pool handle
sqlite3_stmt *res; ///< Stored result
bool row; ///< true if fetch_row succeeded
short rowcount; ///< Current column pointer in result
std::string m_tmpstr; ///< Used to store result in get_string() call
std::string m_last_query; ///< Last query executed
int cache_rc; ///< Cached result after call to get_result()
bool cache_rc_valid; ///< Indicates cache_rc is valid
int m_row_count; ///< 0 if get_result() returned no rows
std::map<std::string, int> m_nmap; ///< map translating column names to index
int m_num_cols; ///< number of columns in result
};
} // namespace SQLW
#endif // _QUERY_H