forked from iwongu/sqlite3pp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite3pp_ez.cpp
/
sqlite3pp_ez.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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
GNU General Public License
Copyright (C) 2021 David Maisonave (www.axter.com)
The sqlite3pp_ez source code is free software. You can redistribute it and/or modify it under the terms of the GNU General Public License.
This source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
For usage examples see https://github.com/David-Maisonave/sqlite3pp_EZ
or sqlite3pp_ez.h
*/
#include <windows.h>
#include <stringapiset.h>
#ifdef SQLITE3PP_LOADABLE_EXTENSION
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT3
#endif
#include "sqlite3pp_ez.h"
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <direct.h>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#define V_COUT(VB, V) {if (sqlite3pp::sql_base::GetVerbosityLevel() >= sqlite3pp::VBLV_##VB) {std::cout << __FUNCTION__ << ":" << #VB << ": " << V << std::endl;} }
namespace sqlite3pp
{
///////////////////////////////////////////////////////////////////////////
// Added functions for UNICODE support
///////////////////////////////////////////////////////////////////////////
std::wstring to_wstring( const char* src )
{
int nchars = MultiByteToWideChar( CP_ACP, 0, src, -1, NULL, 0 );
wchar_t* wsource = new wchar_t[nchars + 2]();
if ( wsource == NULL )
return std::wstring();
MultiByteToWideChar( CP_ACP, 0, src, -1, wsource, nchars );
std::wstring retrnVal = wsource;
delete[] wsource;
return retrnVal;
}
std::string to_string( const wchar_t* src )
{
int nchars = WideCharToMultiByte( CP_ACP, 0, src, -1, NULL, 0, NULL, NULL );
char* source = new char[nchars + 2]();
if ( source == NULL )
return std::string();
WideCharToMultiByte( CP_ACP, 0, src, -1, source, nchars, NULL, NULL );
std::string retrnVal = source;
delete[] source;
return retrnVal;
}
std::string to_string(const std::wstring &src)
{
return sqlite3pp::to_string(src.c_str());
}
std::string to_string(const std::string &src)
{
return src;
}
std::wstring to_wstring(const std::string &src)
{
return sqlite3pp::to_wstring(src.c_str());
}
std::wstring to_wstring(const std::wstring &src)
{
return src;
}
// Convertion types
std::string to_string(const Clob& src)
{
if (src)
return std::string(src->data(), src->data() + src->size());
return "";
}
std::wstring to_wstring(const Clob& src)
{
if (src)
return std::wstring(src->data(), src->data() + src->size());
return L"";
}
std::string to_string(const Blob& src)
{
if (src)
return std::string(src->data(), src->data() + src->size());
return "";
}
std::wstring to_wstring(const Blob& src)
{
if (src)
return std::wstring(src->data(), src->data() + src->size());
return L"";
}
std::string to_string(int src)
{
return std::to_string(src);
}
std::wstring to_wstring(int src)
{
return to_wstring(std::to_string(src));
}
std::string to_string(long long int src)
{
return std::to_string(src);
}
std::wstring to_wstring(long long int src)
{
return to_wstring(std::to_string(src));
}
std::string to_string(unsigned long long int src)
{
return std::to_string(src);
}
std::wstring to_wstring(unsigned long long int src)
{
return to_wstring(sqlite3pp::to_string(src));
}
std::string to_string(double src)
{
return std::to_string(src);
}
std::wstring to_wstring(double src)
{
return to_wstring(sqlite3pp::to_string(src));
}
bool isValidDate(const Date& t)
{
if (t.t < 1)
return false;
return true;
}
bool isValidDate(const Datetime& t)
{
if (t.tm_struct.tm_sec < 0 || t.tm_struct.tm_sec > 60)
return false;
if (t.tm_struct.tm_min < 0 || t.tm_struct.tm_min > 59)
return false;
if (t.tm_struct.tm_hour < 0 || t.tm_struct.tm_hour > 23)
return false;
if (t.tm_struct.tm_mday < 1 || t.tm_struct.tm_mday > 31)
return false;
if (t.tm_struct.tm_mon < 0 || t.tm_struct.tm_mon > 11)
return false;
if (t.tm_struct.tm_year < 0 || t.tm_struct.tm_year > 11000) // No more than 10,000 years into the future :-)
return false;
if (t.tm_struct.tm_wday < 0 || t.tm_struct.tm_wday > 6)
return false;
if (t.tm_struct.tm_yday < 0 || t.tm_struct.tm_yday > 365)
return false;
if (t.tm_struct.tm_isdst < 0 || t.tm_struct.tm_isdst > 24) // ToDo: Check what are valid values for this variable. Should be just 0 & 1.
return false;
return true;
}
std::string to_string(const Date& t)
{
if (isValidDate(t))
{
char buf[256] = { 0 };
std::tm tm_struct = { 0 };
gmtime_s(&tm_struct, &t.t);
strftime(buf, sizeof(buf), "%Y-%m-%db", &tm_struct);
return buf;
}
return "0000-00-00";
}
std::wstring to_wstring(const Date& src)
{
return to_wstring(sqlite3pp::to_string(src));
}
std::string to_string(const Datetime& t)
{
if (isValidDate(t))
{
char buf[256] = { 0 };
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &t.tm_struct);
return buf;
}
return "0000-00-00 00:00:00";
}
std::wstring to_wstring(const Datetime& src)
{
return to_wstring(sqlite3pp::to_string(src));
}
VerbosityLevels sql_base::m_VerbosityLevels = VBLV_ERROR;
void sql_base::SetVerbosityLevel(VerbosityLevels v)
{
m_VerbosityLevels = v;
}
VerbosityLevels sql_base::GetVerbosityLevel()
{
return m_VerbosityLevels;
}
db_api_root::db_api_root()
{
#ifdef SQLITE3PP_LOADABLE_EXTENSION
static sqlite3_api_routines Glbl_sqlite3_api_routines;
SQLITE_EXTENSION_INIT2(&Glbl_sqlite3_api_routines);
#endif // SQLITE3PP_LOADABLE_EXTENSION
}
int database::connect( const wchar_t* db_filename, int flags, const wchar_t * vfs )
{
if ( !borrowing_ )
{
disconnect();
}
return sqlite3_open16( db_filename, &db_ );
}
database::database(const wchar_t * db_filename, int flags, const wchar_t * vfs ) : db_( nullptr ), borrowing_( false )
{
// static int rc = ::sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, NULL);
if ( db_filename )
{
auto rc = connect( db_filename, flags, vfs );
if ( rc != SQLITE_OK )
throw database_error( "can't connect database" );
}
}
int database::execute( const std::string& sql )
{
return execute( sql.c_str() );
}
int database::execute( const std::wstring& sql )
{
return execute(to_string(sql) );
}
int database::attach(const wchar_t* db_filename, const wchar_t* name)
{
return executef("ATTACH '%q' AS '%q'", to_string(db_filename).c_str(), to_string(name).c_str());
}
int database::detach(const wchar_t* name)
{
return executef("DETACH '%q'", to_string(name).c_str());
}
int database::backup(const wchar_t* db_filename, database& destdb, const wchar_t* destdbname, backup_handler h, int step_page)
{
return backup(to_string(db_filename).c_str(), destdb, to_string(destdbname).c_str(), h, step_page);
}
statement::statement( database& db, wchar_t const* stmt ) : db_( db ), stmt_( 0 ), tail_( 0 )
{
if ( stmt )
{
auto rc = prepare( stmt );
if ( rc != SQLITE_OK )
throw database_error( db_ );
}
}
int statement::prepare( wchar_t const* stmt )
{
auto rc = finish();
if ( rc != SQLITE_OK )
return rc;
return prepare_impl( stmt );
}
int statement::prepare_impl( wchar_t const* stmt )
{
union
{
char const** a;
void const ** v;
}myw2v = {&tail_ };
int rc = sqlite3_prepare16_v2( db_.db_, stmt, static_cast<int>(std::wcslen( stmt )), &stmt_, myw2v.v );
return rc;
}
query::query( database& db, wchar_t const* stmt ) : statement( db, stmt )
{
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Added Global functions for global_db usage
///////////////////////////////////////////////////////////////////////////
database sql_base::global_db;
tstring sql_base::filenameOfOpenDB;
bool sql_base::bIsGlblDbOpen = false;
int sql_base::last_rc = 0;
const char sql_base::TableArg_PreExecuteArg[] = "PreExecuteArg";
const char sql_base::TableArg_WhereClauseArg[] = "WhereClauseArg";
const char sql_base::TableArg_DbFileNameArg[] = "DbFileNameArg";
const char sql_base::TableArg_ValueArg[] = "ValueArg";
void sql_base::set(tstring db_filename)
{
filenameOfOpenDB = db_filename;
bIsGlblDbOpen = true;
}
void sql_base::unset()
{
filenameOfOpenDB = tstring();
bIsGlblDbOpen = false;
}
database& setGlobalDB( const std::string& db_filename, ActionIfDatabaseOpen actionifopen)
{
return setGlobalDB(to_wstring(db_filename), actionifopen);
}
database& setGlobalDB( const std::wstring& db_filename_i, ActionIfDatabaseOpen actionifopen)
{
const std::wstring& db_filename = Get_UpdatedPathCopy(db_filename_i);
if (sql_base::bIsGlblDbOpen)
{
if (actionifopen == AIO_IgnoreOpenRequest ||
(actionifopen == AIO_SkipIfSameFile && sql_base::filenameOfOpenDB == to_tstring(db_filename)))
return sql_base::global_db;
if (actionifopen == AIO_CloseBeforeOpen)
Detach();
}
if (sql_base::bIsGlblDbOpen)
throw database_error("Trying to set Global DB with '" + to_string(db_filename.c_str()) + "' before detaching previous connection.");
sql_base::global_db = database(db_filename.c_str());
sql_base::set(to_tstring(db_filename));
return sql_base::global_db;
}
database& getGlobalDB( )
{
if (!sql_base::bIsGlblDbOpen)
throw database_error("Trying to get Global DB before it is opened.");
return sql_base::global_db;
}
int Execute( const std::string& sql )
{
return Execute(to_wstring(sql));
}
int Execute( const std::wstring& sql )
{
if (!sql_base::bIsGlblDbOpen)
throw database_error("Trying to Execute Global DB before it is opened. Query='" + to_string(sql.c_str()) + "'");
int rc = sql_base::last_rc = sql_base::global_db.execute( sql.c_str() );
// ToDo: Add logic here to repart error if rc!=SQLITE_OK
return rc;
}
int Connect( const char* cdb_filename, int flags, const char * vfs )
{
std::string db_filename = Get_UpdatedPathCopy(cdb_filename);
if (sql_base::bIsGlblDbOpen)
throw database_error("Trying to connect to '" + db_filename + "' after Global DB is open.");
int rc = sql_base::last_rc = sql_base::global_db.connect(db_filename.c_str(), flags, vfs);
if (SQLITE_OK == rc)
sql_base::set(to_tstring(db_filename));
else
throw database_error("Connect failed for '" + db_filename + "'.");
return rc;
}
int Connect(const wchar_t* cdb_filename, int flags, const wchar_t * vfs )
{
std::wstring db_filename = Get_UpdatedPathCopy(cdb_filename);
if (sql_base::bIsGlblDbOpen)
throw database_error("Trying to connect to '" + to_string(db_filename) + "' after Global DB is open.");
int rc = sql_base::last_rc = sql_base::global_db.connect(db_filename.c_str(), flags, vfs);;
if (SQLITE_OK == rc)
sql_base::set(to_tstring(db_filename));
else
throw database_error("Connect failed for '" + to_string(db_filename) + "'.");
return rc;
}
int Attach( const char* cdb_filename, const char* name )
{
std::string db_filename = Get_UpdatedPathCopy(cdb_filename);
if (sql_base::bIsGlblDbOpen)
throw database_error("Trying to attach to '" + db_filename + "' after Global DB is open.");
int rc = sql_base::last_rc = sql_base::global_db.attach(db_filename.c_str(), name);
if (SQLITE_OK == rc)
sql_base::set(to_tstring(db_filename));
else
throw database_error("Attach failed for '" + db_filename + "'.");
return rc;
}
int Attach( const wchar_t* cdb_filename, const wchar_t* name )
{
std::wstring db_filename = Get_UpdatedPathCopy(cdb_filename);
if (sql_base::bIsGlblDbOpen)
throw database_error("Trying to attach to '" + to_string(db_filename) + "' after Global DB is open.");
int rc = sql_base::last_rc = sql_base::global_db.attach( db_filename.c_str(), name );
if (SQLITE_OK == rc)
sql_base::set(to_tstring(db_filename));
else
throw database_error("Attach failed for '" + to_string(db_filename) + "'.");
return rc;
}
int Detach()
{
if (!sql_base::bIsGlblDbOpen)
throw database_error("Trying to detached before Global DB is open.");
int rc = sql_base::last_rc = sql_base::global_db.detach(sql_base::filenameOfOpenDB.c_str());
if (SQLITE_OK == rc)
sql_base::unset();
else
throw database_error("Detach failed for '" + to_string(sql_base::filenameOfOpenDB) + "'.");
return rc;
}
int Backup( const char* cdb_filename, database & destdb, const char* cdestdbname, database::backup_handler h, int step_page )
{
std::string db_filename = Get_UpdatedPathCopy(cdb_filename);
std::string destdbname = Get_UpdatedPathCopy(cdestdbname);
if (!sql_base::bIsGlblDbOpen)
throw database_error("Trying to use Global DB before it has been opened.");
return sql_base::global_db.backup(db_filename.c_str(),destdb,destdbname.c_str(),h,step_page);
}
int Backup( const wchar_t* cdb_filename, database & destdb, const wchar_t* cdestdbname, database::backup_handler h, int step_page )
{
std::wstring db_filename = Get_UpdatedPathCopy(cdb_filename);
std::wstring destdbname = Get_UpdatedPathCopy(cdestdbname);
if (!sql_base::bIsGlblDbOpen)
throw database_error("Trying to use Global DB before it has been opened.");
return sql_base::global_db.backup(db_filename.c_str(), destdb, destdbname.c_str(), h, step_page );
}
std::string GetDbErrMsg()
{
if (!sql_base::bIsGlblDbOpen)
return "Error: Failed to open global database before using it";
return sql_base::global_db.error_msg();
}
std::wstring GetDbErrMsgW()
{
if (!sql_base::bIsGlblDbOpen)
return L"Error: Failed to open global database before using it";
return to_wstring(sql_base::global_db.error_msg());
}
int GetDbErrNo()
{
if (!sql_base::bIsGlblDbOpen)
return -1;
return sql_base::global_db.error_code();
}
int GetDbExtErrNo()
{
if (!sql_base::bIsGlblDbOpen)
return -1;
return sql_base::global_db.extended_error_code();
}
bool dir_exists(std::string foldername, bool RepaceEnvVar)
{
if (RepaceEnvVar)
foldername = Get_UpdatedPathCopy(foldername);
struct stat st = { 0 };
stat(foldername.c_str(), &st);
return st.st_mode & S_IFDIR;
}
bool dir_exists(std::wstring foldername, bool RepaceEnvVar)
{
if (RepaceEnvVar)
foldername = Get_UpdatedPathCopy(foldername);
struct _stat st = { 0 };
_wstat(foldername.c_str(), &st);
return st.st_mode & S_IFDIR;
}
bool file_exists(std::string filename, bool RepaceEnvVar)
{
if (RepaceEnvVar)
filename = Get_UpdatedPathCopy(filename);
struct stat st = { 0 };
return (stat(filename.c_str(), &st) == 0);
}
bool file_exists(std::wstring filename, bool RepaceEnvVar)
{
if (RepaceEnvVar)
filename = Get_UpdatedPathCopy(filename);
struct _stat st = { 0 };
return (_wstat(filename.c_str(), &st) == 0);
}
bool copy_file(std::wstring Src, std::wstring Dest, bool OverWriteIfExist)
{
Src = Get_UpdatedPathCopy(Src);
Dest = Get_UpdatedPathCopy(Dest);
if (file_exists(Dest))
{
if (OverWriteIfExist)
{
if (!DeleteFileW(Dest.c_str()))
return false;
}
else
return false;
}
bool RetrnVal = false;
std::ofstream outfile(Dest.c_str(), std::ios::out | std::ios::binary);
if (outfile.is_open())
{
std::ifstream is(Src.c_str(), std::ios::in | std::ios::binary);
if (is.is_open())
{
is.seekg(0, is.end);
const std::streamoff length = is.tellg();
is.seekg(0, is.beg);
char *buffer = new char[static_cast<size_t>(length) + 1]();
if (buffer)
{
is.read(buffer, length);
outfile.write(buffer, length);
delete[] buffer;
RetrnVal = true;
}
is.close();
}
outfile.close();
}
return RetrnVal;
}
bool copy_file(std::string Src, std::string Dest, bool OverWriteIfExist)
{
return copy_file(to_wstring(Src), to_wstring(Dest), OverWriteIfExist);
}
void replace_all(std::wstring & data, const std::wstring &toSearch, const std::wstring &replaceStr)
{
// Get the first occurrence
size_t pos = data.find(toSearch);
// Repeat till end is reached
while (pos != std::string::npos)
{
// Replace this occurrence of Sub String
data.replace(pos, toSearch.size(), replaceStr);
// Get the next occurrence from the current position
pos = data.find(toSearch, pos + replaceStr.size());
}
}
void CheckEnv(std::wstring &src, const std::string &VarName, const std::string VarNamePrefix, const std::string VarNamePostfix)
{
char env_p[_MAX_PATH] = { 0 };
size_t Sz = 0;
if (!getenv_s(&Sz, env_p, sizeof(env_p), VarName.c_str()))
{
const std::wstring EncVarName = to_wstring(VarNamePrefix + VarName + VarNamePostfix);
replace_all(src, EncVarName, to_tstring(env_p));
}
}
std::string GetUpdatedSrcPath(std::string &src, int EnvVarToFetch, const std::string VarNamePrefix, const std::string VarNamePostfix)
{
src = to_string(Get_UpdatedPathCopy(to_wstring(src), EnvVarToFetch, VarNamePrefix, VarNamePostfix));
return src;
}
std::string Get_UpdatedPathCopy(std::string src, int EnvVarToFetch, const std::string VarNamePrefix, const std::string VarNamePostfix)
{
return to_string(Get_UpdatedPathCopy(to_wstring(src), EnvVarToFetch, VarNamePrefix, VarNamePostfix));
}
std::wstring GetUpdatedSrcPath(std::wstring &src, int EnvVarToFetch, const std::string VarNamePrefix, const std::string VarNamePostfix)
{ // EnvVarToFetch BIT Settings: 1=Get User Var, 2=Get System Paths, 4=Get Misc Var
if (EnvVarToFetch & 1)
{
// User level environmental variables
CheckEnv(src, "APPDATA", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "USERNAME", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "HOMEDRIVE", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "HOMEPATH", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "USERPROFILE", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "APPDATA", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "LOCALAPPDATA", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "TEMP", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "TMP", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "ONEDRIVE", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "USERDOMAIN", VarNamePrefix, VarNamePostfix);
}
if (EnvVarToFetch & 2)
{
// System path level environmental variables
CheckEnv(src, "SYSTEMDRIVE", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "COMMONPROGRAMFILES", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "PROGRAMFILES", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "PROGRAMDATA", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "COMMONPROGRAMFILES(x86)", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "WINDIR", VarNamePrefix, VarNamePostfix);
}
if (EnvVarToFetch & 4)
{
// Miscellaneous environmental variables
CheckEnv(src, "COMPUTERNAME", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "DATE", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "TIME", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "RANDOM", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "OS", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "CD", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "PUBLIC", VarNamePrefix, VarNamePostfix);
CheckEnv(src, "ALLUSERSPROFILE", VarNamePrefix, VarNamePostfix);
}
return src;
}
std::wstring Get_UpdatedPathCopy(std::wstring src, int EnvVarToFetch, const std::string VarNamePrefix, const std::string VarNamePostfix)
{
return GetUpdatedSrcPath(src, EnvVarToFetch, VarNamePrefix, VarNamePostfix);
}
// Additional implementation for SQLite3pp
#ifndef SQLITE3PP_CONVERT_TO_RESULTING_AFFINITY
#ifndef SQLITE3PP_NO_UNICODE
wchar_t const* query::rows::get(int idx, wchar_t const*) const
{
return reinterpret_cast<wchar_t const*>(sqlite3_column_text16(stmt_, idx));
}
std::wstring query::rows::get(int idx, const std::wstring&) const
{
#ifdef SQLITE3PP_ALLOW_NULL_STRING_RETURN
bool AllowNullStringReturn = true;
#else
bool AllowNullStringReturn = false;
#endif // !SQLITE3PP_ALLOW_NULL_STRING_RETURN
std::wstring value;
const char * strtype = sqlite3_column_decltype(stmt_, idx);
if (!strtype)
{
V_COUT(WARN, "Received NULL value when getting column type for idx " << idx << ". Treating type as ASCII or UTF8.");
}
bool GetUnicodeString = false;
if (!strtype || strcmp(strtype, "TEXT") == 0 || strncmp("CHARACTER", strtype, 9) == 0 || strncmp("VARYING CHARACTER", strtype, 17) == 0 || strncmp("VARCHAR", strtype, 7) == 0)
GetUnicodeString = false;
else if ( strncmp("NCHAR", strtype, 5) == 0 || strncmp("NVARCHAR", strtype, 8) == 0 || strncmp("NATIVE CHARACTER", strtype, 16) == 0)
GetUnicodeString = true;
else
{
V_COUT(WARN, "Could not find a string type to process. Treating type as ASCII or UTF8.");
assert(0);// Code should NOT get here. If it does something went wrong.
GetUnicodeString = false;
}
union
{ // This union is here for debugging purposes.
wchar_t const* Val_w;
char const* Val_a;
const void* Val;
};
if (GetUnicodeString)
{
Val_w = get(idx, (wchar_t const*)0);
if (Val_w || AllowNullStringReturn)
value = Val_w;
}
else
{
Val_a = get(idx, (char const*)0);
if (Val_a || AllowNullStringReturn)
value = to_wstring(Val_a);
}
return value;
}
database_error::database_error(const std::string& msg) : std::runtime_error(msg.c_str())
{
}
#endif// !SQLITE3PP_NO_UNICODE
Blob query::rows::get(int idx, const Blob&) const
{
const int data_len = column_bytes(idx);
const unsigned char* ptr = static_cast<const unsigned char*>(sqlite3_column_blob(stmt_, idx));
Blob data(new std::vector<unsigned char>(ptr, ptr + data_len));
return data;
}
Clob query::rows::get(int idx, const Clob&) const
{
const int data_len = column_bytes(idx);
const char* ptr = static_cast<const char*>(sqlite3_column_blob(stmt_, idx));
Clob data(new std::vector<char>(ptr, ptr + data_len));
return data;
}
unsigned char query::rows::get(int idx, const unsigned char&) const
{
return static_cast<unsigned char>(get(idx, int()));
}
short int query::rows::get(int idx, const short int&) const
{
return static_cast<short int>(get(idx, int()));
}
bool query::rows::get(int idx, const bool&) const
{
return static_cast<bool>(get(idx, int()));
}
unsigned long long int query::rows::get(int idx, const unsigned long long int&) const
{
return static_cast<unsigned long long int>(sqlite3_column_int64(stmt_, idx));
}
Date query::rows::get(int idx, const Date&) const
{
const char* s = reinterpret_cast<const char*>(sqlite3_column_text(stmt_, idx));
std::tm d = { 0 };
Date data = { 0 };
int rc = sscanf_s(s, "%d-%d-%d", &d.tm_year, &d.tm_mon, &d.tm_mday);
if (rc < 1 || !d.tm_mday)
{
if (s) V_COUT(WARN, "Could not parse value '" << s << "' into a date.");
if (rc < 1) V_COUT(WARN, "sscanf_s returned value less than 1 indicating invalid data.");
if (!d.tm_mday) V_COUT(WARN, "tm_mday == 0. Invalid value.");
return data;
}
if (d.tm_year > 1900)
{
d.tm_year -= 1900;
d.tm_mon -= 1;
}
data.t = mktime(&d);
if (data.t == -1)
{
V_COUT(WARN, "Received -1 from mktime.");
return Date();
}
return data;
}
Datetime query::rows::get(int idx, const Datetime&) const
{
Datetime data = { 0 };
const char* s = reinterpret_cast<const char*>(sqlite3_column_text(stmt_, idx));
int rc = sscanf_s(s, "%d-%d-%d %d:%d:%d", &data.tm_struct.tm_year, &data.tm_struct.tm_mon, &data.tm_struct.tm_mday, &data.tm_struct.tm_hour, &data.tm_struct.tm_min, &data.tm_struct.tm_sec);
if (rc < 1 || !data.tm_struct.tm_mday)
{
if (s) V_COUT(WARN, "Could not parse value '" << s << "' into a date.");
if (rc < 1) V_COUT(WARN, "sscanf_s returned value less than 1 indicating invalid data.");
if (!data.tm_struct.tm_mday) V_COUT(WARN, "tm_mday == 0. Invalid value.");
return Datetime();
}
if (data.tm_struct.tm_year > 1900)
{
data.tm_struct.tm_year -= 1900;
data.tm_struct.tm_mon -= 1;
}
return data;
}
std::wostream& operator<<(std::wostream& os, const sql_base::Character& t)
{
os << to_wstring(t);
return os;
}
std::ostream& operator<<(std::ostream& os, const sql_base::Nchar& t)
{
os << to_string(t);
return os;
}
std::wostream& operator<<(std::wostream& os, const sqlite3pp::Blob& t)
{
std::string data(t->data(), t->data() + t->size());
std::wstring wdata = to_wstring(data);
os.write(wdata.c_str(), wdata.size());
return os;
}
std::ostream& operator<<(std::ostream& os, const sqlite3pp::Blob& t)
{
const char* ptr = (const char*)t->data();
os.write(ptr, t->size());
return os;
}
std::wostream& operator<<(std::wostream& os, const sqlite3pp::Clob& t)
{
std::string data(t->data(), t->data() + t->size());
std::wstring wdata = to_wstring(data);
os.write(wdata.c_str(), wdata.size());
return os;
}
std::ostream& operator<<(std::ostream& os, const sqlite3pp::Clob& t)
{
const char* ptr = (const char*)t->data();
os.write(ptr, t->size());
return os;
}
std::wostream& operator<<(std::wostream& os, const sqlite3pp::Datetime& t)
{
if (isValidDate(t))
{
wchar_t buf[256] = { 0 };
wcsftime(buf, sizeof(buf), L"%Y-%m-%d %H:%M:%S", &t.tm_struct);
os << buf;
}
else
{
V_COUT(WARN, "tm_mday == 0. Invalid value.");
os << L"0000-00-00 00:00:00";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const sqlite3pp::Datetime& t)
{
if (isValidDate(t))
{
char buf[256] = { 0 };
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &t.tm_struct);
os << buf;
}
else
{
V_COUT(WARN, "tm_mday == 0. Invalid value.");
os << "0000-00-00 00:00:00";
}
return os;
}
std::wostream& operator<<(std::wostream& os, const sqlite3pp::Date& t)
{
if (isValidDate(t))
{
wchar_t buf[256] = { 0 };
std::tm tm_struct = { 0 };
gmtime_s(&tm_struct, &t.t);
wcsftime(buf, sizeof(buf), L"%Y-%m-%d", &tm_struct);
os << buf;
}
else
{
V_COUT(WARN, "t.t = Invalid Falue.");
os << L"0000-00-00";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const sqlite3pp::Date& t)
{
if (isValidDate(t))
{
char buf[256] = { 0 };
std::tm tm_struct = { 0 };
gmtime_s(&tm_struct, &t.t);
strftime(buf, sizeof(buf), "%Y-%m-%db", &tm_struct);
os << buf;
}
else
{
V_COUT(WARN, "t.t = Invalid Falue.");
os << "0000-00-00";
}
return os;
}
#endif // !SQLITE3PP_CONVERT_TO_RESULTING_AFFINITY
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Start of implementation for SQLiteClassBuilder
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
// sqlite_master is used when querying all the tables in a SQLite DB
class sqlite_master
{
public:
using StrType = std::string;
static StrType getTableName() { return "sqlite_master"; }
static StrType getColumnNames() { return "type, name, tbl_name, rootpage, sql"; }
static StrType getSelecColumnNames() { return "type, name, tbl_name, rootpage, sql"; }
template<class T> void getStreamData(T q) { q.getter() >> type >> name >> tbl_name >> rootpage >> sql; }
static int getColumnCount() { return 5; }
public:
StrType type;
StrType name;
StrType tbl_name;
StrType rootpage;
StrType sql;
};
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
// SQLiteClassBuilder Predefines.
// Predefined string options
const StrOptions SQLiteClassBuilder::strOpt_std_string = { "std::string", "sqlite3pp::to_string", "", "", "#include <string>" };
const StrOptions SQLiteClassBuilder::strOpt_std_wstring = { "std::wstring", "sqlite3pp::to_wstring", "L", "", "#include <string>" };
const StrOptions SQLiteClassBuilder::strOpt_sql_tstring = { "sqlite3pp::tstring", "sqlite3pp::to_tstring", "T_(", ")", "#include \"sqlite3pp_ez.h\"" };
const StrOptions SQLiteClassBuilder::strOpt_sql_tstring_T = { "sqlite3pp::tstring", "sqlite3pp::to_tstring", "_T(", ")", "#include \"sqlite3pp_ez.h\"" };
// Predefined MiscOptions for common settings
const MiscOptions SQLiteClassBuilder::MiscOpt_max = { ",", false, false, false, false, false, false, false, false, false };
const MiscOptions SQLiteClassBuilder::MiscOpt_min = { ",", true, true, true, true, true, false, false, true, true };
const MiscOptions SQLiteClassBuilder::MiscOpt_var = { ",", true, true, true, true, true, true, false, true, true };
// Default settings for HeaderOpt
const HeaderOpt SQLiteClassBuilder::HeadersCreatedSqlDir = { "SQL\\", "sql_", "", "h", "..\\sqlite3pp_ez.h" };
const HeaderOpt SQLiteClassBuilder::HeadersCreadedBaseDir = { "", "sql_", "", "h", "sqlite3pp_ez.h" };
const char *SQLiteClassBuilder::Nill = "#NILL#";
const char *SQLiteClassBuilder::CreateHeaderForAllTables = "%_CreateHeaderForAllTables_%";
////////////////////////////////////////////////////////////////////////////////////////////
std::string SQLiteClassBuilder::GetType(const std::string &tblVw, const std::string &colName, const char* str_org)
{
std::string strtype = GetType_s(tblVw, colName, str_org);
V_COUT(DETAIL, "Using type '" << strtype << "' for column '" << colName << "' in table/view '" << tblVw << "'.");
return strtype;
}
std::string SQLiteClassBuilder::GetType_s(const std::string &tblVw, const std::string &colName, const char* str_org)
{
const std::string DefaultType = "Text";
if (!str_org)
{
// Logging out as DEBUG because some views do return NULL value for the column type.
V_COUT(DEBUG, "Entered with DB type NULL value for column '" << colName << "' in table/view '" << tblVw << "'.\nGracefully continuing by returning default type '" << DefaultType << "'.");
return DefaultType;
}
char str[99] = { 0 };
strcpy_s(str, str_org);
_strupr_s(str);
// There's no practical method for handling blob or clob other than the Blob and Clob type, so don't even include them in an option to declare them any other way.
if (strcmp("BLOB", str) == 0)
return "Blob";
if (strcmp("CLOB", str) == 0)
return "Clob";
#ifdef SQLITE3PP_CONVERT_TO_RESULTING_AFFINITY // If defined convert types to Resulting Affinity (int, double, or StrType)
bool UseBaseTypes = true;
#else // Use SQLite3 sub types and use type names
bool UseBaseTypes = false;
#endif //SQLITE3PP_CONVERT_TO_RESULTING_AFFINITY
if (UseBaseTypes || m_options.m.use_basic_types_only)
{
// Only output detail once
static bool HasLoggedDetails = false;
if (!HasLoggedDetails)
{
HasLoggedDetails = true;
V_COUT(DETAIL, "Only setting DB types to basic types due to compiler #define SQLITE3PP_CONVERT_TO_RESULTING_AFFINITY(" << UseBaseTypes << ") or input option use_basic_types_only(" << m_options.m.use_basic_types_only << ")");
}
if (strcmp("INTEGER", str) == 0 || strcmp("INT", str) == 0 || strcmp("TINYINT", str) == 0 || strcmp("SMALLINT", str) == 0 || strcmp("MEDIUMINTSMALLINT", str) == 0 || strcmp("BIGINT", str) == 0 || strcmp("UNSIGNED BIG INT", str) == 0 || strcmp("INT2", str) == 0 || strcmp("INT8", str) == 0)