forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmormot.db.sql.odbc.pas
More file actions
1702 lines (1617 loc) · 58 KB
/
Copy pathmormot.db.sql.odbc.pas
File metadata and controls
1702 lines (1617 loc) · 58 KB
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 Direct ODBC 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.sql.odbc;
{
*****************************************************************************
Efficient SQL Database Connection via ODBC
- TSqlDBOdbcConnection* and TSqlDBOdbcStatement Classes
*****************************************************************************
}
interface
{$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.rtti,
mormot.core.json,
mormot.core.perf,
mormot.core.log,
mormot.db.core,
mormot.db.sql;
{ ************ TSqlDBOdbcConnection* and TSqlDBOdbcStatement Classes }
type
/// will implement properties shared by the ODBC library
TSqlDBOdbcConnectionProperties = class(TSqlDBConnectionPropertiesThreadSafe)
protected
fDriverDoesNotHandleUnicode: boolean;
fSqlDriverConnectPrompt: boolean;
fSqlStatementTimeout: integer;
/// this overridden method will hide de DATABASE/PWD fields in ODBC connection string
function GetDatabaseNameSafe: RawUtf8; override;
/// this overridden method will retrieve the kind of DBMS from the main connection
function GetDbms: TSqlDBDefinition; override;
public
/// initialize the connection properties
// - will raise an exception if the ODBC library is not available
// - SQLConnect() API will be used if aServerName is set: it should contain
// the ODBC Data source name as defined in "ODBC Data Source Administrator"
// tool (C:\Windows\SysWOW64\odbcad32.exe for 32bit app on Win64) - in this
// case, aDatabaseName will be ignored
// - SqlDriverConnect() API will be used if aServerName is '' and
// aDatabaseName is set - in this case, aDatabaseName should contain a
// full connection string like (e.g. for a local SQLEXPRESS instance):
// ! 'DRIVER=SQL Server Native Client 10.0;UID=.;server=.\SQLEXPRESS;'+
// ! 'Trusted_Connection=Yes;MARS_Connection=yes'
// see @http://msdn.microsoft.com/en-us/library/ms715433
// or when using Firebird ODBC:
// ! 'DRIVER=Firebird/InterBase(r) driver;CHARSET=UTF8;UID=SYSDBA;PWD=masterkey;'
// ! 'DBNAME=MyServer/3051:C:\database\myData.fdb'
// ! 'DRIVER=Firebird/InterBase(r) driver;CHARSET=UTF8;DBNAME=dbfile.fdb;'+
// ! 'CLIENT=fbembed.dll'
// for IBM DB2 and its official driver:
// ! 'Driver=IBM DB2 ODBC DRIVER;Database=SAMPLE;'+
// ! 'Hostname=localhost;Port=50000;UID=db2admin;Pwd=db2Password'
// for PostgreSQL - driver from http://ftp.postgresql.org/pub/odbc/versions/msi
// ! 'Driver=PostgreSQL Unicode;Database=postgres;'+
// ! 'Server=localhost;Port=5432;UID=postgres;Pwd=postgresPassword'
// for MySQL - driver from https://dev.mysql.com/downloads/connector/odbc
// (note: 5.2.6 and 5.3.1 driver seems to be slow in ODBC.FreeHandle)
// ! 'Driver=MySQL ODBC 5.2 UNICODE Driver;Database=test;'+
// ! 'Server=localhost;Port=3306;UID=root;Pwd='
// for IBM Informix and its official driver:
// ! 'Driver=IBM INFORMIX ODBC DRIVER;Database=SAMPLE;'+
// ! 'Host=localhost;Server=<instance name on host>;Service=<service name
// ! in ../drivers/etc/services>;Protocol=olsoctcp;UID=<Windows/Linux user account>;
// ! Pwd=<Windows/Linux user account password>'
constructor Create(const aServerName, aDatabaseName,
aUserID, aPassWord: RawUtf8); override;
/// create a new connection
// - call this method if the shared MainConnection is not enough (e.g. for
// multi-thread access)
// - the caller is responsible of freeing this instance
// - this overridden method will create an TSqlDBOdbcConnection instance
function NewConnection: TSqlDBConnection; override;
/// get all table names
// - will retrieve the corresponding metadata from ODBC library if SQL
// direct access was not defined
procedure GetTableNames(out Tables: TRawUtf8DynArray); override;
/// get all view names
// - will retrieve the corresponding metadata from ODBC library if SQL
// direct access was not defined
procedure GetViewNames(out Views: TRawUtf8DynArray); override;
/// retrieve the column/field layout of a specified table
// - will also check if the columns are indexed
// - will retrieve the corresponding metadata from ODBC library if SQL
// direct access was not defined (e.g. for dDB2)
procedure GetFields(const aTableName: RawUtf8;
out Fields: TSqlDBColumnDefineDynArray); override;
/// initialize fForeignKeys content with all foreign keys of this DB
// - used by GetForeignKey method
procedure GetForeignKeys; override;
/// retrieve a list of stored procedure names from current connection
procedure GetProcedureNames(out Procedures: TRawUtf8DynArray); override;
/// retrieve procedure input/output parameter information
// - aProcName: stored procedure name to retrieve parameter infomation.
// - Parameters: parameter list info (name, datatype, direction, default)
procedure GetProcedureParameters(const aProcName: RawUtf8;
out Parameters: TSqlDBProcColumnDefineDynArray); override;
/// if full connection string may prompt the user for additional information
// - property used only with SqlDriverConnect() API (i.e. when aServerName
// is '' and aDatabaseName contains a full connection string)
// - set to TRUE to allow UI prompt if needed
property SqlDriverConnectPrompt: boolean
read fSqlDriverConnectPrompt write fSqlDriverConnectPrompt;
/// The number of seconds to wait for a SQL statement to execute before canceling the query.
// When set to 0 (the default) there is no timeout. See ODBC SQL_QUERY_TIMEOUT documentation
property SqlStatementTimeoutSec: integer
read fSqlStatementTimeout write fSqlStatementTimeout;
end;
/// implements a direct connection to the ODBC library
TSqlDBOdbcConnection = class(TSqlDBConnectionThreadSafe)
protected
fOdbcProperties: TSqlDBOdbcConnectionProperties;
fEnv: pointer;
fDbc: pointer;
fDbms: TSqlDBDefinition;
fDbmsName, fDriverName, fDbmsVersion, fSqlDriverFullString: RawUtf8;
public
/// connect to a specified ODBC database
constructor Create(aProperties: TSqlDBConnectionProperties); override;
/// release memory and connection
destructor Destroy; override;
/// connect to the ODBC library, i.e. create the DB instance
// - should raise an Exception on error
// - if TSqlDBOdbcConnectionProperties.Dbms has not been forced, will try to
// recognize the DBMS from the connection DriverName/DbmsName text
procedure Connect; override;
/// stop connection to the ODBC library, i.e. release the DB instance
// - should raise an Exception on error
procedure Disconnect; override;
/// return TRUE if Connect has been already successfully called
function IsConnected: boolean; override;
/// initialize a new SQL query statement for the given connection
// - the caller should free the instance after use
function NewStatement: TSqlDBStatement; override;
/// begin a Transaction for this connection
// - current implementation do not support nested transaction with those
// methods: exception will be raised in such case
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;
/// the remote DBMS type, as retrieved at ODBC connection opening
property Dbms: TSqlDBDefinition
read fDbms;
/// the full connection string (expanded from ServerName)
property SqlDriverFullString: RawUtf8
read fSqlDriverFullString;
published
/// the remote DBMS name, as retrieved at ODBC connection opening
property DbmsName: RawUtf8
read fDbmsName;
/// the remote DBMS version, as retrieved at ODBC connection opening
property DbmsVersion: RawUtf8
read fDbmsVersion;
/// the local driver name, as retrieved at ODBC connection opening
property DriverName: RawUtf8
read fDriverName;
end;
/// implements a statement using a ODBC connection
TSqlDBOdbcStatement = class(TSqlDBStatementWithParamsAndColumns)
protected
fStatement: pointer;
fColData: TRawByteStringDynArray;
fSqlW: RawByteString;
procedure AllocStatement;
procedure DeallocStatement;
function CType2SQL(CDataType: integer): integer;
procedure BindColumns;
procedure GetData(var Col: TSqlDBColumnProperty; ColIndex: integer);
function GetCol(Col: integer; ExpectedType: TSqlDBFieldType): TSqlDBStatementGetCol;
function MoreResults: boolean;
public
/// create a ODBC statement instance, from an existing ODBC connection
// - the Execute method can be called once per TSqlDBOdbcStatement instance,
// but you can use the Prepare once followed by several ExecutePrepared methods
// - if the supplied connection is not of TOleDBConnection type, will raise
// an exception
constructor Create(aConnection: TSqlDBConnection); override;
// release all associated memory and ODBC handles
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 EOdbcException or ESqlDBException 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 overridden method will log the SQL statement if sllSQL has been
// enabled in SynDBLog.Family.Level
// - raise an EOdbcException or ESqlDBException on any error
procedure ExecutePrepared; override;
/// Reset the previous prepared statement
// - this overridden implementation will reset all bindings and the cursor state
// - raise an EOdbcException on any error
procedure Reset; override;
/// After a statement has been prepared via Prepare() + ExecutePrepared() or
// Execute(), this method must be called one or more times to evaluate it
// - you shall call this method before calling any Column*() methods
// - return TRUE on success, with data ready to be retrieved by Column*()
// - return FALSE if no more row is available (e.g. if the SQL statement
// is not a SELECT but an UPDATE or INSERT command)
// - access the first or next row of data from the SQL Statement result:
// if SeekFirst is TRUE, will put the cursor on the first row of results,
// otherwise, it will fetch one row of data, to be called within a loop
// - raise an EOdbcException or ESqlDBException exception on any error
function Step(SeekFirst: boolean = false): boolean; override;
/// close the ODBC statement cursor resources
procedure ReleaseRows; override;
/// returns TRUE if the column contains NULL
function ColumnNull(Col: integer): boolean; override;
/// return a Column integer value of the current Row, first Col is 0
function ColumnInt(Col: integer): Int64; override;
/// return a Column floating point value of the current Row, first Col is 0
function ColumnDouble(Col: integer): double; override;
/// return a Column floating point 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
// - should retrieve directly the 64 bit Currency content, to avoid
// any rounding/conversion error from floating-point types
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
// - ColumnBlob() will return the binary content of the field is was not ftBlob,
// e.g. a 8 bytes RawByteString for a vtInt64/vtDouble/vtDate/vtCurrency,
// or a direct mapping of the RawUnicode
function ColumnBlob(Col: integer): RawByteString; override;
/// return one column value into JSON content
procedure ColumnToJson(Col: integer; W: TJsonWriter); override;
/// returns the number of rows updated by the execution of this statement
function UpdateCount: integer; override;
end;
// backward compatibility types redirections
{$ifndef PUREMORMOT2}
type
TODBCConnectionProperties = TSqlDBOdbcConnectionProperties;
TODBCConnection = TSqlDBOdbcConnection;
TODBCStatement = TSqlDBOdbcStatement;
{$endif PUREMORMOT2}
implementation
uses
mormot.db.raw.odbc; // define raw ODBC library API
{ ************ TSqlDBOdbcConnection* and TSqlDBOdbcStatement Classes }
{ TSqlDBOdbcConnection }
const
DBMS_NAMES: array[0..10] of PAnsiChar = (
'ORACLE',
'MICROSOFT SQL',
'ACCESS',
'MYSQL',
'MARIA',
'SQLITE',
'FIREBIRD',
'INTERBASE',
'POSTGRE',
'INFORMIX',
nil);
DBMS_TYPES: array[-1..high(DBMS_NAMES) - 1] of TSqlDBDefinition = (
dDefault,
dOracle, // 'ORACLE'
dMSSQL, // 'MICROSOFT SQL'
dJet, // 'ACCESS'
dMySQL, // 'MYSQL'
dMariaDB, // 'MARIA'
dSQLite, // 'SQLITE'
dFirebird, // 'FIREBIRD'
dFirebird, // 'INTERBASE'
dPostgreSql, // 'POSTGRE'
dInformix); // 'INFORMIX'
DRIVER_NAMES: array[0..23] of PAnsiChar = (
'SQLSRV',
'LIBTDSODBC',
'IVSS',
'IVMSSS',
'PBSS',
'DB2CLI',
'LIBDB2',
'IVDB2',
'PBDB2',
'MSDB2',
'CWBODBC',
'MYODBC',
'MARIA',
'SQORA',
'MSORCL',
'PBOR',
'IVOR',
'ODBCFB',
'IB',
'SQLITE',
'PSQLODBC',
'NXODBCDRIVER',
'ICLIT09B',
nil);
DRIVER_TYPES: array[-1..high(DRIVER_NAMES) - 1] of TSqlDBDefinition = (
dDefault,
dMSSQL, // 'SQLSRV'
dMSSQL, // 'LIBTDSODBC'
dMSSQL, // 'IVSS'
dMSSQL, // 'IVMSSS'
dMSSQL, // 'PBSS'
dDB2, // 'DB2CLI'
dDB2, // 'LIBDB2'
dDB2, // 'IVDB2'
dDB2, // 'PBDB2'
dDB2, // 'MSDB2'
dDB2, // 'CWBODBC'
dMySQL, // 'MYODBC'
dMariaDB, // 'MARIA'
dOracle, // 'SQORA'
dOracle, // 'MSORCL'
dOracle, // 'PBOR'
dOracle, // 'IVOR'
dFirebird, // 'ODBCFB'
dFirebird, // 'IB'
dSQLite, // 'SQLITE'
dPostgreSQL, // 'PSQLODBC'
dNexusDB, // 'NXODBCDRIVER'
dInformix); // 'ICLIT09B'
DRIVERCOMPLETION: array[boolean] of SqlUSmallint = (
SQL_DRIVER_NOPROMPT,
SQL_DRIVER_PROMPT);
procedure TSqlDBOdbcConnection.Connect;
var
Log: ISynLog;
Len: SqlSmallint;
begin
SynDBLog.EnterLocal(Log, self, 'Connect');
Disconnect; // force fDbc=nil
if fEnv = nil then
if (ODBC = nil) or
(ODBC.AllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, fEnv) = SQL_ERROR) then
EOdbcException.RaiseUtf8('%: Unable to allocate an environment handle', [self]);
with ODBC do
try
// connect
Check(self, nil,
SetEnvAttr(fEnv, SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC3, 0),
SQL_HANDLE_ENV, fEnv);
Check(self, nil,
AllocHandle(SQL_HANDLE_DBC, fEnv, fDbc),
SQL_HANDLE_ENV, fEnv);
with fOdbcProperties do
if fServerName <> '' then
Check(self, nil,
ConnectA(fDbc, pointer(fServerName), length(fServerName),
pointer(fUserID), length(fUserID), pointer(fPassWord), length(fPassWord)),
SQL_HANDLE_DBC, fDbc)
else if fDatabaseName = '' then
EOdbcException.RaiseU(
'Missing ServerName=DataSourceName or DataBaseName=FullConnectString')
else
begin
FastSetString(fSqlDriverFullString, 1024);
fSqlDriverFullString[1] := #0;
Len := 0;
Check(self, nil,
SqlDriverConnectA(fDbc, GetDesktopWindow, pointer(fDatabaseName),
length(fDatabaseName), pointer(fSqlDriverFullString), length(fSqlDriverFullString),
Len, DRIVERCOMPLETION[fOdbcProperties.fSqlDriverConnectPrompt]),
SQL_HANDLE_DBC, fDbc);
SetLength(fSqlDriverFullString, Len);
end;
// retrieve information of the just created connection
GetInfoString(fDbc, SQL_DRIVER_NAME, fDriverName);
GetInfoString(fDbc, SQL_DBMS_NAME, fDbmsName);
GetInfoString(fDbc, SQL_DBMS_VER, fDbmsVersion);
// guess DBMS type from driver name or DBMS name
if fOdbcProperties.fDbms > dDefault then
fDbms := fOdbcProperties.fDbms // has been forced in Properties
else
begin
fDbms := DRIVER_TYPES[IdemPPChar(pointer(fDriverName), @DRIVER_NAMES)];
if fDbms = dDefault then
fDbms := DBMS_TYPES[IdemPPChar(pointer(fDbmsName), @DBMS_NAMES)];
if fDbms = dDefault then
EOdbcException.RaiseUtf8(
'%.Connect: unrecognized provider DbmsName=% DriverName=% DbmsVersion=%',
[self, DbmsName, DriverName, DbmsVersion]);
end;
if Log <> nil then
Log.Log(sllDebug, 'Connected to % using % % recognized as %',
[DbmsName, DriverName, DbmsVersion, ToText(fDbms)^]);
// notify any re-connection
inherited Connect;
except
on E: Exception do
begin
self.Disconnect; // clean up on fail
raise;
end;
end;
end;
constructor TSqlDBOdbcConnection.Create(aProperties: TSqlDBConnectionProperties);
var
{%H-}Log: ISynLog;
begin
SynDBLog.EnterLocal(Log, self, 'Create');
if not aProperties.InheritsFrom(TSqlDBOdbcConnectionProperties) then
EOdbcException.RaiseUtf8('Invalid %.Create(%)', [self, aProperties]);
fOdbcProperties := TSqlDBOdbcConnectionProperties(aProperties);
inherited Create(aProperties);
end;
destructor TSqlDBOdbcConnection.Destroy;
begin
inherited Destroy;
if (ODBC <> nil) and
(fEnv <> nil) then
ODBC.FreeHandle(SQL_HANDLE_ENV, fEnv);
end;
procedure TSqlDBOdbcConnection.Disconnect;
var
{%H-}log: ISynLog;
begin
try
inherited Disconnect; // flush any cached statement
finally
if (ODBC <> nil) and
(fDbc <> nil) then
with ODBC do
begin
SynDBLog.EnterLocal(log, self, 'Disconnect');
Disconnect(fDbc);
FreeHandle(SQL_HANDLE_DBC, fDbc);
fDbc := nil;
end;
end;
end;
function TSqlDBOdbcConnection.IsConnected: boolean;
begin
result := fDbc <> nil;
end;
function TSqlDBOdbcConnection.NewStatement: TSqlDBStatement;
begin
result := TSqlDBOdbcStatement.Create(self);
end;
procedure TSqlDBOdbcConnection.Commit;
begin
inherited Commit; // dec(fTransactionCount)
with ODBC do
try
Check(self, nil,
EndTran(SQL_HANDLE_DBC, fDbc, SQL_COMMIT),
SQL_HANDLE_DBC, fDbc);
Check(self, nil,
SetConnectAttrW(fDbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_ON, 0),
SQL_HANDLE_DBC, fDbc); // back to default AUTO COMMIT ON mode
except
inc(fTransactionCount); // the transaction is still active
raise;
end;
end;
procedure TSqlDBOdbcConnection.Rollback;
begin
inherited RollBack;
with ODBC do
begin
Check(self, nil,
EndTran(SQL_HANDLE_DBC, fDbc, SQL_ROLLBACK),
SQL_HANDLE_DBC, fDbc);
Check(self, nil,
SetConnectAttrW(fDbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_ON, 0),
SQL_HANDLE_DBC, fDbc); // back to default AUTO COMMIT ON mode
end;
end;
procedure TSqlDBOdbcConnection.StartTransaction;
var
{%H-}log: ISynLog;
begin
SynDBLog.EnterLocal(log, self, 'StartTransaction');
if TransactionCount > 0 then
EOdbcException.RaiseUtf8('% do not support nested transactions', [self]);
inherited StartTransaction;
ODBC.Check(self, nil,
ODBC.SetConnectAttrW(fDbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0),
SQL_HANDLE_DBC, fDbc);
end;
{ TSqlDBOdbcStatement }
procedure TSqlDBOdbcStatement.AllocStatement;
var
hDbc: SqlHDbc;
begin
if fStatement <> nil then
EOdbcException.RaiseUtf8('%.AllocStatement called twice', [self]);
fCurrentRow := 0;
fTotalRowsRetrieved := 0;
if not fConnection.Connected then
fConnection.Connect;
hDbc := (fConnection as TSqlDBOdbcConnection).fDbc;
with ODBC do
Check(nil, self,
AllocHandle(SQL_HANDLE_STMT, hDbc, fStatement),
SQL_HANDLE_DBC, hDbc);
end;
procedure TSqlDBOdbcStatement.DeallocStatement;
begin
if fStatement <> nil then
// avoid Informix exception and log exception race condition
try
try
ODBC.Check(nil, self,
ODBC.FreeHandle(SQL_HANDLE_STMT, fStatement),
SQL_HANDLE_DBC, (fConnection as TSqlDBOdbcConnection).fDbc);
except
end;
finally
fStatement := Nil;
end;
end;
function ODBCColumnToFieldType(DataType, ColumnPrecision, ColumnScale: integer):
TSqlDBFieldType;
begin
// ftUnknown, ftNull, ftInt64, ftDouble, ftCurrency, ftDate, ftUtf8, ftBlob
case DataType of
SQL_DECIMAL,
SQL_NUMERIC,
SQL_FLOAT:
begin
result := ftDouble;
if ColumnPrecision = 10 then
case ColumnScale of
0:
result := ftInt64;
1..4:
result := ftCurrency;
end;
end;
SQL_REAL,
SQL_DOUBLE:
result := ftDouble;
SQL_SMALLINT,
SQL_INTEGER,
SQL_TINYINT,
SQL_BIT,
SQL_BIGINT:
result := ftInt64;
SQL_BINARY,
SQL_VARBINARY,
SQL_LONGVARBINARY:
result := ftBlob;
SQL_TIME,
SQL_DATETIME,
SQL_TYPE_DATE,
SQL_TYPE_TIME,
SQL_TYPE_TIMESTAMP:
result := ftDate;
else // all other types will be converted to text
result := ftUtf8;
end;
end;
const
/// internal mapping to handled GetData() type for Column*() methods
// - numerical values (integer or floating-point) are converted to SQL_C_CHAR
// - date/time to SQL_C_TYPE_TIMESTAMP object
// - text columns to SQL_C_WCHAR (for proper UTF-8 data retrieval)
// - BLOB columns to SQL_C_BINARY
ODBC_TYPE_TOC: array[TSqlDBFieldType] of ShortInt = (
SQL_C_CHAR, // ftUnknown
SQL_C_CHAR, // ftNull
SQL_C_CHAR, // ftInt64
SQL_C_CHAR, // ftDouble
SQL_C_CHAR, // ftCurrency
SQL_C_TYPE_TIMESTAMP, // ftDate
SQL_C_WCHAR, // ftUtf8
SQL_C_BINARY); // ftBlob
procedure TSqlDBOdbcStatement.BindColumns;
var
p: PSqlDBColumnProperty;
nCols, NameLength, DataType, DecimalDigits, Nullable: SqlSmallint;
ColumnSize: SqlULen;
c, siz: integer;
Name: TByteToWideChar;
begin
ReleaseRows;
with ODBC do
begin
Check(nil, self,
NumResultCols(fStatement, nCols),
SQL_HANDLE_STMT, fStatement);
SetLength(fColData, nCols);
fColumn.Capacity := nCols;
for c := 1 to nCols do
begin
Check(nil, self,
DescribeColW(fStatement, c, Name{%H-}, 256, NameLength, DataType,
ColumnSize, DecimalDigits, Nullable),
SQL_HANDLE_STMT, fStatement);
p := AddColumn(RawUnicodeToUtf8(Name, NameLength));
p^.ColumnValueInlined := true;
p^.ColumnValueDBType := DataType;
if ColumnSize > 65535 then
ColumnSize := 0; // avoid out of memory error for BLOBs
p^.ColumnValueDBSize := ColumnSize;
p^.ColumnNonNullable := (Nullable = SQL_NO_NULLS);
p^.ColumnType := ODBCColumnToFieldType(DataType, 10, DecimalDigits);
if p^.ColumnType = ftUtf8 then
if ColumnSize = 0 then
siz := 256
else
siz := ColumnSize * 2 + 16
else // guess max size as WideChar buffer
siz := ColumnSize;
if siz < 64 then
siz := 64; // ODBC never truncates fixed-length data: ensure minimum
if siz > Length(fColData[c - 1]) then
SetLength(fColData[c - 1], siz);
end;
assert(fColumnCount = nCols);
end;
end;
procedure TSqlDBOdbcStatement.GetData(var Col: TSqlDBColumnProperty; ColIndex: integer);
var
ExpectedDataType: ShortInt;
ExpectedDataLen: integer;
Status: SqlReturn;
Indicator: SqlLen;
P: PAnsiChar;
function IsTruncated: boolean;
begin
result := (Indicator > 0) and
(ODBC.GetDiagField(fStatement) = '01004');
end;
procedure CheckStatus;
begin
if Status <> SQL_SUCCESS then
ODBC.HandleError(nil, self, Status, SQL_HANDLE_STMT, fStatement, false, sllNone);
end;
procedure RaiseError;
begin
EOdbcException.RaiseUtf8('%.GetCol: [%] column had Indicator=%',
[self, Col.ColumnName, Indicator]);
end;
begin
ExpectedDataType := ODBC_TYPE_TOC[Col.ColumnType];
ExpectedDataLen := length(fColData[ColIndex]);
//FillcharFast(pointer(fColData[ColIndex])^,ExpectedDataLen,ord('~'));
Status := ODBC.GetData(fStatement, ColIndex + 1, ExpectedDataType,
pointer(fColData[ColIndex]), ExpectedDataLen, @Indicator);
Col.ColumnDataSize := Indicator;
if Status <> SQL_SUCCESS then
if Status = SQL_SUCCESS_WITH_INFO then
if Col.ColumnType in FIXEDLENGTH_SQLDBFIELDTYPE then
Status := SQL_SUCCESS
else // allow rounding problem
if IsTruncated then
begin
if Col.ColumnType <> ftBlob then
begin
dec(ExpectedDataLen, SizeOf(WideChar)); // ignore null termination
inc(Indicator, SizeOf(WideChar)); // always space for additional #0
end;
SetLength(fColData[ColIndex], Indicator);
P := pointer(fColData[ColIndex]);
inc(P, ExpectedDataLen);
ExpectedDataLen := Indicator - ExpectedDataLen;
//FillcharFast(P^,ExpectedDataLen,ord('~'));
Status := ODBC.GetData(fStatement, ColIndex + 1, ExpectedDataType, P,
ExpectedDataLen, @Indicator);
CheckStatus;
end
else
CheckStatus
else
CheckStatus;
if Indicator >= 0 then
case Status of
SQL_SUCCESS,
SQL_NO_DATA:
Col.ColumnDataState := colDataFilled;
else
RaiseError;
end
else
case Indicator of
SQL_NULL_DATA:
Col.ColumnDataState := colNull;
SQL_NO_TOTAL:
if Col.ColumnType in FIXEDLENGTH_SQLDBFIELDTYPE then
Col.ColumnDataState := colDataFilled
else
EOdbcException.RaiseUtf8('%.GetCol: SQL_NO_TOTAL [%] % column has no size',
[self, Col.ColumnName, ToText(Col.ColumnType)^]);
else
RaiseError;
end;
end;
function TSqlDBOdbcStatement.GetCol(Col: integer;
ExpectedType: TSqlDBFieldType): TSqlDBStatementGetCol;
var
c: integer;
begin
// colNull, colWrongType, colTmpUsed, colTmpUsedTruncated
CheckCol(Col); // check Col<fColumnCount
if (not Assigned(fStatement)) or
(fColData = nil) then
EOdbcException.RaiseUtf8('%.Column*() with no prior Execute', [self]);
// get all fColData[] (driver may be without SQL_GD_ANY_ORDER)
for c := 0 to fColumnCount - 1 do
if fColumns[c].ColumnDataState = colNone then
GetData(fColumns[c], c);
// retrieve information for the specified column
if (ExpectedType = ftNull) or
(fColumns[Col].ColumnType = ExpectedType) or
(fColumns[Col].ColumnDataState = colNull) then
result := fColumns[Col].ColumnDataState
else
result := colWrongType;
end;
function TSqlDBOdbcStatement.MoreResults: boolean;
var
R: SqlReturn;
begin
R := ODBC.MoreResults(fStatement);
case R of
SQL_NO_DATA:
result := false; // no more results
SQL_SUCCESS,
SQL_SUCCESS_WITH_INFO:
result := true; // got next
else
begin
ODBC.Check(nil, self, R, SQL_HANDLE_STMT, fStatement); // error
result := false; // makes compiler happy
end;
end;
end;
function TSqlDBOdbcStatement.ColumnBlob(Col: integer): RawByteString;
var
res: TSqlDBStatementGetCol;
begin
res := GetCol(Col, ftBlob);
case res of
colNull:
result := '';
colWrongType:
ColumnToTypedValue(Col, ftBlob, result);
else
result := copy(fColData[Col], 1, fColumns[Col].ColumnDataSize);
end;
end;
function TSqlDBOdbcStatement.ColumnUtf8(Col: integer): RawUtf8;
var
res: TSqlDBStatementGetCol;
begin
res := GetCol(Col, ftUtf8);
case res of
colNull:
result := '';
colWrongType:
ColumnToTypedValue(Col, ftUtf8, result);
else
RawUnicodeToUtf8(
pointer(fColData[Col]), fColumns[Col].ColumnDataSize shr 1, result);
end;
end;
function TSqlDBOdbcStatement.ColumnCurrency(Col: integer): currency;
begin
case GetCol(Col, ftCurrency) of
colNull:
result := 0;
colWrongType:
ColumnToTypedValue(Col, ftCurrency, result);
else
PInt64(@result)^ := StrToCurr64(pointer(fColData[Col])); // as SQL_C_CHAR
end;
end;
function TSqlDBOdbcStatement.ColumnDateTime(Col: integer): TDateTime;
begin
case GetCol(Col, ftDate) of
colNull:
result := 0;
colWrongType:
ColumnToTypedValue(Col, ftDate, result);
else
result := PSql_TIMESTAMP_STRUCT(pointer(fColData[Col]))^.ToDateTime(
fColumns[Col].ColumnValueDBType);
end;
end;
function TSqlDBOdbcStatement.ColumnDouble(Col: integer): double;
begin
case GetCol(Col, ftDouble) of
colNull:
result := 0;
colWrongType:
ColumnToTypedValue(Col, ftDouble, result);
else
result := GetExtended(pointer(fColData[Col])); // encoded as SQL_C_CHAR
end;
end;
function TSqlDBOdbcStatement.ColumnInt(Col: integer): Int64;
begin
case GetCol(Col, ftInt64) of
colNull:
result := 0;
colWrongType:
ColumnToTypedValue(Col, ftInt64, result);
else
SetInt64(pointer(fColData[Col]), result); // encoded as SQL_C_CHAR
end;
end;
function TSqlDBOdbcStatement.ColumnNull(Col: integer): boolean;
begin
// will check for NULL but never returns colWrongType
result := GetCol(Col, ftNull) = colNull;
end;
procedure TSqlDBOdbcStatement.ColumnToJson(Col: integer; W: TJsonWriter);
var
p: PSqlDBColumnProperty;
v: pointer;
tmp: array[0..31] of AnsiChar;
begin
if (not Assigned(fStatement)) or
(CurrentRow <= 0) then
EOdbcException.RaiseUtf8('%.ColumnToJson() with no prior Step', [self]);
p := @fColumns[Col];
if GetCol(Col, p^.ColumnType) = colNull then
begin
W.AddNull;
exit;
end;
v := pointer(fColData[Col]);
case p^.ColumnType of
ftInt64: // stored as SQL_C_CHAR
W.AddNoJsonEscape(v, p^.ColumnDataSize);
ftDouble,
ftCurrency: // stored as SQL_C_CHAR
W.AddFloatStr(v, p^.ColumnDataSize);
ftDate:
W.AddShort(@tmp, PSql_TIMESTAMP_STRUCT(v)^.
ToIso8601(tmp{%H-}, p^.ColumnValueDBType, dsfForceDateWithMS in fFlags));
ftUtf8: // stored as SQL_C_WCHAR
begin
W.Add('"');
if p^.ColumnDataSize > 1 then
W.AddJsonEscapeW(v, p^.ColumnDataSize shr 1);
W.AddDirect('"');
end;
ftBlob:
if dsfForceBlobAsNull in fFlags then
W.AddNull
else
W.WrBase64(v, p^.ColumnDataSize, true);
else
ESqlDBException.RaiseUtf8('%: Invalid ColumnType(%)=%',
[self, Col, ord(p^.ColumnType)]);
end;
end;
constructor TSqlDBOdbcStatement.Create(aConnection: TSqlDBConnection);
begin
if not aConnection.InheritsFrom(TSqlDBOdbcConnection) then
EOdbcException.RaiseUtf8('%.Create(%)', [self, aConnection]);
inherited Create(aConnection);
end;
destructor TSqlDBOdbcStatement.Destroy;
begin
try
DeallocStatement;
finally
inherited Destroy;
end;
end;
const
NULWCHAR: WideChar = #0;
ODBC_IOTYPE_TO_PARAM: array[TSqlDBParamInOutType] of ShortInt = (
SQL_PARAM_INPUT, // paramIn
SQL_PARAM_OUTPUT, // paramOut
SQL_PARAM_INPUT_OUTPUT); // paramInOut
IDList_type: PWideChar = 'IDList';
StrList_type: PWideChar = 'StrList';
function TSqlDBOdbcStatement.CType2SQL(CDataType: integer): integer;
begin
case CDataType of
SQL_C_CHAR:
case fDbms of
dInformix:
result := SQL_INTEGER;
else
result := SQL_VARCHAR;
end;
SQL_C_TYPE_DATE:
result := SQL_TYPE_DATE;
SQL_C_TYPE_TIMESTAMP:
result := SQL_TYPE_TIMESTAMP;
SQL_C_WCHAR:
case fDbms of
dInformix:
result := SQL_VARCHAR;
else
result := SQL_WVARCHAR;
end;
SQL_C_BINARY:
result := SQL_VARBINARY;
SQL_C_SBIGINT:
result := SQL_BIGINT;
SQL_C_DOUBLE:
result := SQL_DOUBLE;
else
raise EOdbcException.CreateUtf8(
'%.ExecutePrepared: Unexpected ODBC C type %', [self, CDataType]);
end;
end;
procedure TSqlDBOdbcStatement.ExecutePrepared;
var
p, k: integer;
status: SqlReturn;
InputOutputType, CValueType, ParameterType, DecimalDigits: SqlSmallint;
ColumnSize: SqlULen;
ParameterValue: SqlPointer;
ItemSize, BufferSize: SqlLen;
ItemPW: PWideChar;
timestamp: SQL_TIMESTAMP_STRUCT;
ansitext: boolean;
tmp: RawUtf8;
StrLen_or_Ind: array of PtrInt;
ArrayData: array of record
StrLen_or_Ind: array of PtrInt;
WData: RawByteString; // as UTF-16 buffer
end;
label
retry;
begin
SqlLogBegin(sllSQL);