forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmormot.db.sql.ibx.pas
1476 lines (1393 loc) · 44.6 KB
/
mormot.db.sql.ibx.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
/// Database Framework IBX/FB Pascal API Connection (beta)
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.db.sql.ibx;
{
*****************************************************************************
Direct FirebirdSQL Client Access using the FB / IBX2 Pascal API layer
- TSqlDBIbxConnection* and TSqlDBIbxStatement Classes
*****************************************************************************
Written by https://github.com/TTomas - BETA stage until further validated
more details on https://synopse.info/forum/viewtopic.php?pid=14086#p14086
For low level connection, uses the MWA Software Firebird Pascal API package,
(fbintf) part of IBX for Lazarus - https://www.mwasoftware.co.uk/fb-pascal-api
Only fbintf package need to be installed
- With explicit StartTransaction (or Batch): all statements in connection
are executed within this main transaction owned by the connection.
- If no explicit StartTransaction is called, all statements create their
own proper transaction on prepare, and COMMIT them after execution or
Eof or ReleaseRows. This implements a software-simulated "auto commit".
Each internal transaction is owned by the associated Statement.
- if TSqlDBIbxConnectionProperties.CreateDescendingOnlyPK is forced to True,
it will create only one descending PK index using this statement:
PRIMARY KEY(ID) using desc index PK_TableName
default dFirebird create two indexes on ID, one ascending, second descending
nedded for select max(ID) - see http://www.firebirdfaq.org/faq205
- Batch is implemented for insert, update, delete using "execute block"
- Firebird4 API interface, with its new IBatch interface for
insert/update also implemented in fbintf package.
}
interface
{$ifdef NOSYNDBIBX}
// NOSYNDBIBX from mormot2.lpk Lazarus package > Custom Options > Defines
implementation // compile a void unit if NOSYNDBIBX conditional is set
{$else}
{.$define ZEOSTRANS}
// simulate transaction management like ZeosLib (testing only)
// - Zeos don't commit read (select) statements and transaction remains open
// for a long period of time
// - only CommitRetaining transaction with write (insert, update, delete) statements
// - for testing purposes, to compare performance with ZeosLib
{$I mormot.defines.inc}
uses
types,
sysutils,
classes,
variants,
// main IBX/FB Pascal API units
IB,
// mORMot 2 units
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.json,
mormot.core.datetime,
mormot.core.data,
mormot.core.perf,
mormot.core.rtti,
mormot.core.log,
mormot.core.buffers,
mormot.db.core,
mormot.db.sql;
type
/// Exception type associated to the IBX/FB Pascal API database components
ESqlDBIbx = class(ESqlDBException);
/// implement properties shared by IBX/FB Pascal API connections
TSqlDBIbxConnectionProperties = class(TSqlDBConnectionPropertiesThreadSafe)
protected
fCreateDescendingOnlyPK: boolean;
fFirebirdLibraryPathName: string;
fIbxDBParams: TStringList;
fCreateIfNotExists: boolean;
procedure SetCreateDescendingOnlyPK(AValue: boolean);
/// initialize fForeignKeys content with all foreign keys of this DB
// - do nothing by now
procedure GetForeignKeys; override;
// Override to enable descending PK
function SqlFieldCreate(const aField: TSqlDBColumnCreate;
var aAddPrimaryKey: RawUtf8): RawUtf8; override;
public
/// initialize the properties to connect to the IBX/FB Pascal API engine
// - aServerName shall contain the Firebird server and port URI, e.g:
// HOST[:PORT], empty for embbeded firebird will set ThreadingMode to tmMainConnection
// - aDatabaseName, aUserID, aPassword
// - note that when run from mORMot's ORM, this class will by default
// create one connection per thread
constructor Create(const aServerName, aDatabaseName,
aUserID, aPassWord: RawUtf8); override;
/// finalize this connection properties
destructor Destroy; override;
/// create a new connection
// - caller is responsible of freeing this instance
// - this overridden method will create an TSqlDBIbxConnection instance
function NewConnection: TSqlDBConnection; override;
/// method overriden to support our CreateDescendingOnlyPK property
function SqlCreate(const aTableName: RawUtf8;
const aFields: TSqlDBColumnCreateDynArray; aAddID: boolean): RawUtf8; override;
/// method overriden to support our CreateDescendingOnlyPK property
function IsPrimaryKeyIndexed(var AscendingOnly: boolean): boolean; override;
published
/// full file path name to the firebird client dll (fbclient.dll), default ''
property FirebirdLibraryPathName: string
read fFirebirdLibraryPathName write fFirebirdLibraryPathName;
/// optional low-levl IBX DB Params, see documentation in IBX/FB Pascal API
property IbxDBParams: TStringList
read fIbxDBParams;
/// create the database file if not exists, default is True
property CreateIfNotExists: boolean
read fCreateIfNotExists;
/// force to create only a DESC index on primary key, for best performance
// - the default mORMot behavior is to create both ascending and descending
// indexes on the ID primary key: it is needed because only an ascending
// index is created on FireBird PK, and max(ID) is slow - see
// http://www.firebirdfaq.org/faq205
// - but having two indexes on same column slow down database writes
// - forcing this property to True will create only one descending PK index
property CreateDescendingOnlyPK: boolean
read fCreateDescendingOnlyPK write SetCreateDescendingOnlyPK;
end;
/// implements a connection via the IBX/FB Pascal API access layer
TSqlDBIbxConnection = class(TSqlDBConnectionThreadSafe)
protected
fFbLibraryPathName: string;
fDBParams: TStringList;
fCreateDBIfNotExists: boolean;
fDBName: string;
fFirebirdAPI: IFirebirdAPI;
fAttachment: IAttachment;
// Main Transaction used with Begin(Start)Transaction/Batch
fTPB: ITPB;
fTransaction: ITransaction;
function GetFirebirdAPI: IFirebirdAPI;
function GenerateTPB(aReadOnly: boolean = false): ITPB;
public
/// prepare a connection to a specified Firebird database server
constructor Create(aProperties: TSqlDBConnectionProperties); override;
/// finalize the connection
destructor Destroy; override;
/// connect to the specified Firebird server
// - should raise an ESqlDBIbx on error
procedure Connect; override;
/// stop connection to the specified Firebird database server
// - should raise an ESqlDBIbx on error
procedure Disconnect; override;
/// return TRUE if Connect has been already successfully called
function IsConnected: boolean; override;
/// create a new statement instance
function NewStatement: TSqlDBStatement; override;
/// begin a Transaction for this connection
procedure StartTransaction; override;
/// commit changes of a Transaction for this connection
// - StartTransaction method must have been called before
procedure Commit; override;
/// discard changes of a Transaction for this connection
// - StartTransaction method must have been called before
procedure Rollback; override;
/// access to the associated IBX/FB Pascal API connection instance
property Attachment: IAttachment
read fAttachment;
/// access to the associated IBX/FB Pascal raw API
property FirebirdAPI: IFirebirdAPI
read GetFirebirdAPI;
// main Transaction used with Begin(Start)Transaction/Batch
property Transaction: ITransaction
read fTransaction;
end;
TIBXColumnsMeta = record
SQLType: cardinal;
CodePage: TSystemCodePage;
Scale: integer;
Subtype: integer;
end;
/// implements a statement via a IBX/FB Pascal API database connection
TSqlDBIbxStatement = class(TSqlDBStatementWithParamsAndColumns)
protected
fAutoStartCommitTrans: boolean;
fStatement: IStatement;
fResultSet: IResultSet;
fResults: IResults;
fMeta: IMetaData;
fColumnsMeta: array of TIBXColumnsMeta;
fIbxParams: ISQLParams;
farrParams: array of ISQLParam;
// Internal Transaction used for all statements if not explicit StartTransaction/Batch
// This transaction is Started and COMMIT after execution (auto commit)
fInternalTPB: ITPB;
fInternalTransaction: ITransaction;
fReadOnlyTransaction: boolean;
procedure InternalStartTransaction;
procedure InternalCommitTransaction;
procedure ErrorColAndRowset(const Col: integer);
procedure CheckColAndRowset(const Col: integer);
{$ifdef HASINLINE} inline; {$endif}
function IbxSQLTypeToTSqlDBFieldType(const aColMeta: TIBXColumnsMeta): TSqlDBFieldType;
public
destructor Destroy; override;
/// Prepare an UTF-8 encoded SQL statement
// - parameters marked as ? will be bound later, before ExecutePrepared call
// - if ExpectResults is TRUE, then Step() and Column*() methods are available
// to retrieve the data rows
// - raise an ESqlDBIbx on any error
procedure Prepare(const aSQL: RawUtf8;
ExpectResults: boolean = false); overload; override;
/// Execute a prepared SQL statement
// - parameters marked as ? should have been already bound with Bind*() functions
// - this implementation will also handle bound array of values (if any)
// - this overridden method will log the SQL statement if sllSQL has been
// enabled in SynDBLog.Family.Level
// - raise an ESqlDBIbx on any error
procedure ExecutePrepared; override;
/// gets a number of updates made by latest executed statement
function UpdateCount: integer; override;
/// Reset the previous prepared statement
// - this overridden implementation will reset all bindings and the cursor state
// - raise an ESqlDBIbx on any error
procedure Reset; override;
/// Access the next or first row of data from the SQL Statement result
// - return true on success, with data ready to be retrieved by Column*() methods
// - return false if no more row is available (e.g. if the SQL statement
// is not a SELECT but an UPDATE or INSERT command)
// - if SeekFirst is TRUE, will put the cursor on the first row of results
// - raise an ESqlDBIbx on any error
function Step(SeekFirst: boolean = false): boolean; override;
/// free IResultSet/IResultSetMetaData when ISqlDBStatement is back in cache
procedure ReleaseRows; override;
/// return a Column integer value of the current Row, first Col is 0
function ColumnInt(Col: integer): Int64; override;
/// returns TRUE if the column contains NULL
function ColumnNull(Col: integer): boolean; override;
/// return a Column floating point value of the current Row, first Col is 0
function ColumnDouble(Col: integer): double; override;
/// return a Column date and time value of the current Row, first Col is 0
function ColumnDateTime(Col: integer): TDateTime; override;
/// return a Column currency value of the current Row, first Col is 0
function ColumnCurrency(Col: integer): currency; override;
/// return a Column UTF-8 encoded text value of the current Row, first Col is 0
function ColumnUtf8(Col: integer): RawUtf8; override;
/// return a Column as a blob value of the current Row, first Col is 0
function ColumnBlob(Col: integer): RawByteString; override;
/// return one column value into JSON content
procedure ColumnToJson(Col: integer; W: TJsonWriter); override;
end;
implementation
uses
IBErrorCodes;
{ TSqlDBIbxStatement }
procedure TSqlDBIbxStatement.InternalStartTransaction;
begin
{$ifndef ZEOSTRANS}
if (fInternalTransaction <> nil) and
fInternalTransaction.InTransaction then
ESqlDBIbx.RaiseUtf8('Invalid Internal %.StartTransaction: ' +
'Transaction is Started/InTransactions', [self]);
{$endif ZEOSTRANS}
if fInternalTransaction <> nil then
{$ifdef ZEOSTRANS}
begin
if not fInternalTransaction.InTransaction then
fInternalTransaction.Start(TACommit);
end
{$else}
fInternalTransaction.Start
{$endif ZEOSTRANS}
else
begin
if (fInternalTPB = nil) then
fInternalTPB := TSqlDBIbxConnection(Connection).GenerateTPB(fReadOnlyTransaction);
fInternalTransaction := TSqlDBIbxConnection(Connection).Attachment.
StartTransaction(fInternalTPB);
end;
end;
procedure TSqlDBIbxStatement.InternalCommitTransaction;
begin
if (fInternalTransaction <> nil) and
fInternalTransaction.InTransaction then
{$ifdef ZEOSTRANS}
if fStatement.GetSQLStatementType in
[SQLInsert, SQLUpdate, SQLDelete, SQLDDL, SQLSelectForUpdate,
SQLSetGenerator] then
fInternalTransaction.CommitRetaining;
{$else}
fInternalTransaction.Commit;
{$endif ZEOSTRANS}
end;
procedure TSqlDBIbxStatement.CheckColAndRowset(const Col: integer);
begin
if (fResultSet = nil) or
(cardinal(Col) >= cardinal(fColumnCount)) then
ErrorColAndRowset(Col);
end;
procedure TSqlDBIbxStatement.ErrorColAndRowset(const Col: integer);
begin
ESqlDBIbx.RaiseUtf8('%.ColumnInt(%) ResultSet=%',
[self, Col, fResultSet]);
end;
function TSqlDBIbxStatement.IbxSQLTypeToTSqlDBFieldType(
const aColMeta: TIBXColumnsMeta): TSqlDBFieldType;
var
scale: integer;
begin
case aColMeta.SQLType of
SQL_VARYING,
SQL_TEXT:
result := ftUtf8;
SQL_DOUBLE,
SQL_FLOAT:
result := ftDouble;
SQL_TIMESTAMP,
SQL_TIMESTAMP_TZ_EX,
SQL_TIME_TZ_EX,
SQL_TIMESTAMP_TZ,
SQL_TIME_TZ,
SQL_TYPE_TIME,
SQL_TYPE_DATE:
result := ftDate;
SQL_BOOLEAN,
SQL_LONG,
SQL_SHORT,
SQL_D_FLOAT,
SQL_INT64:
begin
scale := aColMeta.Scale;
if scale = 0 then
result := ftInt64
else
if scale >= -4 then
result := ftCurrency
else
result := ftDouble;
end;
SQL_BLOB:
begin
if aColMeta.Subtype = isc_blob_text then
result := ftUtf8
else
result := ftBlob;
end;
else
// SQL_INT128, SQL_DEC_FIXED, SQL_DEC16, SQL_DEC34
// SQL_NULL, SQL_ARRAY, SQL_QUAD
raise ESqlDBIbx.CreateUtf8('%: unexpected TIbxType %',
[self, aColMeta.SQLType]);
end;
end;
destructor TSqlDBIbxStatement.Destroy;
begin
InternalCommitTransaction;
if fResults <> nil then
fResults.SetRetainInterfaces(false);
if fResultSet <> nil then
fResultSet.SetRetainInterfaces(false);
fResultSet := nil;
fResults := nil;
if fStatement <> nil then
fStatement.SetRetainInterfaces(false);
fStatement := nil;
fInternalTransaction := nil;
fInternalTPB := nil;
inherited Destroy;
end;
procedure TSqlDBIbxStatement.Prepare(const aSQL: RawUtf8; ExpectResults: boolean);
var
con: TSqlDBIbxConnection;
tr: ITransaction;
fColumnMetaData: IColumnMetaData;
i, n: PtrInt;
name: string;
begin
SQLLogBegin(sllDB);
if (fStatement <> nil) or
(fResultSet <> nil) then
ESqlDBIbx.RaiseUtf8('%.Prepare() shall be called once', [self]);
inherited Prepare(aSQL, ExpectResults); // connect if necessary
fReadOnlyTransaction := IdemPChar(pointer(fSQL), 'SELECT');
con := (fConnection as TSqlDBIbxConnection);
if not con.IsConnected then
con.Connect;
if (con.Transaction = nil) or
not con.Transaction.GetInTransaction then
begin
fAutoStartCommitTrans := True;
InternalStartTransaction;
tr := fInternalTransaction;
end
else
begin
fAutoStartCommitTrans := False;
tr := con.Transaction;
end;
fStatement := con.Attachment.Prepare(
tr, {$ifdef UNICODE} Utf8ToString(fSQL) {$else} fSQL {$endif});
fStatement.SetStaleReferenceChecks(false);
fStatement.SetRetainInterfaces(true);
ClearColumns;
fIbxParams := fStatement.GetSQLParams;
SetLength(farrParams, fIbxParams.Count);
for i := 0 to fIbxParams.Count - 1 do
farrParams[i] := fIbxParams.getSQLParam(i);
if ExpectResults then
begin
fMeta := fStatement.GetMetaData;
n := fMeta.getCount;
SetLength(fColumnsMeta, n);
fColumn.Capacity := n;
for i := 0 to n - 1 do
begin
fColumnMetaData := fMeta.getColumnMetaData(i);
fColumnsMeta[i].SqlType := fColumnMetaData.GetSQLType;
fColumnsMeta[i].CodePage := fColumnMetaData.getCodePage;
fColumnsMeta[i].Scale := fColumnMetaData.getScale;
fColumnsMeta[i].Subtype := fColumnMetaData.getSubtype;
name := fColumnMetaData.getName;
AddColumn(// Delphi<2009: already UTF-8 encoded due to controls_cp=CP_UTF8
{$ifdef UNICODE}StringToUtf8{$endif}(name))^.ColumnType :=
IbxSQLTypeToTSqlDBFieldType(fColumnsMeta[i]);
end;
end;
SQLLogEnd;
end;
function DynRawUtf8ArrayToConst(const aValue: TRawUtf8DynArray): TTVarRecDynArray;
var
ndx: PtrInt;
begin
SetLength(result, Length(aValue));
for ndx := 0 to Length(aValue) - 1 do
begin
result[ndx].VType := vtAnsiString;
result[ndx].VAnsiString := pointer(aValue[ndx]);
end;
end;
function Param2Type(const aParam: ISQLParam): RawUtf8;
begin
case aParam.GetSQLType of
SQL_VARYING,
SQL_TEXT:
FormatUtf8('VARCHAR(%)', [aParam.GetSize], result);
SQL_DOUBLE,
SQL_D_FLOAT:
result := 'DOUBLE PRECISION';
SQL_FLOAT:
result := 'FLOAT';
SQL_LONG:
if aParam.getScale = 0 then
result := 'INTEGER'
else
begin
if aParam.getSubtype = 1 then
FormatUtf8('NUMERIC(9,%)', [-aParam.getScale], result)
else
FormatUtf8('DECIMAL(9,%)', [-aParam.getScale], result);
end;
SQL_SHORT:
if aParam.getScale = 0 then
result := 'SMALLINT'
else
begin
if aParam.getSubtype = 1 then
FormatUtf8('NUMERIC(4,%)', [-aParam.getScale], result)
else
FormatUtf8('DECIMAL(4,%)', [-aParam.getScale], result);
end;
SQL_TIMESTAMP:
result := 'TIMESTAMP';
SQL_BLOB:
if aParam.getSubtype = isc_blob_text then
result := 'BLOB SUB_TYPE TEXT'
else
result := 'BLOB';
//SQL_ARRAY = 540;
//SQL_QUAD = 550;
SQL_TYPE_TIME:
result := 'TIME';
SQL_TYPE_DATE:
result := 'DATE';
SQL_INT64: // IB7
if aParam.getScale = 0 then
result := 'BIGINT'
else
begin
if aParam.getSubtype = 1 then
FormatUtf8('NUMERIC(18,%)', [-aParam.getScale], result)
else
FormatUtf8('DECIMAL(18,%)', [-aParam.getScale], result);
end;
SQL_BOOLEAN:
result := 'BOOLEAN';
SQL_NULL{FB25}:
result := 'CHAR(1)';
end;
end;
function Min(a, b: PtrInt): PtrInt;
{$ifdef HASINLINE}inline;{$endif}
begin
if a < b then
result := a
else
result := b;
end;
procedure TSqlDBIbxStatement.ExecutePrepared;
var
con: TSqlDBIbxConnection;
i: integer;
procedure BatchArrayExecute;
var
iP, iA: PtrInt;
begin
fStatement.SetBatchRowLimit(fParamsArrayCount);
for iA:=0 to fParamsArrayCount-1 do
begin
for iP := 0 to fParamCount - 1 do
// set parameters as expected by FirebirdSQL
begin
with fParams[iP] do
begin
case VType of
ftUnknown,
ftNull:
farrParams[iP].SetIsNull(True);
else
if VArray[iA]='null' then
farrParams[iP].SetIsNull(True)
else
begin
case VType of
ftDate:
farrParams[iP].SetAsDateTime(Iso8601ToDateTimePUtf8Char(
PUtf8Char(pointer(VArray[iA])) + 1, Length(VArray[iA]) - 2));
ftInt64:
farrParams[iP].SetAsInt64(GetInt64(pointer(VArray[iA])));
ftDouble:
farrParams[iP].SetAsDouble(GetExtended(pointer(VArray[iA])));
ftCurrency:
farrParams[iP].SetAsCurrency(StrToCurrency(pointer(VArray[iA])));
ftUtf8:
farrParams[iP].SetAsString(UnQuoteSqlString(VArray[iA]));
ftBlob:
farrParams[iP].SetAsString(VArray[iA]);
else
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared: Invalid type parameter #%', [self, i]);
end;
end
end;
end;
end;
try
fStatement.AddToBatch;
except
on E: EIBBatchBufferOverflow do
begin
if fAutoStartCommitTrans then
begin
fStatement.ExecuteBatch(fInternalTransaction);
InternalCommitTransaction;
InternalStartTransaction;
end
else
fStatement.ExecuteBatch(con.fTransaction);
{you might want to check the batch completion info here - see 6.8.3}
fStatement.AddToBatch;
end
else
raise;
end;
end;
if fAutoStartCommitTrans then
begin
fStatement.ExecuteBatch(fInternalTransaction);
InternalCommitTransaction;
end
else
fStatement.ExecuteBatch(con.fTransaction);
end;
procedure BlockArrayExecute;
const
cMaxStm = 50; // max statements in execute block, FB max is 255
var
oldSQL: RawUtf8;
aPar: TRawUtf8DynArray;
aParTyp: TRawUtf8DynArray;
iP, iA, iStart, iEnd, iCnt, iStmCount: integer;
W: TTextWriter;
newStatement: IStatement;
procedure PrepareBlockStatement;
begin
newStatement := con.Attachment.Prepare(
fStatement.GetTransaction,
{$ifdef UNICODE} Utf8ToString(W.Text) {$else} W.Text {$endif});
newStatement.SetStaleReferenceChecks(false);
end;
procedure ExecuteBlockStatement;
var
iP, iA, ndx: PtrInt;
iParams: ISQLParams;
iParam: ISQLParam;
begin
// Bind Params
iParams := newStatement.GetSQLParams;
ndx := fParamCount * (iEnd - iStart + 1);
if iParams.Count <> ndx then
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared expected % bound parameters, got %',
[self, iParams.Count, fParamCount * ndx]);
for iP := 0 to fParamCount - 1 do
begin
if fParams[iP].VInt64 <> fParamsArrayCount then
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared: #% parameter expected array count %, got %',
[self, iP, fParamsArrayCount, fParams[iP].VInt64]);
with fParams[iP] do
begin
case VType of
ftUnknown:
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared: Unknown type array parameter #%',
[self, iP]);
ftNull:
// handle null column
for iA := 0 to iEnd-iStart do
iParams.getSQLParam(iA * fParamCount + iP).SetIsNull(true);
else
for iA := 0 to iEnd - iStart do
begin
iParam := iParams.getSQLParam(iA * fParamCount + iP);
ndx := iA + iStart;
if VArray[ndx] = 'null' then
iParam.SetIsNull(true)
else
begin
case VType of
ftDate:
iParam.SetAsDateTime(Iso8601ToDateTimePUtf8Char(
PUtf8Char(pointer(VArray[ndx])) + 1, Length(VArray[ndx]) - 2));
ftInt64:
iParam.SetAsInt64(GetInt64(pointer(VArray[ndx])));
ftDouble:
iParam.SetAsDouble(GetExtended(pointer(VArray[ndx])));
ftCurrency:
iParam.SetAsCurrency(StrToCurrency(pointer(VArray[ndx])));
ftUtf8:
iParam.SetAsString(UnQuoteSqlString(VArray[ndx]));
ftBlob:
iParam.SetAsString(VArray[ndx]);
else
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared: Invalid type parameter #%', [self, ndx]);
end;
end;
end;
end;
end;
end;
// 4. Execute
newStatement.Execute;
end;
begin
// 1. Create execute block SQL
oldSQL := StringReplaceAll(fSql, '?', '%');
SetLength(aParTyp, fParamCount);
SetLength(aPar, fParamCount);
for iP := 0 to fParamCount-1 do
aParTyp[iP] := Param2Type(fIbxParams.Params[iP]);
iStart := 0;
iStmCount := Round(fParamsArrayCount /
Round(fParamsArrayCount / cMaxStm + 0.5));
W := TTextWriter.CreateOwnedStream(49152);
try
while iStart < fParamsArrayCount do
begin
iEnd := Min(iStart + iStmCount - 1, fParamsArrayCount - 1);
if (iStart = 0) or
(iEnd - iStart + 1 <> iStmCount) then
begin
iStmCount := iEnd - iStart + 1;
W.CancelAll;
W.AddShort('execute block('#10);
iCnt := 0;
for iA := iStart to iEnd do
for iP := 0 to fParamCount - 1 do
begin
W.Add('p');
W.AddU(iCnt);
W.Add(' ');
W.AddString(aParTyp[iP]);
W.Add('=','?');
W.AddComma;
inc(iCnt);
end;
W.CancelLastComma;
W.AddShort(') as begin'#10);
iCnt := 0;
for iA := iStart to iEnd do
begin
for iP := 0 to fParamCount - 1 do
begin
FormatUtf8(':p%', [iCnt], aPar[iP]);
Inc(iCnt);
end;
W.Add(oldSQL, DynRawUtf8ArrayToConst(aPar));
W.Add(';', #10);
end;
W.AddShorter('end');
PrepareBlockStatement;
end;
ExecuteBlockStatement;
inc(iStart, iStmCount);
end;
finally
W.Free;
end;
end;
begin
SQLLogBegin(sllSQL);
inherited ExecutePrepared;
if fStatement = nil then
ESqlDBIbx.RaiseUtf8('%.ExecutePrepared() invalid call', [self]);
con := (fConnection as TSqlDBIbxConnection);
fAutoStartCommitTrans := (con.fTransaction=nil) or
not con.fTransaction.GetInTransaction;
if fAutoStartCommitTrans and
((fInternalTransaction=nil) or
not fInternalTransaction.GetInTransaction) then
begin
InternalStartTransaction;
if not fStatement.IsPrepared then
begin
fStatement.Prepare(fInternalTransaction);
fStatement.SetStaleReferenceChecks(false);
fStatement.SetRetainInterfaces(true);
end;
end;
if fParamsArrayCount > 0 then // Array Bindings
begin
if fIbxParams.Count <> fParamCount then
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared expected % bound parameters, got %',
[self, fIbxParams.Count, fParamCount]);
if fExpectResults then
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared cant ExpectResults with ArrayParams', [self]);
if fStatement.HasBatchMode and
(fStatement.GetSQLStatementType in [SQLInsert,SQLUpdate]) then
BatchArrayExecute
else
BlockArrayExecute;
end
else
begin
if fIbxParams.Count <> fParamCount then
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared expected % bound parameters, got %',
[self, fIbxParams.Count, fParamCount]);
for i := 0 to fParamCount - 1 do
// set parameters as expected by FirebirdSQL
begin
with fParams[i] do
begin
case VType of
ftUnknown,
ftNull:
farrParams[i].SetIsNull(True);
ftDate:
farrParams[i].SetAsDateTime(PDateTime(@VInt64)^);
ftInt64:
farrParams[i].SetAsInt64(PInt64(@VInt64)^);
ftDouble:
farrParams[i].SetAsDouble(unaligned(PDouble(@VInt64)^));
ftCurrency:
farrParams[i].SetAsCurrency(PCurrency(@VInt64)^);
ftUtf8:
farrParams[i].SetAsString(VData);
ftBlob:
farrParams[i].SetAsString(VData);
else
ESqlDBIbx.RaiseUtf8(
'%.ExecutePrepared: Invalid type parameter #%', [self, i]);
end;
end;
end;
if fExpectResults then
begin
fCurrentRow := -1;
if fAutoStartCommitTrans then
fResultSet := fStatement.OpenCursor(fInternalTransaction)
else
fResultSet := fStatement.OpenCursor(con.fTransaction);
fResults := fResultSet;
fResultSet.SetRetainInterfaces(true);
if not fResultSet.IsEof then
fCurrentRow:=0;
if fResultSet = nil then
SynDBLog.Add.Log(sllWarning,'Ibx.ExecutePrepared returned nil %',
[fSQL], self);
end
else
begin
if fAutoStartCommitTrans then
begin
fResults := fStatement.Execute(fInternalTransaction);
InternalCommitTransaction;
end
else
fResults := fStatement.Execute(con.fTransaction);
end;
end;
SQLLogEnd;
end;
function TSqlDBIbxStatement.UpdateCount: integer;
var
s, i, u, d: integer;
begin
s := 0;
i := 0;
u := 0;
d := 0;
result := 0;
if fStatement <> nil then
if fStatement.GetRowsAffected(s, i, u, d) then
result := i + u + d;
end;
procedure TSqlDBIbxStatement.Reset;
begin
InternalCommitTransaction;
inherited Reset;
end;
function TSqlDBIbxStatement.Step(SeekFirst: boolean): boolean;
begin
if fColumnCount = 0 then // no row returned
result := false
else if fResultSet = nil then
raise ESqlDBIbx.CreateUtf8('%.Step() invalid self', [self])
else if SeekFirst then
begin
result := fResultSet.FetchNext;
if result then
fCurrentRow := 1
else
begin
fCurrentRow := 0;
InternalCommitTransaction;
end;
end
else
begin
result := fResultSet.FetchNext;
if result then
inc(fCurrentRow)
else
InternalCommitTransaction;
end;
if not result then
fResultSet.Close;
end;
procedure TSqlDBIbxStatement.ReleaseRows;
begin
InternalCommitTransaction;
if fResultSet <> nil then
begin
fResultSet.SetRetainInterfaces(false);
fResultSet.Close;
fResultSet := nil;
end;
if fResults <> nil then
begin
fResults.SetRetainInterfaces(false);
fResults := nil;
end;
inherited ReleaseRows;
end;
function TSqlDBIbxStatement.ColumnInt(Col: integer): Int64;
begin
CheckColAndRowset(Col);
result := fResults[Col].GetAsInt64;
end;
function TSqlDBIbxStatement.ColumnNull(Col: integer): boolean;
var
len: SmallInt;
data: PByte;
begin
CheckColAndRowset(Col);
fResultSet.GetData(Col, result, len, data);
end;
function TSqlDBIbxStatement.ColumnDouble(Col: integer): double;
begin
CheckColAndRowset(Col);
result := fResults[Col].GetAsDouble;
end;
function TSqlDBIbxStatement.ColumnDateTime(Col: integer): TDateTime;
begin
CheckColAndRowset(Col);
result := fResults[Col].GetAsDateTime;
end;
function TSqlDBIbxStatement.ColumnCurrency(Col: integer): currency;
var
nul: boolean;
len: smallint;
data: PByte;
begin
CheckColAndRowset(Col);
if fColumnsMeta[Col].Scale = -4 then
begin
fResults.GetData(Col, nul, len, data);
PInt64(@result)^ := PInt64(data)^;
end
else
result := fResults[Col].GetAsCurrency;
end;
function TSqlDBIbxStatement.ColumnUtf8(Col: integer): RawUtf8;
var
nul: boolean;
len: smallint;
data: PByte;
begin
CheckColAndRowset(Col);
if (fColumnsMeta[Col].CodePage = CP_UTF8) and
(fColumnsMeta[Col].SqlType <> SQL_BLOB) then // blob requires GetAsString
begin
fResults.GetData(Col, nul, len, data);
FastSetString(result, data, len);
end
else
result := fResults[Col].GetAsString;
end;
function TSqlDBIbxStatement.ColumnBlob(Col: integer): RawByteString;
begin
CheckColAndRowset(Col);
result := fResults[Col].GetAsString;
end;
procedure TSqlDBIbxStatement.ColumnToJson(Col: integer; W: TJsonWriter);
var
s: RawUtf8;
isNull: boolean;
len: smallint;
data: PByte;
begin
fResults.GetData(Col, isNull, len, data);
if isNull then
W.AddNull
else
begin
with fColumnsMeta[Col] do
case SQLType of
SQL_VARYING,
SQL_TEXT: