forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmormot.db.sql.oledb.pas
2509 lines (2330 loc) · 89.8 KB
/
mormot.db.sql.oledb.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 Direct OleDB 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.oledb;
{
*****************************************************************************
Efficient SQL Database Connection via OleDB
- Some Low-Level OleDB / ORM Constants
- TSqlDBOleDBConnection* and TSqlDBOleDBStatement Classes
- Database Engine Specific OleDB Connection Classes
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
{$ifdef OSWINDOWS} // compiles as void unit for non-Windows - allow Lazarus package
uses
sysutils,
classes,
variants,
Windows, // OleDB is a Windows-specific protocol
ActiveX,
ComObj,
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.buffers,
mormot.core.datetime,
mormot.core.data,
mormot.core.rtti,
mormot.core.json,
mormot.core.perf,
mormot.core.log,
mormot.db.core,
mormot.db.sql,
mormot.db.raw.oledb;
{ ************ Some Low-Level OleDB / ORM Constants }
const
PARAMTYPE2OLEDB: array[TSqlDBParamInOutType] of DBPARAMIO = (
DBPARAMIO_INPUT, // paramIn
DBPARAMIO_OUTPUT, // paramOut
DBPARAMIO_INPUT or DBPARAMIO_OUTPUT); // paramInOut
FIELDTYPE2OLEDB: array[TSqlDBFieldType] of DBTYPE = (
DBTYPE_EMPTY, // ftUnknown
DBTYPE_I4, // ftNull
DBTYPE_I8, // ftInt64
DBTYPE_R8, // ftDouble
DBTYPE_CY, // ftCurrency
DBTYPE_DATE, // ftDate
DBTYPE_WSTR or DBTYPE_BYREF, // ftUtf8
DBTYPE_BYTES or DBTYPE_BYREF); // ftBlob
FIELDTYPE2OLEDBTYPE_NAME: array[TSqlDBFieldType] of WideString = (
'', // ftUnknown
'DBTYPE_I4', // ftNull
'DBTYPE_I8', // ftInt64
'DBTYPE_R8', // ftDouble
'DBTYPE_CY', // ftCurrency
'DBTYPE_DATE', // ftDate
'DBTYPE_WVARCHAR', // ftUtf8
'DBTYPE_BINARY'); // ftBlob
{ ************ TSqlDBOleDBConnection* and TSqlDBOleDBStatement Classes }
type
TSqlDBOleDBConnection = class;
TSqlDBOleDBOnCustomError = function(Connection: TSqlDBOleDBConnection;
ErrorRecords: IErrorRecords; RecordNum: cardinal): boolean of object;
/// will implement properties shared by OleDB connections
TSqlDBOleDBConnectionProperties = class(TSqlDBConnectionPropertiesThreadSafe)
protected
fProviderName: RawUtf8;
fConnectionString: SynUnicode;
fOnCustomError: TSqlDBOleDBOnCustomError;
fSchemaRec: array of TDBSchemaRec;
fSupportsOnlyIRowset: boolean;
function GetSchema(const aUid: TGuid; const Fields: array of RawUtf8;
var aResult: IRowSet): boolean;
/// will create the generic fConnectionString from supplied parameters
procedure SetInternalProperties; override;
/// initialize fForeignKeys content with all foreign keys of this DB
// - used by GetForeignKey method
procedure GetForeignKeys; override;
/// create the database
// - shall be called only if necessary (e.g. for file-based database, if
// the file does not exist yet)
function CreateDatabase: boolean; virtual;
public
/// 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 TSqlDBOleDBConnection instance
function NewConnection: TSqlDBConnection; override;
/// display the OleDB/ADO Connection Settings dialog to customize the
// OleDB connection string
// - returns TRUE if the connection string has been modified
// - Parent is an optional GDI Window Handle for modal display
function ConnectionStringDialogExecute(Parent: HWND = 0): boolean;
/// get all table names
// - will retrieve the corresponding metadata from OleDB interfaces if SQL
// direct access was not defined
procedure GetTableNames(out Tables: TRawUtf8DynArray); override;
/// retrieve the column/field layout of a specified table
// - will retrieve the corresponding metadata from OleDB interfaces if SQL
// direct access was not defined
procedure GetFields(const aTableName: RawUtf8; out Fields: TSqlDBColumnDefineDynArray); override;
/// convert a textual column data type, as retrieved e.g. from SqlGetField,
// into our internal primitive types
function ColumnTypeNativeToDB(const aNativeType: RawUtf8; aScale: integer): TSqlDBFieldType; override;
/// the associated OleDB connection string
// - is set by the Create() constructor most of the time from the supplied
// server name, user id and password, according to the database provider
// corresponding to the class
// - you may want to customize it via the ConnectionStringDialogExecute
// method, or to provide some additional parameters
property ConnectionString: SynUnicode
read fConnectionString write fConnectionString;
/// custom Error handler for OleDB COM objects
// - returns TRUE if specific error was retrieved and has updated
// ErrorMessage and InfoMessage
// - default implementation just returns false
property OnCustomError: TSqlDBOleDBOnCustomError
read fOnCustomError write fOnCustomError;
published { to be loggged as JSON }
/// the associated OleDB provider name, as set for each class
property ProviderName: RawUtf8
read fProviderName;
end;
/// implements an OleDB connection
// - will retrieve the remote DataBase behavior from a supplied
// TSqlDBConnectionProperties class, shared among connections
TSqlDBOleDBConnection = class(TSqlDBConnectionThreadSafe)
protected
fMalloc: IMalloc;
fDBInitialize: IDBInitialize;
fTransaction: ITransactionLocal;
fSession: IUnknown;
fOleDBProperties: TSqlDBOleDBConnectionProperties;
fOleDBErrorMessage, fOleDBInfoMessage: string;
/// Error handler for OleDB COM objects
// - will update ErrorMessage and InfoMessage
procedure OleDBCheck(aStmt: TSqlDBStatement; aResult: HRESULT;
const aStatus: TCardinalDynArray = nil); virtual;
/// called just after fDBInitialize.Initialized: could add parameters
procedure OnDBInitialized; virtual;
public
/// connect to a specified OleDB database
constructor Create(aProperties: TSqlDBConnectionProperties); override;
/// release all associated memory and OleDB COM objects
destructor Destroy; override;
/// initialize a new SQL query statement for the given connection
// - the caller should free the instance after use
function NewStatement: TSqlDBStatement; override;
/// connect to the specified database
// - should raise an EOleDBException on error
procedure Connect; override;
/// stop connection to the specified database
// - should raise an EOleDBException on error
procedure Disconnect; override;
/// return TRUE if Connect has been already successfully called
function IsConnected: boolean; override;
/// begin a Transaction for this connection
// - be aware that not all OleDB provider support nested transactions
// see http://msdn.microsoft.com/en-us/library/ms716985(v=vs.85).aspx
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 associated OleDB database properties
property OleDBProperties: TSqlDBOleDBConnectionProperties
read fOleDBProperties;
/// internal error message, as retrieved from the OleDB provider
property OleDBErrorMessage: string
read fOleDBErrorMessage;
/// internal information message, as retrieved from the OleDB provider
property OleDBInfoMessage: string
read fOleDBInfoMessage;
end;
/// used to store properties and value about one TSqlDBOleDBStatement Param
// - we don't use a Variant, not the standard TSqlDBParam record type,
// but manual storage for better performance
// - whole memory block of a TSqlDBOleDBStatementParamDynArray will be used as
// the source Data for the OleDB parameters - so we should align data carefully
{$ifdef CPU64}
{$A8} // un-packed records
{$else}
{$A-} // packed records
{$endif CPU64}
TSqlDBOleDBStatementParam = record
/// storage used for BLOB (ftBlob) values
// - will be refered as DBTYPE_BYREF when sent as OleDB parameters, to
// avoid unnecessary memory copy
VBlob: RawByteString;
/// storage used for TEXT (ftUtf8) values
// - we store TEXT here as WideString, and not RawUtf8, since OleDB
// expects the text to be provided with Unicode encoding
// - for some providers (like Microsoft SQL Server 2008 R2, AFAIK), using
// DBTYPE_WSTR value (i.e. what the doc. says) will raise an OLEDB Error
// 80040E1D (DB_E_UNSUPPORTEDCONVERSION, i.e. 'Requested conversion is not
// supported'): we found out that only DBTYPE_BSTR type (i.e. OLE WideString)
// does work... so we'll use it here! Shame on Microsoft!
// - what's fine with DBTYPE_BSTR is that it can be resized by the provider
// in case of VInOut in [paramOut, paramInOut] - so let it be
VText: WideString;
/// storage used for ftInt64, ftDouble, ftDate and ftCurrency value
VInt64: Int64;
/// storage used for table variables
VIUnknown: IUnknown;
/// storage used for table variables
VArray: TRawUtf8DynArray;
/// storage used for the OleDB status field
// - if VStatus=ord(stIsNull), then it will bind a NULL with the type
// as set by VType (to avoid conversion error like in [e8c211062e])
VStatus: integer;
/// the column/parameter Value type
VType: TSqlDBFieldType;
/// define if parameter can be retrieved after a stored procedure execution
VInOut: TSqlDBParamInOutType;
// so that VInt64 will be 8 bytes aligned
VFill: array[SizeOf(TSqlDBFieldType) + SizeOf(TSqlDBParamInOutType) +
SizeOf(integer).. SizeOf(Int64) - 1] of byte;
end;
{$ifdef CPU64}
{$A-} // packed records
{$endif CPU64}
POleDBStatementParam = ^TSqlDBOleDBStatementParam;
/// used to store properties about TSqlDBOleDBStatement Parameters
// - whole memory block of a TSqlDBOleDBStatementParamDynArray will be used as the
// source Data for the OleDB parameters
TSqlDBOleDBStatementParamDynArray = array of TSqlDBOleDBStatementParam;
/// implements an OleDB SQL query statement
// - this statement won't retrieve all rows of data, but will allow direct
// per-row access using the Step() and Column*() methods
TSqlDBOleDBStatement = class(TSqlDBStatement)
protected
fParams: TSqlDBOleDBStatementParamDynArray;
fColumns: TSqlDBColumnPropertyDynArray;
fParam: TDynArray;
fColumn: TDynArrayHashed;
fCommand: ICommandText;
fRowSet: IRowSet;
fRowSetAccessor: HACCESSOR;
fRowSize: integer;
fRowStepResult: HRESULT;
fRowStepHandleRetrieved: PtrUInt;
fRowStepHandleCurrent: PtrUInt;
fRowStepHandles: TPtrUIntDynArray;
fRowSetData: TBytes;
fParamBindings: TDBBindingDynArray;
fColumnBindings: TDBBindingDynArray;
fHasColumnValueByRef: boolean;
fOleDBConnection: TSqlDBOleDBConnection;
fDBParams: TDBParams;
fRowBufferSize: integer;
fUpdateCount: integer;
fAlignBuffer: boolean;
procedure SetRowBufferSize(Value: integer);
/// resize fParams[] if necessary, set the VType and return pointer to
// the corresponding entry in fParams[]
// - first parameter has Param=1
function CheckParam(Param: integer; NewType: TSqlDBFieldType;
IO: TSqlDBParamInOutType): POleDBStatementParam; overload;
function CheckParam(Param: integer; NewType: TSqlDBFieldType;
IO: TSqlDBParamInOutType; ArrayCount: integer): POleDBStatementParam; overload;
/// raise an exception if Col is incorrect or no IRowSet is available
// - set Column to the corresponding fColumns[] item
// - return a pointer to status-data[-length] in fRowSetData[], or
// nil if status states this column is NULL
function GetCol(Col: integer; out Column: PSqlDBColumnProperty): pointer;
procedure GetCol64(Col: integer; DestType: TSqlDBFieldType; var Dest);
{$ifdef HASINLINE}inline;{$endif}
procedure FlushRowSetData;
procedure ReleaseRowSetDataAndRows;
procedure CloseRowSet;
/// retrieve column information, and initialize Bindings[]
// - add the high-level column information in Column[], initializes
// OleDB Bindings array and returns the row size (in bytes)
function BindColumns(ColumnInfo: IColumnsInfo; var Column: TDynArrayHashed;
out Bindings: TDBBindingDynArray): integer;
procedure LogStatusError(Status: integer; Column: PSqlDBColumnProperty);
public
/// create an OleDB statement instance, from an OleDB connection
// - the Execute method can be called only once per TSqlDBOleDBStatement instance
// - if the supplied connection is not of TSqlDBOleDBConnection type, will raise
// an exception
constructor Create(aConnection: TSqlDBConnection); override;
/// release all associated memory and COM objects
destructor Destroy; override;
/// internal method to retrieve column information from a supplied IRowSet
// - is used e.g. by TSqlDBOleDBStatement.Execute or to retrieve metadata columns
// - raise an exception on error
procedure FromRowSet(RowSet: IRowSet);
/// bind a NULL value to a parameter
// - the leftmost SQL parameter has an index of 1
// - OleDB during MULTI INSERT statements expect BoundType to be set in
// TSqlDBOleDBStatementParam, and its VStatus set to ord(stIsNull)
// - raise an EOleDBException on any error
procedure BindNull(Param: integer; IO: TSqlDBParamInOutType = paramIn;
BoundType: TSqlDBFieldType = ftNull); override;
/// bind an array of Int64 values to a parameter
// - using TABLE variable (MSSQl 2008 & UP). Must be created in the database as:
// $ CREATE TYPE dbo.IDList AS TABLE(id bigint NULL)
// - Internally BindArray(0, [1, 2,3]) is the same as:
// $ declare @a dbo.IDList;
// $ insert into @a (id) values (1), (2), (3);
// $ SELECT usr.ID FROM user usr WHERE usr.ID IN (select id from @a)
procedure BindArray(Param: integer;
const Values: array of Int64); overload; override;
/// bind a array of RawUtf8 (255 length max) values to a parameter
// - using TABLE variable (MSSQl 2008 & UP). Must be created in the database as:
// $ CREATE TYPE dbo.StrList AS TABLE(id nvarchar(255) NULL)
// - must be declareded in the database
procedure BindArray(Param: integer;
const Values: array of RawUtf8); overload; override;
/// bind an integer value to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure Bind(Param: integer; Value: Int64;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a double value to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure Bind(Param: integer; Value: double;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a TDateTime value to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindDateTime(Param: integer; Value: TDateTime;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a currency value to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindCurrency(Param: integer; Value: currency;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a UTF-8 encoded string to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindTextU(Param: integer; const Value: RawUtf8;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a UTF-8 encoded buffer text (#0 ended) to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindTextP(Param: integer; Value: PUtf8Char;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a RTL string to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindTextS(Param: integer; const Value: string;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind an OLE WideString to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindTextW(Param: integer; const Value: WideString;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a Blob buffer to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindBlob(Param: integer; Data: pointer; Size: integer;
IO: TSqlDBParamInOutType = paramIn); overload; override;
/// bind a Blob buffer to a parameter
// - the leftmost SQL parameter has an index of 1
// - raise an EOleDBException on any error
procedure BindBlob(Param: integer; const Data: RawByteString;
IO: TSqlDBParamInOutType = paramIn); overload; 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 EOleDBException on any error
procedure Prepare(const aSql: RawUtf8;
ExpectResults: boolean = false); overload; override;
/// Execute an UTF-8 encoded SQL statement
// - parameters marked as ? should have been already bound with Bind*()
// functions above
// - raise an EOleDBException on any error
procedure ExecutePrepared; override;
/// Reset the previous prepared statement
// - this overridden implementation will reset all bindings and the cursor state
// - raise an EOleDBException on any error
procedure Reset; override;
/// gets a number of updates made by latest executed statement
function UpdateCount: integer; override;
/// retrieve the parameter content, after SQL execution
// - the leftmost SQL parameter has an index of 1
// - to be used e.g. with stored procedures
// - any TEXT parameter will be retrieved as WideString Variant (i.e. as
// stored in TSqlDBOleDBStatementParam)
function ParamToVariant(Param: integer; var Value: Variant;
CheckIsOutParameter: boolean = true): TSqlDBFieldType; 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 EOleDBException on any error
function Step(SeekFirst: boolean = false): boolean; override;
/// clear result rowset when ISqlDBStatement is back in cache
procedure ReleaseRows; override;
/// retrieve a column name of the current Row
// - Columns numeration (i.e. Col value) starts with 0
// - it's up to the implementation to ensure than all column names are unique
function ColumnName(Col: integer): RawUtf8; override;
/// returns the Column index of a given Column name
// - Columns numeration (i.e. Col value) starts with 0
// - returns -1 if the Column name is not found (via case insensitive search)
function ColumnIndex(const aColumnName: RawUtf8): integer; override;
/// the Column type of the current Row
// - ftCurrency type should be handled specificaly, for faster process and
// avoid any rounding issue, since currency is a standard OleDB type
// - FieldSize can be set to store the size in chars of a ftUtf8 column
// (0 means BLOB kind of TEXT column)
function ColumnType(Col: integer;
FieldSize: PInteger = nil): TSqlDBFieldType; 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 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
// - 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 text RTL string value of the current Row, first Col is 0
function ColumnString(Col: integer): string; 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;
/// return a Column as a variant
// - this implementation will retrieve the data with no temporary variable
// (since TQuery calls this method a lot, we tried to optimize it)
// - a ftUtf8 content will be mapped into a generic WideString variant
// for pre-Unicode version of Delphi, and a generic UnicodeString (=string)
// since Delphi 2009: you may not loose any data during charset conversion
// - a ftBlob content will be mapped into a TBlobData AnsiString variant
function ColumnToVariant(
Col: integer; var Value: Variant): TSqlDBFieldType; override;
/// just map the original Collection into a TSqlDBOleDBConnection class
property OleDBConnection: TSqlDBOleDBConnection
read fOleDBConnection;
/// if TRUE, the data will be 8 bytes aligned in OleDB internal buffers
// - it's recommended by official OleDB documentation for faster process
// - is enabled by default, and should not be modified in most cases
property AlignDataInternalBuffer: boolean
read fAlignBuffer write fAlignBuffer;
/// size in bytes of the internal OleDB buffer used to fetch rows
// - several rows are retrieved at once into the internal buffer
// - default value is 16384 bytes, minimal allowed size is 8192
property RowBufferSize: integer
read fRowBufferSize write SetRowBufferSize;
/// direct access to the columns description
// - gives more details than the default ColumnType() function
property Columns: TSqlDBColumnPropertyDynArray
read fColumns;
end;
{ ************ Database Engine Specific OleDB Connection Classes }
type
/// OleDB connection properties to an Oracle database using Oracle's Provider
// - this will use the native OleDB provider supplied by Oracle
// see @http://download.oracle.com/docs/cd/E11882_01/win.112/e17726/toc.htm
TSqlDBOleDBOracleConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'OraOLEDB.Oracle.1'
procedure SetInternalProperties; override;
end;
/// OleDB connection properties to an Oracle database using Microsoft's Provider
// - this will use the generic (older) OleDB provider supplied by Microsoft
// which would not be used any more:
// "This feature will be removed in a future version of Windows. Avoid
// using this feature in new development work, and plan to modify applications
// that currently use this feature. Instead, use Oracle's OLE DB provider."
// see http://msdn.microsoft.com/en-us/library/ms675851
TSqlDBOleDBMSOracleConnectionProperties = class(TSqlDBOleDBOracleConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'MSDAORA'
procedure SetInternalProperties; override;
end;
/// OleDB connection properties to Microsoft SQL Server 2008-2012, via
// SQL Server Native Client 10.0 (SQL Server 2008)
// - this will use the native OleDB provider supplied by Microsoft
// see http://msdn.microsoft.com/en-us/library/ms677227
// - is aUserID='' at Create, it will use Windows Integrated Security
// for the connection
// - will use the SQLNCLI10 provider, which will work on Windows XP;
// if you want all features, especially under MS SQL 2012, use the
// inherited class TSqlDBOleDBMSSQL2012ConnectionProperties; if, on the other
// hand, you need to connect to a old MS SQL Server 2005, use
// TSqlDBOleDBMSSQL2005ConnectionProperties, or set your own provider string
TSqlDBOleDBMSSQLConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'SQLNCLI10'
procedure SetInternalProperties; override;
/// custom Error handler for OleDB COM objects
// - will handle Microsoft SQL Server error messages (if any)
function MSOnCustomError(Connection: TSqlDBOleDBConnection;
ErrorRecords: IErrorRecords; RecordNum: cardinal): boolean;
public
end;
/// OleDB connection properties to Microsoft SQL Server 2005, via
// SQL Server Native Client (SQL Server 2005)
// - this overridden version will use the SQLNCLI provider, which is
// deprecated but may be an alternative with MS SQL Server 2005
// - is aUserID='' at Create, it will use Windows Integrated Security
// for the connection
TSqlDBOleDBMSSQL2005ConnectionProperties = class(TSqlDBOleDBMSSQLConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'SQLNCLI'
procedure SetInternalProperties; override;
public
/// initialize the connection properties
// - this overridden version will disable the MultipleValuesInsert()
// optimization as defined in TSqlDBConnectionProperties.Create(),
// since INSERT with multiple VALUES (..),(..),(..) is available only
// since SQL Server 2008
constructor Create(
const aServerName, aDatabaseName, aUserID, aPassWord: RawUtf8); override;
end;
/// OleDB connection properties to Microsoft SQL Server 2008, via
// SQL Server Native Client 10.0 (SQL Server 2008)
// - just maps default TSqlDBOleDBMSSQLConnectionProperties type
TSqlDBOleDBMSSQL2008ConnectionProperties = TSqlDBOleDBMSSQLConnectionProperties;
/// OleDB connection properties to Microsoft SQL Server 2008/2012, via
// SQL Server Native Client 11.0 (Microsoft SQL Server 2012 Native Client)
// - from http://www.microsoft.com/en-us/download/details.aspx?id=29065 get
// the sqlncli.msi package corresponding to your Operating System: note that
// the "X64 Package" will also install the 32-bit version of the client
// - this overridden version will use newer SQLNCLI11 provider, but won't work
// under Windows XP - in this case, it will fall back to SQLNCLI10 - see
// http://msdn.microsoft.com/en-us/library/ms131291
// - if aUserID='' at Create, it will use Windows Integrated Security
// for the connection
// - for SQL Express LocalDB edition, just use aServerName='(localdb)\v11.0'
TSqlDBOleDBMSSQL2012ConnectionProperties = class(TSqlDBOleDBMSSQLConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'SQLNCLI11'
// - will leave older 'SQLNCLI10' on Windows XP
procedure SetInternalProperties; override;
end;
/// OleDB connection properties to Microsoft SQL Server 2012 R2 and later, via
// SQL Server OLE DB driver (Microsoft OLE DB SQL / MSOLEDBSQL)
TSqlDBOleDBMSSQL2018ConnectionProperties = class(TSqlDBOleDBMSSQLConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'MSOLEDBSQL'
procedure SetInternalProperties; override;
end;
/// OleDB connection properties to MySQL Server
TSqlDBOleDBMySQLConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'MySqlProv'
procedure SetInternalProperties; override;
end;
{$ifdef CPU32} // Jet is not available on Win64
/// OleDB connection properties to Jet/MSAccess .mdb files
// - the server name should be the .mdb file name
// - note that the Jet OleDB driver is not available under Win64 platform
TSqlDBOleDBJetConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'Microsoft.Jet.OLEDB.4.0'
procedure SetInternalProperties; override;
end;
{$endif CPU32}
/// OleDB connection properties to Microsoft Access Database
TSqlDBOleDBACEConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'Microsoft.ACE.OLEDB.12.0'
procedure SetInternalProperties; override;
end;
/// OleDB connection properties to IBM AS/400
TSqlDBOleDBAS400ConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'IBMDA400.DataSource.1'
procedure SetInternalProperties; override;
end;
/// OleDB connection properties to Informix Server
TSqlDBOleDBInformixConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
/// will set the appropriate provider name, i.e. 'Ifxoledbc'
procedure SetInternalProperties; override;
end;
/// OleDB connection properties via Microsoft Provider for ODBC
// - this will use the ODBC provider supplied by Microsoft
// see http://msdn.microsoft.com/en-us/library/ms675326(v=VS.85).aspx
// - an ODBC Driver should be specified at creation
// - you should better use direct connection classes, like
// TSqlDBOleDBMSSQLConnectionProperties or TSqlDBOleDBOracleConnectionProperties
// as defined in mormot.db.sql.odbc.pas
TSqlDBOleDBOdbcSQLConnectionProperties = class(TSqlDBOleDBConnectionProperties)
protected
fDriver: RawUtf8;
/// will set the appropriate provider name, i.e. 'MSDASQL'
procedure SetInternalProperties; override;
public
/// initialize the properties
// - an additional parameter is available to set the ODBC driver to use
// - you may also set aDriver='' and modify the connection string directly,
// e.g. adding '{ DSN=name | FileDSN=filename };'
constructor Create(const aDriver, aServerName, aDatabaseName,
aUserID, aPassWord: RawUtf8); reintroduce;
published { to be logged as JSON }
/// the associated ODBC Driver name, as specified at creation
property Driver: RawUtf8
read fDriver;
end;
// backward compatibility types redirections
{$ifndef PUREMORMOT2}
type
TOleDBConnectionProperties = TSqlDBOleDBConnectionProperties;
TOleDBOracleConnectionProperties = TSqlDBOleDBOracleConnectionProperties;
TOleDBMSOracleConnectionProperties = TSqlDBOleDBMSOracleConnectionProperties;
TOleDBMSSQLConnectionProperties = TSqlDBOleDBMSSQLConnectionProperties;
TOleDBMSSQL2005ConnectionProperties = TSqlDBOleDBMSSQL2005ConnectionProperties;
TOleDBMSSQL2008ConnectionProperties = TSqlDBOleDBMSSQL2008ConnectionProperties;
TOleDBMSSQL2012ConnectionProperties = TSqlDBOleDBMSSQL2012ConnectionProperties;
TOleDBMySQLConnectionProperties = TSqlDBOleDBMySQLConnectionProperties;
{$ifdef CPU32} // Jet is not available on Win64
TOleDBJetConnectionProperties = TSqlDBOleDBJetConnectionProperties;
{$endif CPU32}
TOleDBACEConnectionProperties = TSqlDBOleDBACEConnectionProperties;
TOleDBAS400ConnectionProperties = TSqlDBOleDBAS400ConnectionProperties;
TOleDBOdbcSQLConnectionProperties = TSqlDBOleDBOdbcSQLConnectionProperties;
{$endif PUREMORMOT2}
implementation
{ ************ TSqlDBOleDBConnection* and TSqlDBOleDBStatement Classes }
{ TSqlDBOleDBStatement }
procedure TSqlDBOleDBStatement.BindTextU(Param: integer; const Value: RawUtf8;
IO: TSqlDBParamInOutType);
begin
if (Value = '') and
fConnection.Properties.StoreVoidStringAsNull then
CheckParam(Param, ftNull, IO)
else
Utf8ToWideString(Value, CheckParam(Param, ftUtf8, IO)^.VText);
end;
procedure TSqlDBOleDBStatement.BindTextP(Param: integer; Value: PUtf8Char;
IO: TSqlDBParamInOutType);
begin
if (Value = '') and
fConnection.Properties.StoreVoidStringAsNull then
CheckParam(Param, ftNull, IO)
else
Utf8ToWideString(Value, StrLen(Value), CheckParam(Param, ftUtf8, IO)^.VText);
end;
procedure TSqlDBOleDBStatement.BindTextS(Param: integer; const Value: string;
IO: TSqlDBParamInOutType);
begin
if (Value = '') and
fConnection.Properties.StoreVoidStringAsNull then
CheckParam(Param, ftNull, IO)
else
CheckParam(Param, ftUtf8, IO)^.VText := StringToSynUnicode(Value);
end;
procedure TSqlDBOleDBStatement.BindTextW(Param: integer; const Value: WideString;
IO: TSqlDBParamInOutType);
begin
if (Value = '') and
fConnection.Properties.StoreVoidStringAsNull then
CheckParam(Param, ftNull, IO)
else
CheckParam(Param, ftUtf8, IO)^.VText := Value;
end;
procedure TSqlDBOleDBStatement.BindBlob(Param: integer;
const Data: RawByteString; IO: TSqlDBParamInOutType);
begin
CheckParam(Param, ftBlob, IO)^.VBlob := Data;
end;
procedure TSqlDBOleDBStatement.BindBlob(Param: integer; Data: pointer;
Size: integer; IO: TSqlDBParamInOutType);
begin
FastSetRawByteString(CheckParam(Param, ftBlob, IO)^.VBlob, Data, Size);
end;
procedure TSqlDBOleDBStatement.Bind(Param: integer; Value: double;
IO: TSqlDBParamInOutType);
begin
CheckParam(Param, ftDouble, IO)^.VInt64 := PInt64(@Value)^;
end;
procedure TSqlDBOleDBStatement.BindArray(Param: integer; const Values: array of Int64);
var
i: integer;
begin
with CheckParam(Param, ftInt64, paramIn, length(Values))^ do
for i := 0 to high(Values) do
VArray[i] := Int64ToUtf8(Values[i]);
end;
procedure TSqlDBOleDBStatement.BindArray(Param: integer; const Values: array of RawUtf8);
var
i: integer;
StoreVoidStringAsNull: boolean;
begin
StoreVoidStringAsNull := fConnection.Properties.StoreVoidStringAsNull;
with CheckParam(Param, ftUtf8, paramIn, length(Values))^ do
for i := 0 to high(Values) do
if StoreVoidStringAsNull and
(Values[i] = '') then
VArray[i] := 'null'
else
QuotedStr(Values[i], '''', VArray[i]);
end;
procedure TSqlDBOleDBStatement.Bind(Param: integer; Value: Int64;
IO: TSqlDBParamInOutType);
begin
CheckParam(Param, ftInt64, IO)^.VInt64 := Value;
end;
procedure TSqlDBOleDBStatement.BindCurrency(Param: integer; Value: currency;
IO: TSqlDBParamInOutType);
begin
CheckParam(Param, ftCurrency, IO)^.VInt64 := PInt64(@Value)^;
end;
procedure TSqlDBOleDBStatement.BindDateTime(Param: integer; Value: TDateTime;
IO: TSqlDBParamInOutType);
begin
CheckParam(Param, ftDate, IO)^.VInt64 := PInt64(@Value)^;
end;
procedure TSqlDBOleDBStatement.BindNull(Param: integer; IO: TSqlDBParamInOutType;
BoundType: TSqlDBFieldType);
begin
CheckParam(Param, BoundType, IO)^.VStatus := ord(stIsNull);
end;
function TSqlDBOleDBStatement.CheckParam(Param: integer;
NewType: TSqlDBFieldType; IO: TSqlDBParamInOutType): POleDBStatementParam;
begin
if Param <= 0 then
EOleDBException.RaiseUtf8(
'%.Bind*() called with Param=% should be >= 1', [self, Param]);
if Param > fParamCount then
fParam.Count := Param; // resize fParams[] dynamic array if necessary
result := @fParams[Param - 1];
result^.VType := NewType;
result^.VInOut := IO;
result^.VStatus := 0;
end;
function TSqlDBOleDBStatement.CheckParam(Param: integer; NewType: TSqlDBFieldType;
IO: TSqlDBParamInOutType; ArrayCount: integer): POleDBStatementParam;
begin
result := CheckParam(Param, NewType, IO);
if (NewType in [ftUnknown, ftNull]) or
(fConnection.Properties.BatchSendingAbilities *
[cCreate, cUpdate, cDelete] = []) then
ESqlDBException.RaiseUtf8(
'Invalid call to %s.BindArray(Param=%d,Type=%s)',
[self, Param, TSqlDBFieldTypeToString(NewType)]);
SetLength(result^.VArray, ArrayCount);
result^.VInt64 := ArrayCount;
end;
constructor TSqlDBOleDBStatement.Create(aConnection: TSqlDBConnection);
begin
if not aConnection.InheritsFrom(TSqlDBOleDBConnection) then
EOleDBException.RaiseUtf8('%.Create(%) expects a TSqlDBOleDBConnection',
[self, aConnection]);
inherited Create(aConnection);
fOleDBConnection := TSqlDBOleDBConnection(aConnection);
fParam.Init(TypeInfo(TSqlDBOleDBStatementParamDynArray), fParams, @fParamCount);
fColumn.InitSpecific(TypeInfo(TSqlDBColumnPropertyDynArray), fColumns,
ptRawUtf8, @fColumnCount, {caseinsens=}true);
fRowBufferSize := 16384;
fAlignBuffer := true;
end;
type
TColumnValue = packed record
Status: PtrInt;
Length: PtrUInt; // ignored for alignment
case integer of
0:
(Int64: Int64);
1:
(Double: double);
2:
(ValueInlined: byte); // for TSqlDBColumnProperty.ColumnValueInlined
3:
(ByRef: pointer); // DBTYPE_BYREF PWideChar/PAnsiChar
end;
PColumnValue = ^TColumnValue;
procedure TSqlDBOleDBStatement.LogStatusError(Status: integer;
Column: PSqlDBColumnProperty);
begin
SynDBLog.Add.Log(sllError,
'Invalid [%] % status for column [%] at row % for [%]',
[GetEnumName(TypeInfo(TSqlDBOleDBStatus), Status)^, Status,
Column^.ColumnName, fCurrentRow, fSql], self);
end;
function TSqlDBOleDBStatement.GetCol(Col: integer;
out Column: PSqlDBColumnProperty): pointer;
begin
CheckCol(Col); // check Col value
if (not Assigned(fRowSet)) or
(fColumnCount = 0) then
EOleDBException.RaiseUtf8('%.Column*() with no prior Execute', [self]);
if CurrentRow <= 0 then
EOleDBException.RaiseUtf8('%.Column*() with no prior Step', [self]);
Column := @fColumns[Col];
result := @fRowSetData[Column^.ColumnAttr];
case TSqlDBOleDBStatus(PColumnValue(result)^.Status) of
stOk:
exit; // valid content
stIsNull:
result := nil;
stTruncated:
LogTruncatedColumn(self, Column^);
else
LogStatusError(PColumnValue(result)^.Status, Column);
end;
end;
procedure TSqlDBOleDBStatement.GetCol64(Col: integer; DestType: TSqlDBFieldType;
var Dest);
var
C: PSqlDBColumnProperty;
V: PColumnValue;
begin
V := GetCol(Col, C);
if V = nil then
// column is NULL
Int64(Dest) := 0
else if C^.ColumnType = DestType then
// types match -> fast direct retrieval
Int64(Dest) := V^.Int64
else
// need conversion to destination type
ColumnToTypedValue(Col, DestType, Dest);
end;
function ColPtr(C: PSqlDBColumnProperty; V: PColumnValue): pointer;
{$ifdef HASINLINE} inline; {$endif}
begin
if C^.ColumnValueInlined then
result := @V^.ValueInlined
else
result := V^.ByRef; // either PWideChar or PAnsiChar
end;
function TSqlDBOleDBStatement.ColumnBlob(Col: integer): RawByteString;
// ColumnBlob will return the binary content of the field
var
C: PSqlDBColumnProperty;
V: PColumnValue;
begin
V := GetCol(Col, C);
if V = nil then // column is NULL
result := ''
else
case C^.ColumnType of
ftBlob:
FastSetRawByteString(result, ColPtr(C, V), V^.Length);
ftUtf8:
if V^.Length = 0 then
result := ''
else
// +1 below for trailing WideChar(#0) in the resulting RawUnicode
FastSetRawByteString(result, ColPtr(C, V), V^.Length + 1);
else
FastSetRawByteString(result, @V^.Int64, SizeOf(Int64)); // as binary
end;
end;
function TSqlDBOleDBStatement.ColumnCurrency(Col: integer): currency;
begin
GetCol64(Col, ftCurrency, result{%H-});
end;
function TSqlDBOleDBStatement.ColumnDateTime(Col: integer): TDateTime;
begin
GetCol64(Col, ftDate, result{%H-});
end;
function TSqlDBOleDBStatement.ColumnDouble(Col: integer): double;
begin
GetCol64(Col, ftDouble, result{%H-});
end;
function TSqlDBOleDBStatement.ColumnIndex(const aColumnName: RawUtf8): integer;
begin
result := fColumn.FindHashed(aColumnName);
end;
function TSqlDBOleDBStatement.ColumnNull(Col: integer): boolean;
var
C: PSqlDBColumnProperty;
begin
result := GetCol(Col, C) = nil;
end;
function TSqlDBOleDBStatement.ColumnInt(Col: integer): Int64;
begin
GetCol64(Col, ftInt64, result{%H-});
end;
function TSqlDBOleDBStatement.ColumnName(Col: integer): RawUtf8;
begin
CheckCol(Col);
result := fColumns[Col].ColumnName;
end;
function TSqlDBOleDBStatement.ColumnType(Col: integer;
FieldSize: PInteger): TSqlDBFieldType;
begin
CheckCol(Col);
with fColumns[Col] do
begin
result := ColumnType;
if FieldSize <> nil then
if ColumnValueInlined then
FieldSize^ := ColumnValueDBSize
else
FieldSize^ := 0;
end;
end;
function TSqlDBOleDBStatement.ColumnUtf8(Col: integer): RawUtf8;
var
C: PSqlDBColumnProperty;
V: PColumnValue;
begin
V := GetCol(Col, C);
if V = nil then // column is NULL
result := ''
else