forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmormot.db.rad.unidac.pas
858 lines (797 loc) · 28.5 KB
/
mormot.db.rad.unidac.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
/// Database Framework for UniDac/AnyDac TDataSet Connection
// - 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.rad.unidac;
{
*****************************************************************************
Third Party UniDac Components Database Access for mormot.db.rad
- UniDac Database Engine Connection
*****************************************************************************
}
interface
{$ifdef FPC} // UniDac is a Delphi-specific feature
implementation // to compile a void unit on FPC
{$else}
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
variants,
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.datetime,
mormot.core.data,
mormot.core.variants,
mormot.core.rtti,
mormot.core.json,
mormot.core.buffers,
mormot.core.log,
mormot.db.core,
mormot.db.sql,
mormot.db.rad,
Uni,
UniProvider,
UniScript;
{ ************ UniDac Database Engine Connection }
const
cMSSQLProvider = 'prDirect';
type
/// Exception type associated to UniDAC database access
ESqlDBUniDAC = class(ESqlDBDataset);
/// connection properties definition using UniDAC database access
TSqlDBUniDACConnectionProperties = class(TSqlDBDatasetConnectionProperties)
protected
fSpecificOptions: TStringList;
/// initialize fForeignKeys content with all foreign keys of this DB
// - do nothing by now (UniDAC metadata may be used in the future)
procedure GetForeignKeys; override;
public
/// initialize the properties to connect via UniDAC database access
// - aServerName shall contain the UniDAC provider name, e.g. 'Oracle' - you
// can use the TSqlDBUniDACConnectionProperties.URI() to retrieve the
// provider name from its mormot.db.sql.TSqlDBDefinition enumeration,
// and optionally set some options, which will be added to the internal
// SpecificOptions[]:
// ! 'Oracle?ClientLibrary=oci64\oci.dll'
// ! 'MySQL?Server=192.168.2.60;Port=3306', 'world', 'root', 'dev'
// - aDatabaseName shall contain the database server name
constructor Create(const aServerName, aDatabaseName, aUserID, aPassWord: RawUtf8); override;
/// release internal structures
destructor Destroy; override;
/// create a new connection
// - caller is responsible of freeing this instance
// - this overridden method will create an TSqlDBUniDACConnection instance
function NewConnection: TSqlDBConnection; override;
/// compute the UniDAC URI from a given database engine and server name
// - the optional server name can contain a port number, specified after ':'
// - you can set an optional full path to the client library name,
// to be completed on the left side with the executable path
// - possible use may be:
// ! PropsOracle := TSqlDBUniDACConnectionProperties.Create(
// ! TSqlDBUniDACConnectionProperties.URI(dOracle,'','oci64\oci.dll'),
// ! 'tnsname','user',pass');
// ! PropsFirebird := TSqlDBUniDACConnectionProperties.Create(
// ! TSqlDBUniDACConnectionProperties.URI(dFirebird,'',
// ! 'Firebird\fbembed.dll'),'databasefilename','','');
// ! PropsMySQL := TSqlDBUniDACConnectionProperties.Create(
// ! TSqlDBUniDACConnectionProperties.URI(dMySQL,'192.168.2.60:3306'),
// ! 'world', 'root', 'dev');
class function URI(aServer: TSqlDBDefinition; const aServerName: RawUtf8;
const aLibraryLocation: TFileName = '';
aLibraryLocationAppendExePath: boolean = true): RawUtf8;
/// retrieve the column/field layout of a specified table
// - this overridden method will use UniDAC metadata to retrieve the information
procedure GetFields(const aTableName: RawUtf8; out Fields: TSqlDBColumnDefineDynArray); override;
/// get all table names
// - this overridden method will use UniDAC metadata to retrieve the information
procedure GetTableNames(out Tables: TRawUtf8DynArray); override;
/// retrieve the advanced indexed information of a specified Table
// - this overridden method will use UniDAC metadata to retrieve the information
procedure GetIndexes(const aTableName: RawUtf8; out Indexes: TSqlDBIndexDefineDynArray); override;
/// allow to set the options specific to a UniDAC driver
// - for instance, you can set for both SQLite3 and Firebird/Interbase:
// ! Props.SpecificOptions.Values['ClientLibrary'] := ClientDllName;
property SpecificOptions: TStringList
read fSpecificOptions;
end;
/// implements a direct connection via UniDAC database access
TSqlDBUniDACConnection = class(TSqlDBConnectionThreadSafe)
protected
fDatabase: TUniConnection;
public
/// prepare a connection for a specified UniDAC database access
constructor Create(aProperties: TSqlDBConnectionProperties); override;
/// release memory and connection
destructor Destroy; override;
/// connect to the specified database server using UniDAC
// - should raise an ESqlDBUniDAC on error
procedure Connect; override;
/// stop connection to the specified database server using UniDAC
// - should raise an ESqlDBUniDAC 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 UniDAC connection instance
property Database: TUniConnection
read fDatabase;
end;
/// implements a statement via a UniDAC connection
TSqlDBUniDACStatement = class(TSqlDBDatasetStatement)
protected
fBatchExecute: Boolean;
/// initialize and set fQuery: TUniQuery internal field as expected
procedure DatasetCreate; override;
/// set fQueryParams internal field as expected
function DatasetPrepare(const aSQL: string): boolean; override;
/// execute underlying TUniQuery.ExecSQL
procedure DatasetExecSQL; override;
/// overriden by itSDS to properly handle UniDAC parameters
procedure DataSetBindSqlParam(const aArrayIndex, aParamIndex: integer;
const aParam: TSqlDBParam); override;
public
end;
const
/// UniDAC provider names corresponding to mormot.db.sql recognized SQL engines
UNIDAC_PROVIDER: array[dOracle..high(TSqlDBDefinition)] of RawUtf8 = (
'Oracle', 'SQL Server', 'Access', 'MySQL', 'SQLite', 'InterBase',
'NexusDB', 'PostgreSQL', 'DB2', '', 'MySQL');
implementation
uses
DAScript,
CRDataTypeMap,
DBAccess;
{ TSqlDBUniDACConnectionProperties }
constructor TSqlDBUniDACConnectionProperties.Create(const aServerName,
aDatabaseName, aUserID, aPassWord: RawUtf8);
var
p: TSqlDBDefinition;
provider, options, namevalue: RawUtf8;
opt: PUtf8Char;
begin
Split(aServerName, '?', provider, options);
for p := Low(UNIDAC_PROVIDER) to high(UNIDAC_PROVIDER) do
if SameTextU(UNIDAC_PROVIDER[p], provider) then
begin
fDbms := p;
break;
end;
inherited Create(provider, aDatabaseName, aUserID, aPassWord);
fSpecificOptions := TStringList.Create;
opt := pointer(options);
while opt <> nil do
begin
GetNextItem(opt, ';', namevalue);
if namevalue <> '' then
fSpecificOptions.Add(Utf8ToString(namevalue));
end;
case fDbms of
dSQLite:
begin
// UniDAC support of SQLite3 is just buggy
{$ifdef FPC}
fSpecificOptions.Values['UseUnicode'] := 'true'; // FPC strings do like UTF8
{$else}
{$ifndef UNICODE}
fForceUseWideString := true; // for non-unicode Delphi
{$endif UNICODE}
{$endif FPC}
fSpecificOptions.Values['ForceCreateDatabase'] := 'true';
fSQLCreateField[ftInt64] := ' BIGINT'; // SQLite3 INTEGER = 32bit for UniDAC
end;
dFirebird:
begin
{$ifdef FPC}
fSpecificOptions.Values['UseUnicode'] := 'true'; // FPC strings do like UTF8
{$else}
{$ifndef UNICODE}
fForceUseWideString := true;
{$endif UNICODE}
{$endif FPC}
fSpecificOptions.Values['CharSet'] := 'UTF8';
fSpecificOptions.Values['CharLength'] := '2';
fSpecificOptions.Values['DescribeParams'] := 'true';
// http://www.devart.com/unidac/docs/index.html?ibprov_article.htm
end;
dOracle:
begin
{$ifdef FPC}
fSpecificOptions.Values['UseUnicode'] := 'true'; // FPC strings do like UTF8
{$else}
{$ifndef UNICODE}
fForceUseWideString := true; // for non-unicode Delphi
{$endif UNICODE}
{$endif FPC}
fSpecificOptions.Values['Direct'] := 'true';
fSpecificOptions.Values['HOMENAME'] := '';
end;
dMySQL,
dMariaDB:
begin
{$ifdef FPC}
fSpecificOptions.Values['UseUnicode'] := 'true'; // FPC strings do like UTF8
{$else}
{$ifndef UNICODE}
fForceUseWideString := true;
{$endif UNICODE}
{$endif FPC}
// s.d. 30.11.19 Damit der Connect schneller geht ! CRVioTCP.pas WaitForConnect
fSpecificOptions.Values['MySQL.ConnectionTimeout'] := '0';
end;
dMSSQL:
begin
{$ifdef ISDELPHI}
{$ifndef UNICODE}
fForceUseWideString := true;
{$endif UNICODE}
{$endif ISDELPHI}
if aUserID = '' then
fSpecificOptions.Values['Authentication'] := 'auWindows';
fSpecificOptions.Values['SQL Server.Provider'] := cMSSQLProvider;
// s.d. 30.11.19 Damit der Connect im Direct Mode so Schnell ist wie mit prAuto/OleDB
fSpecificOptions.Values['SQL Server.ConnectionTimeout'] := '0';
// http://www.devart.com/unidac/docs/index.html?sqlprov_article.htm
end;
dPostgreSQL:
begin // thanks delphinium for the trick!
{$ifdef FPC}
fSpecificOptions.Values['UseUnicode'] := 'true'; // FPC strings do like UTF8
{$else}
{$ifndef UNICODE}
fForceUseWideString := true;
{$endif UNICODE}
{$endif FPC}
fSpecificOptions.Values['CharSet'] := 'UTF8';
end;
end;
end;
destructor TSqlDBUniDACConnectionProperties.Destroy;
begin
fSpecificOptions.Free;
inherited;
end;
procedure TSqlDBUniDACConnectionProperties.GetFields(const aTableName: RawUtf8;
out Fields: TSqlDBColumnDefineDynArray);
var
meta: TDAMetaData;
n: integer;
F: TSqlDBColumnDefine;
FA: TDynArray;
hasSubType: boolean;
Owner, Table: RawUtf8;
begin
meta := (MainConnection as TSqlDBUniDACConnection).fDatabase.CreateMetaData;
try
FA.Init(TypeInfo(TSqlDBColumnDefineDynArray), Fields, @n);
FA.Compare := SortDynArrayAnsiStringI; // FA.Find() case insensitive
FillCharFast(F, SizeOf(F), 0);
meta.MetaDataKind := 'Columns';
Split(aTableName, '.', Owner, Table);
if Table = '' then
begin
Table := Owner;
Owner := '';
end;
if (Owner = '') and
(fDbms <> dOracle) then
Owner := MainConnection.Properties.DatabaseName; // itSDS
if Owner <> '' then
meta.Restrictions.Values['TABLE_SCHEMA'] := Utf8ToString(UpperCase(Owner))
else
meta.Restrictions.Values['SCOPE'] := 'LOCAL';
meta.Restrictions.Values['TABLE_NAME'] := Utf8ToString(UpperCase(Table));
meta.Open;
hasSubType := meta.FindField('DATA_SUBTYPE') <> nil;
while not meta.Eof do
begin
F.ColumnName := StringToUtf8(meta.FieldByName('COLUMN_NAME').AsString);
F.ColumnTypeNative := StringToUtf8(meta.FieldByName('DATA_TYPE').AsString);
if hasSubType then
F.ColumnTypeNative := F.ColumnTypeNative +
StringToUtf8(meta.FieldByName('DATA_SUBTYPE').AsString);
F.ColumnLength := meta.FieldByName('DATA_LENGTH').AsInteger;
F.ColumnScale := meta.FieldByName('DATA_SCALE').AsInteger;
F.ColumnPrecision := meta.FieldByName('DATA_PRECISION').AsInteger;
F.ColumnType := ColumnTypeNativeToDB(F.ColumnTypeNative, F.ColumnScale);
if F.ColumnType = ftUnknown then
begin
// UniDAC metadata failed -> use SQL
Fields := nil;
inherited GetFields(aTableName, Fields);
exit;
end;
FA.Add(F);
meta.Next;
end;
Setlength(Fields, n);
GetIndexesAndSetFieldsColumnIndexed(aTableName, Fields);
finally
meta.Free;
end;
end;
procedure TSqlDBUniDACConnectionProperties.GetIndexes(const aTableName: RawUtf8;
out Indexes: TSqlDBIndexDefineDynArray);
var
meta, indexs: TDAMetaData;
F: TSqlDBIndexDefine;
FA: TDynArray;
n: integer;
ColName, Owner, Table: RawUtf8;
ndxName: string;
begin
Indexes := nil;
FA.Init(TypeInfo(TSqlDBIndexDefineDynArray), Indexes, @n);
FillCharFast(F, SizeOf(F), 0);
meta := (MainConnection as TSqlDBUniDACConnection).fDatabase.CreateMetaData;
indexs := (MainConnection as TSqlDBUniDACConnection).fDatabase.CreateMetaData;
try
meta.MetaDataKind := 'Indexes';
meta.Restrictions.Values['TABLE_NAME'] := Utf8ToString(UpperCase(aTableName));
Split(aTableName, '.', Owner, Table);
if Table = '' then
begin
Table := Owner;
Owner := '';
end;
if (Owner = '') and
(fDbms <> dOracle) then
Owner := MainConnection.Properties.DatabaseName; // itSDS
if Owner <> '' then
meta.Restrictions.Values['TABLE_SCHEMA'] := Utf8ToString(UpperCase(Owner))
else
meta.Restrictions.Values['SCOPE'] := 'LOCAL';
meta.Restrictions.Values['TABLE_NAME'] := Utf8ToString(UpperCase(Table));
meta.Open;
while not meta.Eof do
begin
ndxName := meta.FieldByName('INDEX_NAME').AsString;
F.IndexName := StringToUtf8(ndxName);
F.KeyColumns := '';
indexs.MetaDataKind := 'indexcolumns';
if Owner <> '' then
indexs.Restrictions.Values['TABLE_SCHEMA'] := Utf8ToString(UpperCase(Owner))
else
indexs.Restrictions.Values['SCOPE'] := 'LOCAL';
indexs.Restrictions.Values['TABLE_NAME'] := Utf8ToString(UpperCase(aTableName));
indexs.Restrictions.Values['INDEX_NAME'] := ndxName;
indexs.Open;
while not indexs.Eof do
begin
ColName := StringToUtf8(indexs.FieldByName('COLUMN_NAME').AsString);
if F.KeyColumns = '' then
F.KeyColumns := ColName
else
F.KeyColumns := F.KeyColumns + ',' + ColName;
indexs.Next;
end;
FA.Add(F);
indexs.Close;
meta.Next;
end;
SetLength(Indexes, n);
finally
indexs.Free;
meta.Free;
end;
end;
procedure TSqlDBUniDACConnectionProperties.GetForeignKeys;
var
conn: TUniConnection;
begin
conn := (MainConnection as TSqlDBUniDACConnection).Database;
if conn = nil then
exit;
{ TODO : get FOREIGN KEYS from UniDAC metadata ? }
end;
procedure TSqlDBUniDACConnectionProperties.GetTableNames(
out Tables: TRawUtf8DynArray);
var
List: TStringList;
begin
List := TStringList.Create;
try
(MainConnection as TSqlDBUniDACConnection).fDatabase.GetTableNames(List);
StringListToRawUtf8DynArray(List, Tables);
exit;
finally
List.Free;
end;
inherited;
end;
function TSqlDBUniDACConnectionProperties.NewConnection: TSqlDBConnection;
begin
result := TSqlDBUniDACConnection.Create(self);
TSqlDBUniDACConnection(result).InternalProcess(speCreated);
end;
class function TSqlDBUniDACConnectionProperties.URI(aServer: TSqlDBDefinition;
const aServerName: RawUtf8; const aLibraryLocation: TFileName;
aLibraryLocationAppendExePath: boolean): RawUtf8;
var
Server, Port: RawUtf8;
begin
if aServer < low(UNIDAC_PROVIDER) then
result := ''
else
result := UNIDAC_PROVIDER[aServer];
if result = '' then
exit;
if aLibraryLocation <> '' then
begin
result := result + '?ClientLibrary=';
if aLibraryLocationAppendExePath then
result := result + StringToUtf8(Executable.ProgramFilePath);
result := result + StringToUtf8(aLibraryLocation);
end;
if aServerName <> '' then
begin
Split(aServerName, ':', Server, Port);
if aLibraryLocation = '' then
result := result + '?'
else
result := result + ';';
result := result + 'Server=' + Server;
if Port <> '' then
result := result + ';Port=' + Port;
end;
end;
{ TSqlDBUniDACConnection }
procedure TSqlDBUniDACConnection.Commit;
begin
inherited Commit;
try
fDatabase.Commit;
except
inc(fTransactionCount); // the transaction is still active
raise;
end;
end;
constructor TSqlDBUniDACConnection.Create(aProperties: TSqlDBConnectionProperties);
var
options: TStrings;
PortNumber, i: integer;
begin
inherited Create(aProperties);
if (aProperties.Dbms = dMSSQL) and
not SameText(cMSSQLProvider, 'prDirect') then
CoInit;
fDatabase := TUniConnection.Create(nil);
fDatabase.LoginPrompt := false;
fDatabase.ProviderName := Utf8ToString(fProperties.ServerName);
case aProperties.Dbms of
dSQLite, dFirebird, dPostgreSQL, dMySQL, dMariaDB, dDB2, dMSSQL:
fDatabase.Database := Utf8ToString(fProperties.DatabaseName);
else
fDatabase.Server := Utf8ToString(fProperties.DatabaseName);
end;
fDatabase.Username := Utf8ToString(fProperties.UserID);
fDatabase.Password := Utf8ToString(fProperties.PassWord);
if aProperties.Dbms in [dMySQL, dMariaDB] then
// s.d. 30.11.19 Damit der Connect schneller geht
fDatabase.SpecificOptions.Add('MySQL.ConnectionTimeout=0');
if aProperties.Dbms = dMSSQL then
begin
fDatabase.SpecificOptions.Add('SQL Server.Provider=' + cMSSQLProvider);
// s.d. 30.11.19 Damit der Connect im Direct Mode so Schnell ist wie mit prAuto/OleDB
fDatabase.SpecificOptions.Add('SQL Server.ConnectionTimeout=0');
end;
// handle the options set by TSqlDBUniDACConnectionProperties.URI()
options := (fProperties as TSqlDBUniDACConnectionProperties).fSpecificOptions;
if fDatabase.Server = '' then
fDatabase.Server := options.Values['Server'];
if fDatabase.Database = '' then
fDatabase.Database := options.Values['Database'];
if (fDatabase.Port = 0) and TryStrToInt(options.Values['Port'], PortNumber) then
fDatabase.Port := PortNumber;
for i := 0 to options.Count - 1 do
if FindRawUtf8(['Server', 'Database', 'Port'],
StringToUtf8(options.Names[i]), false) < 0 then
fDatabase.SpecificOptions.Add(options[i]);
end;
procedure TSqlDBUniDACConnection.Connect;
var
Log: ISynLog;
begin
if fDatabase = nil then
ESqlDBUniDAC.RaiseUtf8('%.Connect(%): Database=nil', [self,
fProperties.ServerName]);
Log := SynDBLog.Enter('Connect to ProviderName=% Database=% on Server=%',
[fDatabase.ProviderName, fDatabase.Database, fDatabase.Server], self);
try
case fProperties.Dbms of
dFirebird:
if (fDatabase.Server = '') and
not FileExists(fDatabase.Database) then
with TUniScript.Create(nil) do // always create database for embedded Firebird
try
NoPreconnect := true;
SQL.Text := Utf8ToString(fProperties.SQLCreateDatabase(fProperties.DatabaseName));
Connection := fDatabase;
Execute;
finally
Free;
end;
end;
fDatabase.Open;
inherited Connect; // notify any re-connection
if Log <> nil then
Log.Log(sllDB, 'Connected to % (%)',
[fDatabase.ProviderName, fDatabase.ServerVersionFull]);
except
on E: Exception do
begin
Disconnect; // clean up on fail
raise;
end;
end;
end;
procedure TSqlDBUniDACConnection.Disconnect;
begin
try
inherited Disconnect; // flush any cached statement
finally
if fDatabase <> nil then
fDatabase.Close;
end;
end;
destructor TSqlDBUniDACConnection.Destroy;
begin
try
Disconnect;
if (fProperties.Dbms = dMSSQL) and
not SameText(cMSSQLProvider, 'prDirect') then
CoUnInit;
except
on Exception do
end;
inherited;
FreeAndNil(fDatabase);
end;
function TSqlDBUniDACConnection.IsConnected: boolean;
begin
result := Assigned(fDatabase) and
fDatabase.Connected;
end;
function TSqlDBUniDACConnection.NewStatement: TSqlDBStatement;
begin
result := TSqlDBUniDACStatement.Create(self);
end;
procedure TSqlDBUniDACConnection.Rollback;
begin
inherited Rollback;
fDatabase.Rollback;
end;
procedure TSqlDBUniDACConnection.StartTransaction;
begin
inherited StartTransaction;
fDatabase.StartTransaction;
end;
{ TSqlDBUniDACStatement }
procedure TSqlDBUniDACStatement.DataSetBindSqlParam(const aArrayIndex,
aParamIndex: integer; const aParam: TSqlDBParam);
var
P: TDAParam;
i: PtrInt;
tmp: RawUtf8;
StoreVoidStringAsNull: boolean;
begin
P := TDAParam(fQueryParams[aParamIndex]);
if not P.InheritsFrom(TDAParam) then
begin
inherited DataSetBindSQLParam(aArrayIndex, aParamIndex, aParam);
exit;
end;
if fDatasetSupportBatchBinding then
fBatchExecute := (aArrayIndex < 0) and
(fParamsArrayCount > 0)
else
fBatchExecute := false;
if fBatchExecute then
P.ValueCount := fParamsArrayCount
else
P.ValueCount := 1;
with aParam do
begin
P.ParamType := SQLParamTypeToDBParamType(VInOut);
if VinOut <> paramInOut then
case VType of
mormot.db.core.ftNull:
if fBatchExecute then
for i := 0 to fParamsArrayCount - 1 do
P.Values[i].Clear
else
P.Clear;
mormot.db.core.ftInt64:
begin
if fBatchExecute then
for i := 0 to fParamsArrayCount-1 do
if VArray[i] = 'null' then
P.Values[i].Clear
else
P.Values[i].AsLargeInt := GetInt64(pointer(VArray[i]))
else if aArrayIndex >= 0 then
if VArray[aArrayIndex] = 'null' then
P.Clear
else
P.AsLargeInt := GetInt64(pointer(VArray[aArrayIndex]))
else
P.AsLargeInt := VInt64;
end;
mormot.db.core.ftDouble:
if fBatchExecute then
for i := 0 to fParamsArrayCount - 1 do
if VArray[i] = 'null' then
P.Values[i].Clear
else
P.Values[i].AsFloat := GetExtended(pointer(VArray[i]))
else if aArrayIndex >= 0 then
if VArray[aArrayIndex] = 'null' then
P.Clear
else
P.AsFloat := GetExtended(pointer(VArray[aArrayIndex]))
else
P.AsFloat := PDouble(@VInt64)^;
mormot.db.core.ftCurrency:
if fBatchExecute then
for i := 0 to fParamsArrayCount - 1 do
if VArray[i] = 'null' then
P.Values[i].Clear
else
P.Values[i].AsCurrency := StrToCurrency(pointer(VArray[i]))
else if aArrayIndex >= 0 then
if VArray[aArrayIndex] = 'null' then
P.Clear
else
P.AsCurrency := StrToCurrency(pointer(VArray[aArrayIndex]))
else
P.AsCurrency := PCurrency(@VInt64)^;
mormot.db.core.ftDate:
if fBatchExecute then
for i := 0 to fParamsArrayCount - 1 do
if VArray[i] = 'null' then
P.Values[i].Clear
else
begin
UnQuoteSQLStringVar(pointer(VArray[i]), tmp);
P.Values[i].AsDateTime := Iso8601ToDateTime(tmp);
end
else if aArrayIndex >= 0 then
if VArray[aArrayIndex] = 'null' then
P.Clear
else
begin
UnQuoteSQLStringVar(pointer(VArray[aArrayIndex]), tmp);
P.AsDateTime := Iso8601ToDateTime(tmp);
end
else
P.AsDateTime := PDateTime(@VInt64)^;
mormot.db.core.ftUTF8:
if fBatchExecute then
begin
StoreVoidStringAsNull := fConnection.Properties.StoreVoidStringAsNull;
for i := 0 to fParamsArrayCount - 1 do
if (VArray[i] = 'null') or
(StoreVoidStringAsNull and
(VArray[i] = #39#39)) then
P.Values[i].Clear
else
begin
UnQuoteSQLStringVar(pointer(VArray[i]), tmp);
{$ifdef UNICODE}
P.Values[i].AsWideString := Utf8ToString(tmp);
{$else}
if fForceUseWideString then
P.Values[i].AsWideString := Utf8ToWideString(tmp)
else
P.Values[i].AsString := Utf8ToString(tmp);
{$endif UNICODE}
end
end
else if aArrayIndex >= 0 then
if (VArray[aArrayIndex] = 'null') or
(fConnection.Properties.StoreVoidStringAsNull and
(VArray[aArrayIndex] = #39#39)) then
P.Clear
else
begin
UnQuoteSQLStringVar(pointer(VArray[aArrayIndex]), tmp);
{$ifdef UNICODE}
P.AsWideString := Utf8ToString(tmp);
{$else}
if fForceUseWideString then
P.AsWideString := Utf8ToWideString(tmp)
else
P.AsString := Utf8ToString(tmp);
{$endif UNICODE}
end
else if (VData = '') and
fConnection.Properties.StoreVoidStringAsNull then
P.Clear
else
{$ifdef UNICODE}
P.AsWideString := Utf8ToString(VData);
{$else}
if not fForceUseWideString then
P.AsString := Utf8ToString(VData)
else
P.AsWideString := Utf8ToWideString(VData);
{$endif UNICODE}
mormot.db.core.ftBlob:
if fBatchExecute then
for i := 0 to fParamsArrayCount - 1 do
if VArray[i] = 'null' then
P.Values[i].Clear
else
{$ifdef UNICODE}
begin
P.Values[i].AsBlobRef.Clear;
P.Values[i].AsBlobRef.Write(0, Length(VArray[aArrayIndex]),
pointer(VArray[aArrayIndex]));
end
{$else}
P.Values[i].AsString := VArray[aArrayIndex]
{$endif UNICODE}
else
if aArrayIndex >= 0 then
if VArray[aArrayIndex] = 'null' then
P.Clear
else
{$ifdef UNICODE}
begin
P.AsBlobRef.Clear;
P.AsBlobRef.Write(0, Length(VArray[aArrayIndex]),
pointer(VArray[aArrayIndex]));
end
else
begin
P.AsBlobRef.Clear;
P.AsBlobRef.Write(0, Length(VData), pointer(VData));
end;
{$else}
P.AsString := VArray[aArrayIndex]
else
P.AsString := VData
{$endif UNICODE}
else
ESqlDBUniDAC.RaiseUtf8(
'%.DataSetBindSQLParam: invalid type % on bound parameter #%',
[Self, ord(VType), aParamIndex + 1]);
end;
end;
end;
procedure TSqlDBUniDACStatement.DatasetCreate;
begin
fQuery := TUniQuery.Create(nil);
TUniQuery(fQuery).Connection :=
(fConnection as TSqlDBUniDACConnection).Database;
fDatasetSupportBatchBinding := true;
end;
function TSQLDBUniDACStatement.DatasetPrepare(const aSQL: string): boolean;
begin
(fQuery as TUniQuery).SQL.Text := aSQL;
TUniQuery(fQuery).Prepare;
fQueryParams := TUniQuery(fQuery).Params;
result := fQueryParams <> nil;
end;
procedure TSQLDBUniDACStatement.DatasetExecSQL;
begin
if fBatchExecute then
(fQuery as TUniQuery).Execute(fParamsArrayCount)
else
(fQuery as TUniQuery).Execute;
end;
{ ************ UniDac Database Engine Connection }
initialization
TSqlDBUniDACConnectionProperties.RegisterClassNameForDefinition;
{$endif FPC} // UniDac is a Delphi-specific
end.