-
Notifications
You must be signed in to change notification settings - Fork 19
/
ASGSQLite3_unicode.pas
5685 lines (5149 loc) · 203 KB
/
ASGSQLite3_unicode.pas
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
// To enable debugging remove the dot. Do NOT forget to re-insert before
// deploying to production since this feature will slow down this component
// significantly
{.$DEFINE DEBUG_ENABLED} // Enables Debug information
{.$DEFINE DEBUG_VERY_LOUD}
{.$DEFINE DEBUG_LOUD}
// Disable this for ignoring IProvider interface (for D4)
{$DEFINE IPROVIDER}
// enable this if you want to link the SQLite library statically. (No need for dll)
// DON'T FORGET TO APPLY CORRECT OBJ VERSION IN THIS SOURCE ON LINE {$L 'OBJ\SQLite<<somerversion>>.obj'}
{.$DEFINE SQLite_Static}
{$I asqlite_def.inc}
{$HINTS OFF}
unit ASGSQLite3_unicode;
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Albert Drent
Description: SQLite 3 DataSet class (encapsulates the Delphi DataSet Class)
Target: Delphi 2009+
Creation: October 2009 (based on the original source for Delphi 4+ November 2003)
Version: 2009.12.A beta
EMail: [email protected] (www.aducom.com/nl/eu, www.aducomportal.nl)
Support: [email protected] (supportforum on www.aducom.com)
Please post any questions, remarks etc. to the support forum. We
useually answer questions within days, mostly hours.
Unsollicited mail to support will be intercepted by our spamfilters
and probabely never be heard of.
Legal issues: Copyright (C) 2003..2009 by Aducom Software
Aducom Software
Eckhartstr 61
9746 BN Groningen
Netherlands
(For those who like to send a postcard, my kids love the foreign stamps)
Open Source licence (BSD: http://www.opensource.org/licenses/bsd-license.php)
Copyright (c) 2003..2009, Aducom Software
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of Aducom Software nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Acknowledgement
These components were written for our own needs. Since SQLite is
a freeware component we like to donate this one to the community
too. Parts of the code is adapted from several sources, but mainly
from a sample and the vcl sources of Borland itself. And, of
course, we did a lot and still are...
To Do
A lot...(?)
We are very busy, but will develop on our needs. If anyone can
contribute, please feel welcome. Alter the source with lots of comments
and mail it to me. If it works right I will add it to the official
source and add your credit here below. Before you start, please
put a request on the forum. It would be a shame and a waste of your
time if you develop something which already is... and I need to set
the spamfilter right to let you pass through.
History:
See releasenotes.txt
*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * }
interface
uses
DB,
DBCommon,
// Dialogs,
Classes,
Windows,
SysUtils,
SqlTimSt,
Variants,
{$IFDEF ASQLite_XE3PLUS}System.Generics.Collections,{$ENDIF}
ASGRout3_unicode;
const
SQLiteVersion = 'ASGSQLiteUC V2009.12.A beta release candidate';
MAX_FIELDS = 2048;
MaxBuf = 30000; // max stringbuffer for record (length) (excluding blob's)
SQLITE_OK = 0; // Successful result */
SQLITE_ERROR = 1; // SQL error or missing database */
SQLITE_INTERNAL = 2; // An internal logic error in SQLite */
SQLITE_PERM = 3; // Access permission denied */
SQLITE_ABORT = 4; // Callback routine requested an abort */
SQLITE_BUSY = 5; // The database file is locked */
SQLITE_LOCKED = 6; // A table in the database is locked */
SQLITE_NOMEM = 7; // A malloc() failed */
SQLITE_READONLY = 8; // Attempt to write a readonly database */
SQLITE_INTERRUPT = 9; // Operation terminated by sqlite_interrupt() */
SQLITE_IOERR = 10; // Some kind of disk I/O error occurred */
SQLITE_CORRUPT = 11; // The database disk image is malformed */
SQLITE_NOTFOUND = 12; // (Internal Only) Table or record not found */
SQLITE_FULL = 13; // Insertion failed because database is full */
SQLITE_CANTOPEN = 14; // Unable to open the database file */
SQLITE_PROTOCOL = 15; // Database lock protocol error */
SQLITE_EMPTY = 16; // (Internal Only) Database table is empty */
SQLITE_SCHEMA = 17; // The database schema changed */
SQLITE_TOOBIG = 18; // Too much data for one row of a table */
SQLITE_CONSTRAINT = 19; // Abort due to contraint violation */
SQLITE_MISMATCH = 20; // Data type mismatch */
SQLITE_MISUSE = 21; // Library used incorrectly */
SQLITE_NOLFS = 22; // Uses OS features not supported on host */
SQLITE_AUTH = 23; // Authorization denied */
SQLITE_ROW = 100; // sqlite_step() has another row ready */
SQLITE_DONE = 101; // sqlite_step() has finished executing */
SQLITE_CREATE_INDEX = 1; // Index Name Table Name */
SQLITE_CREATE_TABLE = 2; // Table Name NULL */
SQLITE_CREATE_TEMP_INDEX = 3; // Index Name Table Name */
SQLITE_CREATE_TEMP_TABLE = 4; // Table Name NULL */
SQLITE_CREATE_TEMP_TRIGGER = 5; // Trigger Name Table Name */
SQLITE_CREATE_TEMP_VIEW = 6; // View Name NULL */
SQLITE_CREATE_TRIGGER = 7; // Trigger Name Table Name */
SQLITE_CREATE_VIEW = 8; // View Name NULL */
SQLITE_DELETE = 9; // Table Name NULL */
SQLITE_DROP_INDEX = 10; // Index Name Table Name */
SQLITE_DROP_TABLE = 11; // Table Name NULL */
SQLITE_DROP_TEMP_INDEX = 12; // Index Name Table Name */
SQLITE_DROP_TEMP_TABLE = 13; // Table Name NULL */
SQLITE_DROP_TEMP_TRIGGER = 14; // Trigger Name Table Name */
SQLITE_DROP_TEMP_VIEW = 15; // View Name NULL */
SQLITE_DROP_TRIGGER = 16; // Trigger Name Table Name */
SQLITE_DROP_VIEW = 17; // View Name NULL */
SQLITE_INSERT = 18; // Table Name NULL */
SQLITE_PRAGMA = 19; // Pragma Name 1st arg or NULL */
SQLITE_READ = 20; // Table Name Column Name */
SQLITE_SELECT = 21; // NULL NULL */
SQLITE_TRANSACTION = 22; // NULL NULL */
SQLITE_UPDATE = 23; // Table Name Column Name */
SQLITE_ATTACH = 24; // Filename NULL */
SQLITE_DETACH = 25; // Database Name NULL */
SQLITE_DENY = 1; // Abort the SQL statement with an error */
SQLITE_IGNORE = 2; // Don't allow access, but don't generate an error */
SQLITE_STATIC =pointer(0);
SQLITE_TRENT =pointer(-1);
Crlf : string = #13#10;
Q = '''';
SQLITE_INTEGER = 1;
SQLITE_FLOAT = 2;
SQLITE_TEXT = 3;
SQLITE_BLOB = 4;
SQLITE_NULL = 5;
type
TASQLiteCharset = (ascUnknown, ascUTF8, ascUTF16, ascUTF16le, ascUTF16be);
{$IFNDEF ASQLite_XE2PLUS}
NativeInt = LongInt;
{$ENDIF}
{$IFNDEF UNICODE_SUPPORT}
UnicodeChar = WideChar;
PUnicodeChar = PWideChar;
UnicodeString = WideString;
PUnicodeString = PWideString;
{$ELSE}
UnicodeChar = Char;
PUnicodeChar = PChar;
{$ENDIF}
Dataset_PByte = PByte;
{$IFDEF ASQLite_XE3PLUS}
{$IFDEF ASQLite_XE4PLUS}
Dataset_TRecBuf = TRecBuf;
{$ELSE}
Dataset_TRecBuf = TRecordBuffer;
{$ENDIF}
Dataset_TRecordBuffer = TRecordBuffer;
Dataset_TValueBuffer = TValueBuffer;
Dataset_TBookmark = TBookmark;
TList_TField = TList<TField>;
{$ELSE}
Dataset_TRecBuf = Dataset_PByte;
Dataset_TRecordBuffer = Dataset_PByte;
Dataset_TValueBuffer = Pointer;
Dataset_TBookmark = Pointer;
TList_TField = TList;
{$ENDIF}
pInteger = ^integer;
pPointer = ^Pointer;
pSmallInt = ^smallint;
pFloat = ^extended;
pBoolean = ^boolean;
TConvertBuffer = array[1..255] of AnsiChar;
TSQLite3_Callback = function(UserData: Pointer; ColumnCount: Integer; ColumnValues, ColumnNames: PPointer): Integer; cdecl;
// TSQLiteExecCallback = function(Sender: TObject; Columns: integer; ColumnValues: Pointer; ColumnNames: Pointer): integer of object; cdecl;
TSQLiteBusyCallback = function(Sender: TObject; ObjectName: PAnsiChar; BusyCount: integer): integer of object; cdecl;
TOnData = procedure(Sender: TObject; Columns: integer; ColumnNames, ColumnValues: string) of object;
TOnBusy = procedure(Sender: TObject; ObjectName: string; BusyCount: integer; var Cancel: boolean) of object;
TOnQueryComplete = procedure(Sender: TObject) of object;
TASQLite3NotifyEvent = procedure(Sender: TObject) of object;
// structure for holding field information. It is used by GetTableInfo
TASQLite3Field = class
public
FieldNumber: integer;
FieldName: string;
FieldType: string;
FieldNN: integer; // 1 if notnull
FieldDefault: string;
FieldPK: integer; // 1 if primary key
end;
// object to 'play' with SQLite's default settings
TASQLite3Pragma = class(TComponent)
private
FTempCacheSize: integer;
FDefaultCacheSize: integer;
FDefaultSynchronous: string;
FDefaultTempStore: string;
FTempStore: string;
FSynchronous: string;
protected
function GetTempCacheSize: string;
function GetDefaultCacheSize: string;
function GetDefaultSynchronous: string;
function GetDefaultTempStore: string;
function GetTempStore: string;
function GetSynchronous: string;
published
{ Published declarations }
property TempCacheSize: integer read FTempCacheSize write FTempCacheSize;
property DefaultCacheSize: integer read FDefaultCacheSize write FDefaultCacheSize;
property DefaultSynchronous: string read FDefaultSynchronous
write FDefaultSynchronous;
property DefaultTempStore: string read FDefaultTempStore write FDefaultTempStore;
property TempStore: string read FTempStore write FTempStore;
property Synchronous: string read FSynchronous write FSynchronous;
end;
// component to log messages
// it's for debugging purpose and may be obsolete due
// to the event implementation. not sure yet...
TASQLite3Log = class(TComponent)
private
FLogFile: string;
FLogDebugOut: boolean;
FAppend: boolean;
FLogSQL: boolean;
FLogInt: boolean;
protected
public
procedure Display(Msg: string);
published
{ Published declarations }
property LogFile: string read FLogFile write FLogFile;
property LogDebugOut: boolean read FLogDebugOut write FLogDebugOut; // 20040225
property Append: boolean read FAppend write FAppend;
property LogSQL: boolean read FLogSQL write FLogSQL;
property LogInternals: boolean read FLogInt write FLogInt;
end;
// This component can be used to store sql outside the pascal source.
// It is useful for automatically creating tables on open of a temporary database
// (i.e. in-memory database)
TASQLite3InlineSQL = class(TComponent)
private
FSQL: TStrings;
procedure SetSQL(const Value: TStrings);
function GetSQL: TStrings;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property SQL: TStrings read GetSQL write SetSQL;
end;
{ Basic Database component }
TASQLite3DB = class;
TCompareFunc = function(db : TASQLite3DB; s1Len : integer; s1 : PAnsiChar; s2Len : integer; s2 : PAnsiChar) : integer; cdecl;
TASQLite3DB = class(TComponent)
private
{ Private declarations }
FAfterConnect: TASQLite3NotifyEvent;
FBeforeConnect: TASQLite3NotifyEvent;
FAfterDisconnect: TASQLite3NotifyEvent;
FBeforeDisconnect: TASQLite3NotifyEvent;
FOnBusy: TASQLite3NotifyEvent;
function FGetDefaultExt: string;
function FGetDriverDLL: string;
procedure GetCharset;
protected
{ Protected declarations }
FInlineSQL: TASQLite3InlineSQL;
FExecuteInlineSQL: boolean;
FDatabase: string;
FTransactionType: string;
FInTransaction : boolean;
FSQLiteVersion: string;
FDefaultExt: string;
FDefaultDir: string;
FDriverDll: string;
FConnected: boolean;
FMustExist: boolean;
FTimeOut : integer;
FVersion: string;
FCharEnc: string;
FSQL : string;
FUtf8: boolean;
DBHandle: Pointer;
FASQLitePragma: TASQLite3Pragma;
FASQLiteLog: TASQLite3Log;
FLastError: string;
fEncoding:TASQLiteCharset;
SQLite3_Open16: function(dbname: PChar; var db: pointer): integer; cdecl;
SQLite3_Close: function(db: pointer): integer; cdecl;
SQLite3_Exec: function(DB: Pointer; SQLStatement: PAnsiChar; Callback: TSQLite3_Callback;
UserDate: Pointer; var ErrMsg: PAnsiChar): Integer; cdecl;
SQLite3_LibVersion: function(): PAnsiChar; cdecl;
SQLite3_Errmsg16: function(db: pointer): PWideChar; cdecl;
SQLite3_GetTable: function(db: Pointer; SQLStatement: PAnsiChar; var ResultPtr: Pointer;
var RowCount: cardinal; var ColCount: cardinal; var ErrMsg: PAnsiChar): integer; cdecl;
SQLite3_FreeTable: procedure(Table: PAnsiChar); cdecl;
SQLite3_FreeMem: procedure(P: PAnsiChar); cdecl;
SQLite3_Complete16: function(P: PWideChar): boolean; cdecl;
SQLite3_LastInsertRow: function(db: Pointer): integer; cdecl;
SQLite3_Cancel: procedure(db: Pointer); cdecl;
SQLite3_BusyHandler: procedure(db: Pointer; CallbackPtr: Pointer; Sender: TObject); cdecl;
SQLite3_BusyTimeout: procedure(db: Pointer; TimeOut: integer); cdecl;
SQLite3_Changes: function(db: Pointer): integer; cdecl;
SQLite3_Prepare16: function(db: Pointer; SQLStatement: PWideChar; nBytes: integer;
var hstatement: pointer; var Tail: PWideChar): integer; cdecl;
SQLite3_Finalize: function(hstatement: pointer): integer; cdecl;
SQLite3_Reset: function(hstatement: pointer): integer; cdecl;
SQLite3_Step: function(hstatement: pointer): integer; cdecl;
SQLite3_Column_blob: function(hstatement: pointer; iCol: integer): pointer; cdecl;
SQLite3_Column_bytes: function(hstatement: pointer; iCol: integer): integer; cdecl;
SQLite3_Column_bytes16: function(hstatement: pointer; iCol: integer): integer; cdecl;
SQLite3_Column_count: function(hstatement: pointer): integer; cdecl;
SQLite3_Column_decltype16: function(hstatement: pointer; iCol: integer): PChar; cdecl;
SQLite3_Column_double: function(hstatement: pointer; iCol: integer): double; cdecl;
SQLite3_Column_int: function(hstatement: pointer; iCol: integer): integer; cdecl;
SQLite3_Column_int64: function(hstatement: pointer; iCol: integer): int64; cdecl;
SQLite3_Column_name16: function(hstatement: pointer; iCol: integer): PWideChar; cdecl;
SQLite3_Column_text: function(hstatement: pointer; iCol: integer): PAnsiChar; cdecl;
SQLite3_Column_text16: function(hstatement: pointer; iCol: integer): PWideChar; cdecl;
SQLite3_Column_type: function(hstatement: pointer; iCol: integer): integer; cdecl;
SQLite3_Bind_Null: function(hstatement: pointer; iCol: integer): integer; cdecl;
SQLite3_Bind_Blob: function(hstatement: pointer; iCol: integer; buf: PAnsiChar; n: integer; DestroyPtr: Pointer): integer; cdecl;
SQLite3_Bind_Int: function(hstatement: pointer; iCol: integer; n: integer): integer; cdecl;
SQLite3_Bind_Double: function(hstatement: pointer; iCol: integer; d: double): integer; cdecl;
SQLite3_Bind_Text: function(hstatement: pointer; iCol: integer; buf: pointer; n: integer; DestroyPtr: Pointer): integer; cdecl;
SQLite3_Bind_Value: function(hstatement: pointer; iCol: integer; buf: pointer): integer; cdecl;
SQLite3_Bind_Text16: function(hstatement: pointer; iCol: integer; buf: pointer; n: integer; DestroyPtr: Pointer): integer; cdecl;
SQLite3_Bind_Parameter_Count: function(hstatement: pointer): integer; cdecl;
SQLite3_Bind_Parameter_Name : function(hstatement : pointer; iCol : integer) : PAnsiChar; cdecl;
SQLite3_create_collation16: function(db: Pointer; zName : pWideChar; pref16 : integer; data : pointer; cmp : TCompareFunc): integer; cdecl;//\\\
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DBConnect(Connected: boolean);
function SQLite3_PrepareResult(DB: Pointer; TheStatement: string; Sender: TObject) : pointer;
function SQLite3_GetNextResult(DB: Pointer; TheStatement: pointer; Sender: TObject) : pointer;
procedure SQLite3_CloseResult(TheStatement : pointer);
procedure SetTimeOut(const Value: integer); // sean
public
DLLHandle: THandle;
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function LoadLibs: boolean;
procedure FSetDatabase(Database: string);
function RowsAffected: integer;
function TableExists(const ATableName: string): Boolean;
procedure ExecStartTransaction(TransType: string);
procedure StartTransaction;
procedure StartDeferredTransaction;
procedure StartImmediateTransaction;
procedure StartExclusiveTransaction;
procedure Open;
procedure Close;
procedure Commit;
procedure RollBack;
procedure Vacuum;
procedure ShowDatabases(List: TStrings);
procedure GetTableNames(List: TStrings; SystemTables: boolean = false; TempTables: boolean = false);
procedure GetTableInfo(TableName: string; List: TList);
procedure GetIndexNames(List: TStrings; SystemTables: boolean = false);
procedure GetIndexFieldNames(IndexName: string; List: TStrings);
procedure GetFieldNames(TableName: string; List: TStrings);
procedure GetPrimaryKeys(TableName: string; List: TStrings);
procedure GetTableIndexNames(TableName: string; List: TStrings);
procedure ExecPragma;
// function SQLite_XExec(db: Pointer; SQLStatement: PAnsiChar;
// CallbackPtr: Pointer; Sender: TObject; var ErrMsg: PAnsiChar): integer; cdecl;
function SQLite3_Execute(db: Pointer; TheStatement: string; Params: TParams; Sender: TObject): integer;
function SQLite3_ExecSQL(TheStatement: string; Fields: TFields=nil): integer;
function SQLite3_ExecSQL_Params(TheStatement: string; Params: TParams=nil): integer;
procedure ShowError;
function GetUserVersion(database : string=''): integer;
procedure SetUserVersion(Version : integer; Database : string='');
function GetSchemaVersion(database : string=''): integer;
procedure SetSchemaVersion(Version : integer; Database : string='');
function InTransaction : boolean;
published
{ Published declarations }
property TimeOut: integer read FTimeOut write SetTimeOut;
property CharacterEncoding: string read FCharEnc write FCharEnc;
property TransactionType: string read FTransactionType write FTransactionType;
property Database: string read FDatabase write FSetDatabase;
property ASQLitePragma: TASQLite3Pragma read FASQLitePragma write FASQLitePragma;
property ASQLiteLog: TASQLite3Log read FASQLiteLog write FASQLiteLog;
property DefaultExt: string read FGetDefaultExt write FDefaultExt;
property DefaultDir: string read FDefaultDir write FDefaultDir;
property Version: string read FVersion write FVersion;
property DriverDLL: string read FGetDriverDLL write FDriverDLL;
property Connected: boolean read FConnected write DBConnect;
property MustExist: boolean read FMustExist write FMustExist;
property ASQLiteInlineSQL: TASQLite3InlineSQL read FInlineSQL write FInlineSQL;
property ExecuteInlineSQL: boolean read FExecuteInlineSQL write FExecuteInlineSQL;
property AfterConnect: TASQLite3NotifyEvent read FAfterConnect write FAfterConnect;
property BeforeConnect: TASQLite3NotifyEvent read FBeforeConnect write FBeforeConnect;
property AfterDisconnect: TASQLite3NotifyEvent read FAfterDisconnect write FAfterDisconnect;
property BeforeDisconnect: TASQLite3NotifyEvent read FBeforeDisconnect write FBeforeDisconnect;
property OnBusy : TASQLite3NotifyEvent read FOnBusy write FOnBusy;
property Encoding: TASQLiteCharset read fEncoding;
end;
AsgError = class(Exception);
{ TRecInfo }
{ This structure is used to access additional information stored in
each record buffer which follows the actual record data.
Buffer: PAnsiChar;
||
\/
-------------------------------------------------
|NULL| Record Data | Bookmark | Bookmark Flag |
-------------------------------------------------
^-- PRecInfo = Buffer + FRecInfoOfs
Keep in mind that this is just an example of how the record buffer
can be used to store additional information besides the actual record
data. There is no requirement that TDataSet implementations do it this
way.
For the purposes of this demo, the bookmark format used is just an integer
value. For an actual implementation the bookmark would most likely be
a native bookmark type (as with BDE), or a fabricated bookmark for
data providers which do not natively support bookmarks (this might be
a variant array of key values for instance).
The BookmarkFlag is used to determine if the record buffer contains a
valid bookmark and has special values for when the dataset is positioned
on the "cracks" at BOF and EOF. }
PBookmarkData = ^TBookmarkData;
TBookmarkData = integer;
PRecInfo = ^TRecInfo;
TRecInfo = packed record
Bookmark : TBookmarkData;
BookmarkFlag : TBookmarkFlag;
// Nulls :
end;
//============================================================================== TFResult
// The TFResult class is used to maintain the resultlist in memory. This
// will only be the case for 'normal' data. Blobs and Clobs will be treated
// differently, but they are not supported yet.
//==============================================================================
TASQLite3BaseQuery = class;
TFResult = class
protected
Data: TList;
BookMark: TList;
RowId: TList;
FLastBookmark: integer;
FBufSize: integer;
FDataSet: TASQLite3BaseQuery;
public
constructor Create(TheDataSet: TASQLite3BaseQuery);
destructor Destroy; override;
procedure FreeBlobs;
procedure SetBufSize(TheSize: integer);
procedure Add(TheBuffer: PByte; TheRowId: integer);
procedure Insert(Index: integer; TheBuffer: Pointer; TheRowId: integer);
procedure Delete(Index: integer);
function GetData(Index: integer): Pointer;
function Count: integer;
function IndexOf(TheBookMark: pointer): integer;
function GetBookmark(Index: integer): integer;
function GetRowId(Index: integer): integer;
end;
//============================================================================== TASQLite3UpdateSQL
TASQLite3UpdateSQL = class(TComponent)
private
FInsertSQL: TStrings;
FUpdateSQL: TStrings;
FDeleteSQL: TStrings;
procedure SetInsertSQL(const Value: TStrings);
procedure SetUpdateSQL(const Value: TStrings);
procedure SetDeleteSQL(const Value: TStrings);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property InsertSQL: TStrings read FInsertSQL write SetInsertSQL;
property UpdateSQL: TStrings read FUpdateSQL write SetUpdateSQL;
property DeleteSQL: TStrings read FDeleteSQL write SetDeleteSQL;
end;
//============================================================================== TASQLite3Output
TASQLite3Output = class(TComponent)
private
FActive: boolean;
FOutputType: string;
FTableClass: string;
FHeaderClass: string;
FCellClass: string;
FOutput: TStrings;
FSeparator: string;
FDataSource: TDataSource;
procedure SetOutput(const Value: TStrings);
procedure SetFActive(Active: boolean);
function GetOutput: TStrings;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute(MyDataSet: TDataSet);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
published
property Active: boolean read FActive write SetFActive;
property DataSource: TDataSource read FDataSource write FDataSource;
property OutputType: string read FOutputType write FOutputType;
property TableClass: string read FTableClass write FTableClass;
property HeaderClass: string read FHeaderClass write FHeaderClass;
property CellClass: string read FCellClass write FCellClass;
property Output: TStrings read GetOutput write SetOutput;
property FieldSeparator: string read FSeparator write FSeparator;
end;
//============================================================================== TASQLite3BaseQuery
TASQLite3BaseQuery = class(TDataSet)
private
// FOrderBy : string;
FParams: TParams;
FTypeLess: boolean;
FNoResults: boolean; // suppresses the creation of a result list
FAutoCommit: boolean;
FTransactionType: string;
FTableDateFormat: string;
FSQLiteDateFormat: boolean;
FResult: TFResult;
FSQL: TStrings;
FSQLCursor: boolean;
FPrepared: string;
FRecBufSize: integer;
FRecInfoOfs: integer;
FCurRec: integer;
FMasterFields: string;
FMasterSource: TDataSource;
FSaveChanges: boolean;
MaxStrLen: integer;
FConnection: TASQLite3DB;
FReadOnly: boolean;
FMaxResults: integer;
FStartResult: integer;
FUniDir : boolean;
FStatement : pointer;
CurrentRowId: integer;
SQLStr: string;
ResultStr: PByte;
RowId : integer;
RowIdCol : integer;
DetailList: TList;
procedure SetSQL(const Value: TStrings);
// function UnpackBuffer(Buffer: PAnsiChar; FieldType: TFieldType): TConvertBuffer;
procedure UnpackBuffer(Buffer: PChar; FieldType: TFieldType; var RetBuffer : TConvertBuffer);
procedure SetDataSource(Value: TDataSource);
procedure IntGotoBookmark(Bookmark: PBookmarkData);
function IntFindRecordID(Buf: TBookmarkData): Integer;
function RecordBuffer_To_NativeRecord(aBuf: Dataset_TRecordBuffer):Dataset_PByte;inline;
function RecBuf_To_NativeRecord(aBuf: Dataset_TRecBuf):Dataset_PByte;inline;
function Record_To_RecordBuffer(aRec: Pointer): Dataset_TRecordBuffer;inline;
function Bookmark_To_BookMarkData(aBookmark: Dataset_TBookmark): PBookmarkData;inline;
function ValueBuffer_To_Pointer(aBuffer: Dataset_TValueBuffer): Pointer;inline;
protected
MDFilter : string ; // master-detail filter 2008 Aducom
function BuildFilter(const AIsNull: Boolean) : string;
function SetQueryParams(InStr: string): string; //***
procedure SetParamsList(Value: TParams);
function GetParamsCount: word;
procedure RegisterDetailDataset(DetailDataSet: TASQLite3BaseQuery);
procedure LoadQueryData;
function GetActiveBuffer(var Buffer: Dataset_PByte): boolean;
function GetDataSource: TDataSource; override;
procedure NotifySQLiteMasterChanged;
// function GetFieldValue(const AField: TField; const Blobs: TList = nil): string; // added by Donnie
{ Overriden abstract methods (required) }
function AllocRecordBuffer: Dataset_TRecordBuffer; override;
procedure FreeRecordBuffer(var Buffer: Dataset_TRecordBuffer); override;
procedure GetBookmarkData(Buffer: Dataset_TRecordBuffer; Data: Dataset_TBookmark); override;
function GetBookmarkFlag(Buffer: Dataset_TRecordBuffer): TBookmarkFlag; override;
function GetRecord(Buffer: Dataset_TRecordBuffer; GetMode: TGetMode;
DoCheck: boolean): TGetResult; override;
function GetRecordSize: word; override;
procedure InternalAddRecord(Buffer: {$IFDEF ASQLite_XE3PLUS}Dataset_TRecordBuffer{$ELSE}Pointer{$ENDIF}; Append: boolean); override;
procedure DataEvent(Event: TDataEvent; Info: NativeInt); override;
procedure InternalClose; override;
procedure InternalDelete; override;
procedure InternalFirst; override;
procedure InternalGotoBookmark(Bookmark: Dataset_TBookmark); override;
procedure InternalHandleException; override;
procedure InternalInitFieldDefs; override;
procedure InternalInitRecord(Buffer: Dataset_TRecordBuffer); override;
procedure InternalRefresh; override;
procedure InternalLast; override;
procedure InternalOpen; override;
procedure InternalPost; override;
procedure InternalSetToRecord(Buffer: Dataset_TRecordBuffer); override;
procedure OpenCursor(InfoQuery: Boolean); override; // GPA
function IsCursorOpen: boolean; override;
procedure SetBookmarkFlag(Buffer: Dataset_TRecordBuffer; Value: TBookmarkFlag); override;
procedure SetBookmarkData(Buffer: Dataset_TRecordBuffer; Data: Dataset_TBookmark); override;
procedure SetFieldData(Field: TField; Buffer: Dataset_TValueBuffer); override;
function GetFieldSize(FieldNo: integer): integer; overload;
function GetFieldSize(Field: TField): integer; overload;
function GetNativeFieldSize(FieldNo: integer): integer;
function GetFieldOffset(FieldNo: integer): integer;
function GetCalcFieldOffset(Field: TField): integer;
function isNullSrc(SrcBuffer: pAnsiChar; fieldNo : integer) : boolean; overload;
function isNullSrc(SrcBuffer: Dataset_PByte; fieldNo : integer) : boolean; overload;
procedure setNullSrc(SrcBuffer: Dataset_PByte; fieldNo : integer; aNull : boolean);
function GetMasterFields: string;
procedure SetMasterFields(const Value: string);
{ Additional overrides (optional) }
function GetRecordCount: integer; override;
function GetRecNo: integer; override;
procedure SetRecNo(Value: integer); override;
property BaseSQL: TStrings read FSQL write SetSQL;
procedure SetSQLiteDateFormat(const Value: boolean);
procedure SetFilterText(const Value: string); override;
{$IFNDEF ASQLite_XE3PLUS}
procedure DataConvert(Field: TField; Source: Dataset_TValueBuffer; Dest: Dataset_TValueBuffer; ToNative: Boolean); override;//\\\
{$ENDIF}
function CalcFieldInList(const List: string): Boolean; // John Lito
{$IFDEF IPROVIDER}
{***** IProviderSupport - Begin *****}
//-----| These are not necessary until the moment!
// procedure PSGetAttributes(List: TList); virtual;
// function PSGetDefaultOrder: TIndexDef; virtual;
// function PSGetIndexDefs(IndexTypes: TIndexOptions): TIndexDefs; virtual;
//-----| These are necessary to support IProvider
procedure PSEndTransaction(Commit: Boolean); override;
procedure PSExecute; override;
function PSExecuteStatement(const ASQL: string; AParams: TParams; ResultSet: Pointer = nil): Integer; override;
function PSGetParams: TParams; override;
function PSGetTableName: string; override;
function PSGetUpdateException(E: Exception; Prev: EUpdateError): EUpdateError; override;
function PSInTransaction: Boolean; override;
function PSIsSQLBased: Boolean; override;
function PSIsSQLSupported: Boolean; override;
procedure PSReset; override;
procedure PSSetCommandText(const CommandText: string); override;
procedure PSSetParams(AParams: TParams); override;
procedure PSStartTransaction; override;
function PSUpdateRecord(UpdateKind: TUpdateKind; Delta: TDataSet): Boolean; override;
function PSGetQuoteChar: string; override;
function PSGetKeyFields: string; override;
{***** IProviderSupport - End *****}
{$ENDIF}
public
FOrderBy : string;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ExecSQL;
procedure StartTransaction;
procedure StartDeferredTransaction;
procedure StartImmediateTransaction;
procedure StartExclusiveTransaction;
procedure Commit;
procedure RollBack;
procedure SetFiltered(Value: Boolean); override;
procedure SQLiteMasterChanged(const AIsNull: Boolean); virtual;
function GetFieldData(Field: TField;{$IFDEF ASQLite_XE4PLUS}var{$ENDIF} Buffer: Dataset_TValueBuffer): boolean; override;
function GetFieldData(FieldNo: integer;{$IFDEF ASQLite_XE4PLUS}var{$ENDIF} Buffer: Dataset_TValueBuffer): boolean; override; // 20040225
function GetLastInsertRow: integer;
function CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer; override; //MS
function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override;
function Locate(const KeyFields: string; const KeyValues: variant; Options: TLocateOptions): boolean; override;
function BookmarkValid(Bookmark: TBookmark): boolean; override;
// function LocateNearest(const KeyFields: String; const KeyValues: Variant; Options: TLocateOptions): Boolean;
property Params: TParams read FParams write SetParamsList stored false;
function Lookup(const KeyFields: string; const KeyValues: Variant; // John Lito
const ResultFields: string): Variant; override; // John Lito
function GetFieldBufferIndex(Field: TField): integer; // Sean
published
property AutoCommit: boolean read FAutoCommit write FAutoCommit default true;
property TransactionType: string read FTransactionType write FTransactionType;
property SQLiteDateFormat: boolean read FSQLiteDateFormat write SetSQLiteDateFormat;
property TableDateFormat: string read FTableDateFormat write FTableDateFormat;
property Connection: TASQLite3DB read FConnection write FConnection;
property MaxResults: integer read FMaxResults write FMaxResults;
property StartResult: integer read FStartResult write FStartResult;
property TypeLess: boolean read FTypeLess write FTypeLess;
property MasterFields: string read GetMasterFields write SetMasterFields;
property MasterSource: TDataSource read GetDataSource write SetDataSource;
property SQLCursor: boolean read FSQLCursor write FSQLCursor;
property ReadOnly: boolean read FreadOnly write FReadOnly;
property UniDirectional : boolean read FUniDir write FUniDir;
property AutoCalcFields;
property Filter;
property Filtered;
property Active;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property BeforeRefresh;
property AfterRefresh;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
end;
//============================================================================== TASQLite3Query
TASQLite3Query = class(TASQLite3BaseQuery)
private
FUpdateSQL: TASQLite3UpdateSQL;
FRawSQL: boolean;
procedure SetSQL(const Value: TStrings);
function GetSQL: TStrings;
procedure QueryChanged(Sender: TObject);
protected
procedure InternalOpen; override;
procedure InternalPost; override;
procedure InternalDelete; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure InternalClose; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// property Params: TParams Read FParams Write SetParamsList Stored false;
procedure SQLiteMasterChanged(const AIsNull: Boolean); override;
published
property RawSQL: boolean read FRawSQL write FRawSQL;
property SQL: TStrings read GetSQL write SetSQL;
property UpdateSQL: TASQLite3UpdateSQL read FUpdateSQL write FUpdateSQL;
end;
//============================================================================== TASQLite3Table
TASQLite3Table = class(TASQLite3BaseQuery)
private
FTableName: string;
// FOrderBy : string;
FPrimaryAutoInc: boolean;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure InternalOpen; override;
procedure InternalPost; override;
procedure InternalAddRecord(Buffer: {$IFDEF ASQLite_XE3PLUS}Dataset_TRecordBuffer{$ELSE}Pointer{$ENDIF}; Append: boolean); override;
procedure InternalDelete; override;
procedure SetFTableName(TableName : string);
procedure SetFOrderBy(OrderBy : string);
public
procedure SQLiteMasterChanged(const AIsNull: Boolean); override;
published
property TableName: string read FTableName write SetFTableName;
property PrimaryAutoInc: boolean read FPrimaryAutoInc write FPrimaryAutoInc;
property OrderBy : string read FOrderBy write SetFOrderBy;
end;
//============================================================================== TASQLite3BlobStream
TASQLite3BlobStream = class(TMemoryStream)
private
FField: TBlobField;
FDataSet: TASQLite3BaseQuery;
FMode: TBlobStreamMode;
FModified: Boolean;
FOpened: Boolean;
procedure LoadBlobData;
procedure SaveBlobData;
public
constructor Create(Field: TBlobField; Mode: TBlobStreamMode);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
{$IFDEF ASQLite_XE3PLUS}
function Read(Buffer: TBytes; Offset, Count: Longint): Longint; override;
function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; override;
{$ENDIF}
end;
implementation
uses
Math, StrUtils, AnsiStrings;
function systemNoCaseCompare(db : TASQLite3DB; s1Len : integer; s1 : PWideChar; s2Len : integer; s2 : PWideChar) : integer; cdecl;
begin
result := comparetext(s1, s2);
end;
function systemCompare(db : TASQLite3DB; s1Len : integer; s1 : PWideChar; s2Len : integer; s2 : PWideChar) : integer; cdecl;
begin
result := CompareStr(s1, s2);
end;
{$IFDEF DEBUG_ENABLED}
var
DebugSpaces : Integer = 0;
{$ENDIF}
procedure Debug(const S: string);
begin
{$IFDEF DEBUG_ENABLED}
OutputDebugString(PChar(StringOfChar(' ', DebugSpaces) + S));
{$ENDIF}
end;
procedure DebugEnter(const S: string);
begin
{$IFDEF DEBUG_ENABLED}
OutputDebugString(PChar(StringOfChar(' ', DebugSpaces) + 'Enter ' + S));
inc(DebugSpaces);
{$ENDIF}
end;
procedure DebugLeave(const S: string);
begin
{$IFDEF DEBUG_ENABLED}
dec(DebugSpaces);
OutputDebugString(PChar(StringOfChar(' ', DebugSpaces) + 'Leave ' + S));
{$ENDIF}
end;
//==============================================================================
// SyntaxCheck. This routine is used to check if words match the sql syntax
// It is called where sql statements are parsed and generated
//==============================================================================
function SyntaxCheck(LWord, RWord: string): boolean;
begin
DebugEnter('SyntaxCheck');
try
if comparetext(LWord, RWord) <> 0 then begin
SyntaxCheck := false;
raise AsgError.Create('SQL macro syntax error on sql, expected ' + RWord)
end else
SyntaxCheck := true;
finally
DebugLeave('SyntaxCheck');
end;
end;
//==============================================================================
// Parse the SQL fielddescription and return the Delphi Field types, length etc.
//==============================================================================
procedure GetFieldInfo(FieldInfo: string; var FieldType: TFieldType;
var FieldLen, FieldDec: integer; Encoding:TASQLiteCharset);
var
p1, p2, pn : integer;
vt : string;
begin
DebugEnter('GetFieldInfo');
FieldType := ftString; // just a default;
FieldLen := 255;
FieldDec := 0;
p1 := pos('(', FieldInfo);
if p1 <> 0 then
begin
p2 := pos(')', FieldInfo);
if p2 <> 0 then
begin
vt := LowerCase(Copy(FieldInfo, 1, p1 - 1));
if (vt = 'varchar') or (vt = 'varying character') or (vt = 'character') or (vt = 'char') or (vt = 'varchar2') then begin
FieldType := ftWideString;
FieldLen := StrToInt(Copy(FieldInfo, p1 + 1, p2 - p1 - 1)) *2;
end
else if (vt = 'nvarchar') or (vt = 'native character') or (vt = 'nchar') or (vt = 'nvarchar2') then begin
FieldType := ftWideString;
FieldLen := StrToInt(Copy(FieldInfo, p1 + 1, p2 - p1 - 1));
FieldLen := FieldLen * 2;
end
else if (vt = 'numeric') or
(vt = 'float') or
(vt = 'real') or
(vt = 'double') or
(vt = 'double precision') or
(vt = 'decimal') then begin
vt := Copy(FieldInfo, p1 + 1, p2 - p1 - 1);
pn := pos('.', vt); if pn = 0 then pn := pos(',', vt);
FieldType := ftFloat;
if pn = 0 then begin
FieldLen := StrToInt(vt);
FieldDec := 0;
end else begin
FieldLen := StrToInt(Copy(vt, 1, pn - 1));
FieldDec := StrToInt(Copy(vt, pn + 1, 2));
end;
end;
end
else
FieldLen := 256;
end
else
begin
vt := LowerCase(FieldInfo);
if vt = 'date' then
begin
FieldType := ftDate;
FieldLen := 10;
end
else if vt = 'datetime' then
begin
FieldType := ftDateTime; // fpierce original ftDate
FieldLen := 24; // aducom
end
else if vt = 'time' then
begin
FieldType := ftTime;
FieldLen := 12;
end
else if vt = 'timestamp' then
begin
FieldType := ftTimeStamp;
FieldLen := 12;
end
else if (vt = 'integer') or
(vt = 'int') or
(vt = 'tinyint') or
(vt = 'smallint') or
(vt = 'mediumint') or
(vt = 'int8') or
(vt = 'int2') then
begin
FieldType := ftInteger;
FieldLen := 12;
end
else if (vt = 'float') or (vt = 'real') or (vt = 'double') or (vt = 'double precision') then