forked from yavfast/dbg-spider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuSQLiteDB.pas
1728 lines (1446 loc) · 40.8 KB
/
uSQLiteDB.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
unit uSQLiteDB;
interface
uses
System.Contnrs, System.SysUtils, System.Classes, System.Types, System.Sqlite,
uRWLock;
type
HSQLCONTEXT = Pointer;
HSQLDB = Pointer;
HSQLQUERY = Pointer;
HSQLVALUE = Pointer;
TSQLBase = class;
TSQLColumnType = (sctUnknown = 0, sctInteger = 1, sctFloat = 2, sctText = 3, sctBlob = 4, sctNull = 5);
{ TAIMPSqlColumn }
TSQLColumn = class(TObject)
private
FDataType: TSQLColumnType;
FName: String;
public
property DataType: TSQLColumnType read FDataType;
property Name: String read FName;
end;
{ TAIMPSqlTable }
TSQLTableClass = class of TSQLTable;
TSQLTable = class(TObject)
private
FDataBase: TSQLBase;
FQuery: HSQLQUERY;
FColumns: TObjectList;
FDataTypesFetched: Boolean;
function FetchDataTypes: Boolean;
function GetColumn(const Index: Integer): TSQLColumn;
function GetColumnCount: Integer;
function GetFieldIndex(const Name: String): Integer;
function GetValue(const ColumnName: String): Variant;
function GetActive: Boolean; inline;
procedure SetActive(const Value: Boolean);
protected
procedure CheckActive;
procedure CheckDBActive;
procedure UpdateQuery; virtual;
procedure ClearQuery; virtual;
public
constructor Create(ADataBase: TSQLBase; AQuery: HSQLQUERY);
destructor Destroy; override;
function NextRecord: Boolean;
// I/O
function ReadBlob(const AIndex: Integer; AData: TMemoryStream): Integer; overload;
function ReadBlob(const AName: String; AData: TMemoryStream): Integer; overload;
function ReadDouble(const AIndex: Integer): Double; overload;
function ReadDouble(const AName: String): Double; overload;
function ReadInt(const AIndex: Integer): Integer; overload;
function ReadInt(const AName: String): Integer; overload;
function ReadStr(const AIndex: Integer): String; overload;
function ReadStr(const AName: String): String; overload;
function ReadInt64(const AIndex: Integer): Int64; overload;
function ReadInt64(const AName: String): Int64; overload;
function ReadDateTime(const AIndex: Integer): TDateTime; overload;
function ReadDateTime(const AName: String): TDateTime; overload;
// Properties
property Column[const Index: Integer]: TSQLColumn read GetColumn; default;
property ColumnCount: Integer read GetColumnCount;
property Value[const ColumnName: String]: Variant read GetValue;
property DataBase: TSQLBase read FDataBase;
function FieldExists(const Name: String): Boolean;
property Active: Boolean read GetActive write SetActive;
end;
TSQLView = class(TSQLTable)
private
FParamCount: Integer;
FQueryStr: String;
FLock: TRWLock;
procedure InitParams;
protected
procedure UpdateQuery; override;
procedure Reset;
procedure SetParamAsText(const ParamIdx: Integer; const Str: String);
property Lock: TRWLock read FLock;
public
constructor Create(ADataBase: TSQLBase; AQuery: HSQLQUERY; const AQueryStr: String = ''); overload;
constructor Create(ADataBase: TSQLBase; const AQueryStr: String); overload;
destructor Destroy; override;
procedure SetParam(const ParamName: String; const Value: Variant); overload;
procedure SetParam(const ParamIdx: Integer; const Value: Variant); overload;
procedure BeginExecute;
procedure EndExecute;
function Execute: Boolean;
end;
TSQLConnectMgr = class;
TOnErrorEvent = procedure(const ErrorCode: Integer; const ErrorText, Query: String) of object;
// PRAGMA journal_mode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF
TSQLJournalModeType = (ttDefault = 0, ttDelete, ttTruncate, ttPersist, ttMemory, ttWAL, ttOff);
// PRAGMA synchronous = 0 | OFF | 1 | NORMAL | 2 | FULL;
TSQLSynchronousType = (stDefault = 0, stOff, stNormal, stFull);
TSQLBeginTransactionType = (btGlobal = 0, btDeferred, btImmediate, btExclusive);
TSQLCodes = set of Byte;
{ TAIMPSqlBase }
TSQLBase = class(TObject)
private
FDB: HSQLDB;
FConnectMgr: TSQLConnectMgr;
FLinkedTables: TObjectList;
FLock: TRWLock;
FTransactions: Integer;
FOnError: TOnErrorEvent;
FJournalModeType: TSQLJournalModeType;
FSynchronousType: TSQLSynchronousType;
FGlobalTransactionLock: TRWLock;
FInGlobalTransaction: Boolean;
function CheckError(const ErrorCode: Integer; const ValidCodes: TSQLCodes = [SQLITE_OK]; const Query: String = ''): Boolean;
function PrepareQuery(const AQueryStr: String; out AQuery: HSQLQUERY): Boolean;
Function DoExecStep(AQueryHandle: HSQLQUERY): Integer;
function GetFileName: String;
procedure SetJournalModeType(const Value: TSQLJournalModeType);
procedure SetSynchronousType(const Value: TSQLSynchronousType);
procedure AddLinkedTable(Table: TSQLTable);
procedure RemoveLinkedTable(Table: TSQLTable);
function GetActive: Boolean; inline;
procedure SetActive(const Value: Boolean);
protected
procedure DataBaseInitTables; virtual;
procedure ErrorMsg(const AText: String; const ErrorCode: Integer; const Query: String = ''); overload; virtual;
procedure ErrorMsg(AText: PChar; const ErrorCode: Integer; const Query: String = ''); overload;
procedure Open;
procedure Close;
procedure CheckActive;
public
constructor Create(AConnectMgr: TSQLConnectMgr);
destructor Destroy; override;
function ClearAll: Boolean; virtual;
procedure Compress;
function PopulateTableNames(out AList: TStrings): Boolean;
procedure BeginTransaction(const ATransactionType: TSQLBeginTransactionType = btDeferred);
procedure EndTransaction;
procedure CancelTransaction;
function ExecSQL(const AQuery: String): Boolean; overload;
function ExecSQL(const AQuery: String; out ATable: TSQLTable): Boolean; overload;
function CreateView(const AQuery: String): TSQLView;
procedure UpdatePreparedStatements;
procedure ClosePreparedStatements;
function GetLastInsertRowID: Int64;
// Blobs: Use "?" symbol in Query for set data position
function ExecInsertBlob(const AQuery: String; AData: TMemoryStream): Boolean;
// Properties
property FileName: String read GetFileName;
//êîë-âî ìîäèôèöèðîâàííûõ ñòðîê
Function GetRowAffected : Integer;
//êîë-âî ñòîëáöîâ â òàáëèöå
Function GetColCount(Const ATableName: String): Integer;
//ïóñòàÿ òàáëèöà
Function IsEmpty(Const ATableName: String): Boolean;
Function DeleteTable(Const ATableName: String): Boolean;
Procedure Lock(const LockType: TRWNodeState = nsWriter);
Procedure UnLock;
Procedure GlobalLock; inline;
procedure GlobalUnLock; inline;
Function GetVersion: Integer;
property ConnectMgr: TSQLConnectMgr read FConnectMgr;
property OnError: TOnErrorEvent read FOnError write FOnError;
property JournalModeType: TSQLJournalModeType read FJournalModeType write SetJournalModeType;
property SynchronousType: TSQLSynchronousType read FSynchronousType write SetSynchronousType;
property Active: Boolean read GetActive write SetActive;
end;
TSQLConnectMgr = class(TObject)
private
FDBFileName: String;
FLock: TRWLock;
FDBConnections: TList;
FActive: Boolean;
procedure SetDBFileName(const Value: String);
procedure SetActive(const Value: Boolean);
public
constructor Create(const ADBFileName: String);
destructor Destroy; override;
function GetNewConnection: TSQLBase;
function GetDefaultConnection: TSQLBase;
procedure Remove(Connect: TSQLBase);
procedure Reset(const FreeConnections: Boolean = True);
property DBFileName: String read FDBFileName write SetDBFileName;
property Active: Boolean read FActive write SetActive;
end;
TDBException = class(Exception);
function DBConnectMgr(const DBName: String): TSQLConnectMgr;
function GetDBConnections: TStringList;
procedure DBResetAll(const FreeConnections: Boolean = True);
function sqlite_DateTimeToStr(const DateTime: TDateTime): string;
function sqlite_TryStrToDateTime(const Str: String; var Res: TDateTime): Boolean;
function sqlite_StrToDateTime(const Str: String; const DefValue: TDateTime = 0): TDateTime;
function sqlite_Str(const Str: String; var Count: Integer): PWideChar;
implementation
uses
System.Variants, System.StrUtils, System.WideStrUtils;
type
TSQLCompare = function (P1: PChar; P1Size: Integer; P2: PChar; P2Size: Integer): Integer; cdecl;
TSQLFunction = procedure (Context: HSQLCONTEXT; ArgCount: Integer; ArgVars: PPointer); cdecl;
TSQLFunctionEnd = procedure (Context: HSQLCONTEXT); cdecl;
TSQLiteBusyHandlerCallback = function(UserData: Pointer; P2: integer): integer; cdecl;
TDBConnectMgrList = TStringList;
var
_DBConnectMgrList: TDBConnectMgrList = nil;
_DBConnectMgrLock: TRWLock = nil;
function DBConnectMgr(const DBName: String): TSQLConnectMgr;
var
Idx: Integer;
DBAlias: string;
begin
Result := Nil;
if _DBConnectMgrLock = Nil then Exit;
DBAlias := AnsiLowerCase(ExtractFileName(DBName));
_DBConnectMgrLock.Lock(nsReader);
try
Idx := -1;
if _DBConnectMgrList <> nil then
Idx := _DBConnectMgrList.IndexOf(DBAlias);
if Idx >= 0 then
Result := TSQLConnectMgr(_DBConnectMgrList.Objects[Idx])
else
begin
_DBConnectMgrLock.Lock(nsWriter);
try
if _DBConnectMgrList.IndexOf(DBAlias) < 0 then
begin
Result := TSQLConnectMgr.Create(DBName);
_DBConnectMgrList.AddObject(DBAlias, Result);
Result.Active := True;
end
else
Result := DBConnectMgr(DBName);
finally
_DBConnectMgrLock.UnLock;
end;
end;
// Íà ñëó÷àé, åñëè ñìåíèëè ïóòü ê áàçå
if not AnsiSameText(Result.DBFileName, DBName) then
Result.DBFileName := DBName;
finally
_DBConnectMgrLock.UnLock;
end;
end;
function GetDBConnections: TStringList;
begin
Result := TStringList.Create;
_DBConnectMgrLock.Lock(nsReader);
try
Result.Assign(_DBConnectMgrList);
finally
_DBConnectMgrLock.UnLock;
end;
end;
procedure DBResetAll(const FreeConnections: Boolean = True);
var
Mgr: TSQLConnectMgr;
I: Integer;
begin
_DBConnectMgrLock.Lock(nsWriter);
try
if Assigned(_DBConnectMgrList) then
begin
for I := _DBConnectMgrList.Count - 1 downto 0 do
begin
Mgr := TSQLConnectMgr(_DBConnectMgrList.Objects[I]);
Mgr.Active := False;
if FreeConnections then
begin
_DBConnectMgrList.Objects[I] := nil;
if Assigned(Mgr) then
FreeAndNil(Mgr);
end;
end;
if FreeConnections then
_DBConnectMgrList.Clear;
end;
finally
_DBConnectMgrLock.UnLock;
end;
end;
const
SQLITE_DATE_FMT = 'yyyy-mm-dd';
SQLITE_TIME_FMT = 'hh:nn:ss';
SQLITE_DATETIME_FMT = SQLITE_DATE_FMT + ' ' + SQLITE_TIME_FMT;
function sqlite_DateTimeToStr(const DateTime: TDateTime): string;
begin
if DateTime <> 0 then
Result := FormatDateTime(SQLITE_DATETIME_FMT, DateTime)
else
Result := '';
end;
var
_sqlite_DateTimeFormat: TFormatSettings;
function sqlite_TryStrToDateTime(const Str: String; var Res: TDateTime): Boolean;
begin
Result := TryStrToDateTime(Str, Res, _sqlite_DateTimeFormat);
end;
function sqlite_StrToDateTime(const Str: String; const DefValue: TDateTime = 0): TDateTime;
begin
if not sqlite_TryStrToDateTime(Str, Result) then
Result := DefValue;
end;
function sqlite_Str(const Str: String; var Count: Integer): PWideChar;
var
StrBuf: RawByteString;
begin
StrBuf := UTF8Encode(Str);
Count := Length(StrBuf);
if Count > 0 then
Result := PWideChar(Pointer(@StrBuf[1]))
else
Result := Nil;
end;
function sqlite_StrToString(Str: PChar; Count: Integer): String;
var
Buf: RawByteString;
begin
Result := '';
if Count > 0 then
begin
SetLength(Buf, Count);
Move(Str^, PAnsiChar(Buf)^, Count);
Result := UTF8ToString(Buf);
end;
end;
function UnicodeCompare(UserData: Pointer; P1Size: Integer; P1: PChar; P2Size: Integer; P2: PChar): Integer; cdecl;
var
S1, S2: String;
begin
S1 := sqlite_StrToString(P1, P1Size);
S2 := sqlite_StrToString(P2, P2Size);
Result := AnsiCompareText(S1, S2);
end;
procedure SQLiteUpper(Context: HSQLCONTEXT; ArgCount: Integer; ArgVars: PPointerArray); cdecl;
var
Arg: Pointer;
Cnt: Integer;
BufIn: Pointer;
StrRes: String;
BufOut: PWideChar;
begin
Arg := ArgVars^[0];
if (sqlite3_value_type(Arg) <> SQLITE_NULL) then
begin
Cnt := sqlite3_value_bytes16(Arg);
if Cnt > 0 then
begin
BufIn := sqlite3_value_text16(Arg);
StrRes := sqlite_StrToString(BufIn, Cnt);
StrRes := AnsiUpperCase(StrRes);
BufOut := sqlite_Str(StrRes, Cnt); // TODO: MemLeak?
sqlite3_result_text16(Context, BufOut, Cnt, nil);
end
else
sqlite3_result_text16(Context, nil, 0, nil);
end
else
sqlite3_result_null(Context);
end;
{ TAIMPSqlTable }
procedure TSQLTable.CheckActive;
begin
if not Active then
raise TDBException.Create('Table is not active');
end;
procedure TSQLTable.CheckDBActive;
begin
if not FDataBase.Active then
raise TDBException.Create('Linked DB is not active');
end;
procedure TSQLTable.ClearQuery;
begin
if Active then
try
CheckDBActive;
FreeAndNil(FColumns);
FDataBase.GlobalLock;
try
FDataBase.CheckError(sqlite3_finalize(FQuery), [SQLITE_OK, SQLITE_ABORT]);
finally
FDataBase.GlobalUnLock;
end;
finally
FQuery := nil;
end;
end;
constructor TSQLTable.Create(ADataBase: TSQLBase; AQuery: HSQLQUERY);
begin
inherited Create;
FColumns := TObjectList.Create;
FDataBase := ADataBase;
FQuery := AQuery;
FDataBase.AddLinkedTable(Self);
end;
destructor TSQLTable.Destroy;
begin
FDataBase.RemoveLinkedTable(Self);
ClearQuery;
inherited Destroy;
end;
function TSQLTable.FetchDataTypes: Boolean;
var
AColumn : TSQLColumn;
ADataType: Integer;
I, ACount : Integer;
begin
FColumns.Clear;
CheckActive;
CheckDBActive;
FDataBase.GlobalLock;
try
ACount := sqlite3_column_count(FQuery);
FColumns.Capacity := ACount;
for I := 0 to ACount - 1 do
begin
AColumn := TSQLColumn.Create;
AColumn.FName := sqlite3_column_name16(FQuery, I);
ADataType := sqlite3_column_type(FQuery, I);
AColumn.FDataType := TSQLColumnType(ADataType);
FColumns.Add(AColumn);
end;
finally
FDataBase.GlobalUnLock;
end;
Result := True;
end;
function TSQLTable.FieldExists(const Name: String): Boolean;
begin
Result := GetFieldIndex(Name) >= 0;
end;
function TSQLTable.NextRecord: Boolean;
var
ResCode: Integer;
begin
CheckActive;
CheckDBActive;
FDataBase.GlobalLock;
try
ResCode := FDataBase.DoExecStep(FQuery);
Result := FDataBase.CheckError(ResCode, [SQLITE_ROW, SQLITE_DONE]) and (ResCode = SQLITE_ROW);
finally
FDataBase.GlobalUnLock;
end;
end;
function TSQLTable.ReadBlob(const AIndex: Integer; AData: TMemoryStream): Integer;
var
ABlobBuffer: PByte;
begin
CheckActive;
CheckDBActive;
Result := sqlite3_column_bytes16(FQuery, AIndex);
if Assigned(AData) then
begin
ABlobBuffer := sqlite3_column_blob(FQuery, AIndex);
if Assigned(ABlobBuffer) then
begin
AData.Size := Result;
Move(ABlobBuffer^, AData.Memory^, AData.Size);
end
else
AData.Size := 0;
end;
end;
function TSQLTable.ReadBlob(const AName: String; AData: TMemoryStream): Integer;
begin
Result := ReadBlob(GetFieldIndex(AName), AData);
end;
function TSQLTable.ReadDouble(const AIndex: Integer): Double;
begin
CheckActive;
CheckDBActive;
Result := sqlite3_column_double(FQuery, AIndex);
end;
function TSQLTable.ReadDouble(const AName: String): Double;
begin
Result := ReadDouble(GetFieldIndex(AName));
end;
function TSQLTable.ReadInt(const AIndex: Integer): Integer;
begin
CheckActive;
CheckDBActive;
Result := sqlite3_column_int(FQuery, AIndex);
end;
function TSQLTable.ReadInt(const AName: String): Integer;
begin
Result := ReadInt(GetFieldIndex(AName));
end;
function TSQLTable.ReadInt64(const AIndex: Integer): Int64;
begin
CheckActive;
CheckDBActive;
Result := sqlite3_column_int64(FQuery, AIndex);
end;
function TSQLTable.ReadInt64(const AName: String): Int64;
begin
Result := ReadInt64(GetFieldIndex(AName));
end;
function TSQLTable.ReadDateTime(const AIndex: Integer): TDateTime;
begin
Result := sqlite_StrToDateTime(ReadStr(AIndex));
end;
function TSQLTable.ReadDateTime(const AName: String): TDateTime;
begin
Result := ReadDateTime(GetFieldIndex(AName));
end;
function TSQLTable.ReadStr(const AIndex: Integer): String;
var
textResult : PChar;
begin
Result := '';
CheckActive;
CheckDBActive;
textResult := sqlite3_column_text16(FQuery, AIndex);
if textResult <> nil then
Result := String(textResult);
end;
function TSQLTable.ReadStr(const AName: String): String;
begin
Result := ReadStr(GetFieldIndex(AName));
end;
procedure TSQLTable.SetActive(const Value: Boolean);
begin
if Active <> Value then
begin
if Value then
UpdateQuery
else
ClearQuery;
end;
end;
procedure TSQLTable.UpdateQuery;
begin
// TODO:
end;
function TSQLTable.GetActive: Boolean;
begin
Result := Assigned(FQuery);
end;
function TSQLTable.GetColumn(const Index: Integer): TSQLColumn;
begin
CheckActive;
if not FDataTypesFetched then
FDataTypesFetched := FetchDataTypes;
Result := TSQLColumn(FColumns[Index]);
end;
function TSQLTable.GetColumnCount: Integer;
begin
CheckActive;
if not FDataTypesFetched then
FDataTypesFetched := FetchDataTypes;
Result := FColumns.Count;
end;
function TSQLTable.GetFieldIndex(const Name: String): Integer;
var
I: Integer;
Column: TSQLColumn;
begin
CheckActive;
if not FDataTypesFetched then
FDataTypesFetched := FetchDataTypes;
Result := -1;
for I := 0 to FColumns.Count - 1 do
begin
Column := TSQLColumn(FColumns.List[I]);
if SameText(Column.Name, Name) then
begin
Result := I;
Break;
end;
end;
end;
function TSQLTable.GetValue(const ColumnName: String): Variant;
var
Idx: Integer;
Column: TSQLColumn;
begin
CheckActive;
Idx := GetFieldIndex(ColumnName);
if Idx >= 0 then
begin
Column := GetColumn(Idx);
case Column.DataType of
sctInteger:
Result := ReadInt64(Idx);
sctFloat:
Result := ReadDouble(Idx);
sctText:
Result := ReadStr(Idx);
sctBlob:
Result := ReadStr(Idx);
sctNull:
Result := Null;
else
raise TDBException.CreateFmt('Unknown type %d for field "%s"', [Integer(Column.DataType), ColumnName]);
end;
end
else
raise TDBException.CreateFmt('Field "%s" not found', [ColumnName]);
end;
{ TAIMPSqlBase }
function busy(UserData: Pointer; P2: integer): integer; cdecl;
begin
Sleep(100);
Result := 0;
end;
constructor TSQLBase.Create(AConnectMgr: TSQLConnectMgr);
begin
inherited Create;
FJournalModeType := ttDefault;
FSynchronousType := stDefault;
FOnError := Nil;
FConnectMgr := AConnectMgr;
FLock := TRWLock.Create;
FLinkedTables := TObjectList.Create;
FTransactions := 0;
FGlobalTransactionLock := TRWLock.Create;;
FInGlobalTransaction := False;
Open;
DataBaseInitTables;
end;
function TSQLBase.CreateView(const AQuery: String): TSQLView;
begin
Result := TSQLView.Create(Self, AQuery);
end;
function TSQLBase.DeleteTable(const ATableName: String): Boolean;
begin
Result := ExecSQL('DROP TABLE IF EXIST ' + ATableName);
end;
destructor TSQLBase.Destroy;
begin
Active := False;
FLinkedTables.Clear;
FreeAndNil(FLinkedTables);
FConnectMgr.Remove(Self);
FConnectMgr := Nil;
FreeAndNil(FGlobalTransactionLock);
FreeAndNil(FLock);
inherited Destroy;
end;
procedure TSQLBase.DataBaseInitTables;
begin
end;
procedure TSQLBase.ErrorMsg(AText: PChar; const ErrorCode: Integer; const Query: String = '');
begin
ErrorMsg(String(AText), ErrorCode, Query);
end;
procedure TSQLBase.AddLinkedTable(Table: TSQLTable);
begin
FLock.Lock(nsWriter);
try
FLinkedTables.Add(Table);
finally
FLock.UnLock;
end;
end;
procedure TSQLBase.BeginTransaction(const ATransactionType: TSQLBeginTransactionType = btDeferred);
var
TypeStr: String;
begin
//ExecSQL(Format('SAVEPOINT sp_%d;', [TInterlocked.Increment(FTransactions) - 1]));
FGlobalTransactionLock.Lock(nsReader);
// Çàïðåùàåì âñå äåéñòâèÿ ïî áàçå ñ äðóãèõ ïîòîêîâ
if ATransactionType = btGlobal then
begin
if not FInGlobalTransaction then
begin
FGlobalTransactionLock.Lock(nsWriter);
FInGlobalTransaction := True;
end;
end;
Lock(nsReader);
try
// Òèï òðàíçàêöèè btGlobal èñïîëüçîâàòü äëÿ CancelTransaction
if ATransactionType = btGlobal then
begin
// Æäåì, êîãäà äðóãèå ïîòîêè îòâàëÿòñÿ
while FTransactions > 0 do
Sleep(10);
end;
if FTransactions = 0 then
begin
Lock;
try
if FTransactions = 0 then
begin
case ATransactionType of
btDeferred:
TypeStr := 'DEFERRED';
btImmediate:
TypeStr := 'IMMEDIATE';
btExclusive, btGlobal:
TypeStr := 'EXCLUSIVE';
else
TypeStr := '';
end;
if ExecSQL(Format('BEGIN %s TRANSACTION;', [TypeStr])) then
AtomicIncrement(FTransactions);
end
else
AtomicIncrement(FTransactions);
finally
UnLock;
end;
end
else
AtomicIncrement(FTransactions);
finally
UnLock;
end;
end;
procedure TSQLBase.EndTransaction;
begin
//ExecSQL(Format('RELEASE SAVEPOINT sp_%d;', [TInterlocked.Decrement(FTransactions)]));
Lock(nsReader);
try
if FTransactions = 1 then
begin
Lock(nsWriter);
try
if FTransactions = 1 then
begin
if ExecSQL('END TRANSACTION;') then
AtomicExchange(FTransactions, 0);
if FInGlobalTransaction then
begin
FInGlobalTransaction := False;
FGlobalTransactionLock.UnLock;
Exit;
end;
end
else
AtomicDecrement(FTransactions);
finally
UnLock;
end;
end
else
AtomicDecrement(FTransactions);
finally
UnLock;
FGlobalTransactionLock.UnLock;
end;
end;
procedure TSQLBase.CancelTransaction;
begin
//ExecSQL(Format('ROLLBACK TO SAVEPOINT sp_%d;', [TInterlocked.Decrement(FTransactions)]));
Lock;
try
{$IFDEF DEBUG}
if not FInGlobalTransaction then
ErrorMsg('TSQLBase.CancelTransaction: Only for Global transactions!', -1);
{$ENDIF}
if AtomicDecrement(FTransactions) = 0 then
begin
ExecSQL('ROLLBACK TRANSACTION;');
FInGlobalTransaction := False;
FGlobalTransactionLock.UnLock;
end;
finally
UnLock;
end;
end;
function TSQLBase.ClearAll: Boolean;
var
AList: TStrings;
I: Integer;
begin
Result := PopulateTableNames(AList);
if Result then
try
for I := 0 to AList.Count - 1 do
Result := Result and ExecSQL('DROP TABLE IF EXISTS ' + AList[I]);
DataBaseInitTables;
finally
FreeAndNil(AList);
end;
end;
procedure TSQLBase.Close;
begin
// Êîììèòèì íåçàêðûòûå òðàíçàêöèè. Âñå ROLLBACK äîëæíû îòðàáàòûâàòüñÿ ëîêàëüíî â áëîêå except
Lock;
try
if Active then
begin
if (FTransactions > 0) then
begin
// Æäåì çàâåðøåíèÿ âñåõ òðàíçàêöèé
while FTransactions > 0 do
begin
UnLock;
Sleep(1);
Lock;
end;
end;
// Çàêðûâàåì îòêðûòûå çàïðîñû
ClosePreparedStatements;
// ïðèíóäèòåëüíûé ñáðîñ æóðíàëà äëÿ WAL
if JournalModeType = ttWAL then
JournalModeType := ttDelete;
// çàêðûâàåì ñîåäèíåíèå
CheckError(sqlite3_close(FDB));
end;
finally
FDB := nil;
UnLock;
end;
end;
procedure TSQLBase.ClosePreparedStatements;
var
I: Integer;
Table: TSQLTable;
stmt: sqlite3_stmt;
begin
CheckActive;
Lock;
try
// Î÷èñòêà ïðèëèíêîâàííûõ Views
if Assigned(FLinkedTables) then
begin
for I := 0 to FLinkedTables.Count - 1 do
begin