-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathmormot.orm.sql.pas
2733 lines (2603 loc) · 99.9 KB
/
mormot.orm.sql.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
/// ORM Types and Classes for the SQL Database Access
// - 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.orm.sql;
{
*****************************************************************************
ORM SQL Database Access using mormot.db.sql units
- TRestStorageExternal for ORM/REST Storage over SQL
- TOrmVirtualTableExternal for External SQL Virtual Tables
- External SQL Database Engines Registration Functions
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
variants,
contnrs,
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.crypt.secure,
mormot.core.log,
mormot.orm.base,
mormot.orm.core,
mormot.orm.rest,
mormot.orm.client,
mormot.orm.server,
mormot.orm.storage,
mormot.db.core,
mormot.db.sql,
mormot.rest.core,
mormot.rest.server,
mormot.rest.memserver;
{ *********** TRestStorageExternal for ORM/REST Storage over SQL }
type
TRestStorageExternal = class;
/// event handler called to customize the computation of a new ID
// - should set Handled=TRUE if a new ID has been computed and returned
// - Handled=FALSE would let the default ID computation take place
// - note that execution of this method would be protected by a mutex, so
// it would be thread-safe
TOnEngineAddComputeID = function(Sender: TRestStorageExternal;
var Handled: boolean): TID of object;
/// REST server with direct access to a mormot.db.sql-based external database
// - handle all REST commands, using the external SQL database connection,
// and prepared statements
// - is used by TRestServer.Uri for faster RESTful direct access
// - for JOINed SQL statements, the external database is also defined as
// a SQLite3 virtual table, via the TOrmVirtualTableExternal[Cursor] classes
TRestStorageExternal = class(TRestStorage)
protected
/// values retrieved from fStoredClassProps.ExternalDB settings
fTableName: RawUtf8;
fProperties: TSqlDBConnectionProperties;
fSelectOneDirectSQL, fSelectAllDirectSQL, fSelectTableHasRowsSQL: RawUtf8;
fSelectAllWithID, fRetrieveBlobFieldsSQL, fUpdateBlobfieldsSQL: RawUtf8;
// ID handling during Add/Insert
fEngineAddUseSelectMaxID: boolean;
fEngineLockedMaxID: TID;
fOnEngineAddComputeID: TOnEngineAddComputeID;
fEngineAddForcedID: TID;
/// external column layout as retrieved by fProperties
// - used internally to guess e.g. if the column is indexed
// - fFieldsExternal[] contains the external table info, and the internal
// column name is available via fFieldsExternalToInternal[]
fFieldsExternal: TSqlDBColumnDefineDynArray;
/// gives the index of each fFieldsExternal[] item in Props.Fields[]
// - is >=0 for index in Props.Fields[], -1 for RowID/ID, -2 if unknown
// - use InternalFieldNameToFieldExternalIndex() to convert from column name
fFieldsExternalToInternal: TIntegerDynArray;
/// gives the index of each in Props.Fields[]+1 in fFieldsExternal[]
// - expects [0] of RowID/ID, [1..length(fFieldNames)] for others
fFieldsInternalToExternal: TIntegerDynArray;
// multi-thread BATCH process is secured via Lock/UnLock critical section
fBatchMethod: TUriMethod;
fBatchOptions: TRestBatchOptions;
fBatchCapacity, fBatchCount: integer;
// BATCH sending uses TEXT storage for direct sending to database driver
fBatchIDs: TIDDynArray;
fBatchValues: TRawUtf8DynArray;
// some sub-functions used by Create() during DB initialization
procedure InitializeExternalDB(const log: ISynLog);
procedure LogFields(const log: ISynLog);
procedure FieldsInternalInit;
function FieldsExternalIndexOf(
const ColName: RawUtf8; CaseSensitive: boolean): PtrInt;
function PropInfoToExternalField(Prop: TOrmPropInfo;
var Column: TSqlDBColumnCreate): boolean;
/// get fFieldsExternal[] index using fFieldsExternalToInternal[] mapping
// - do handle ID/RowID fields and published methods
function InternalFieldNameToFieldExternalIndex(
const InternalFieldName: RawUtf8): integer;
/// create, prepare and bound inlined parameters to a thread-safe statement
// - this implementation will call the ThreadSafeConnection virtual method,
// then bound inlined parameters as :(1234): and call its Execute method
// - should return nil on error, and not raise an exception
function PrepareInlinedForRows(const aSql: RawUtf8): ISqlDBStatement;
/// overloaded method using FormatUtf8() and binding mormot.db.sql parameters
function PrepareDirectForRows(const SqlFormat: RawUtf8;
const Args, Params: array of const): ISqlDBStatement;
/// create, prepare, bound inlined parameters and execute a thread-safe statement
// - this implementation will call the ThreadSafeConnection virtual method,
// then bound inlined parameters as :(1234): and call its Execute method
// - should return nil on error, and not raise an exception
function ExecuteInlined(const aSql: RawUtf8;
ExpectResults: boolean): ISqlDBRows; overload;
/// overloaded method using FormatUtf8() and inlined parameters
function ExecuteInlined(const SqlFormat: RawUtf8; const Args: array of const;
ExpectResults: boolean): ISqlDBRows; overload;
/// overloaded method using FormatUtf8() and binding mormot.db.sql parameters
function ExecuteDirect(const SqlFormat: RawUtf8; const Args, Params: array of const;
ExpectResults: boolean): ISqlDBRows;
/// overloaded method using FormatUtf8() and binding mormot.db.sql parameters
function ExecuteDirectSqlVar(const SqlFormat: RawUtf8; const Args: array of const;
var Params: TSqlVarDynArray; const LastIntegerParam: Int64;
ParamsMatchCopiableFields: boolean): boolean;
/// run INSERT of UPDATE from the corresponding JSON object
// - Occasion parameter shall be only either soInsert or soUpate
// - each JSON field will be bound with the proper SQL type corresponding to
// the real external table columns (e.g. as TEXT for variant)
// - returns 0 on error, or the Updated/Inserted ID
function ExecuteFromJson(const SentData: RawUtf8; Occasion: TOrmOccasion;
UpdatedID: TID; BatchOptions: TRestBatchOptions): TID;
/// compute the INSERT or UPDATE statement as decoded from a JSON object
function JsonDecodedPrepareToSql(var Decoder: TJsonObjectDecoder;
out ExternalFields: TRawUtf8DynArray; out Types: TSqlDBFieldTypeArray;
Occasion: TOrmOccasion; BatchOptions: TRestBatchOptions;
BoundArray: boolean): RawUtf8;
function GetConnectionProperties: TSqlDBConnectionProperties;
/// check rpmClearPoolOnConnectionIssue in fStoredClassMapping.Options
function HandleClearPoolOnConnectionIssue: boolean;
function DoAdaptSqlForEngineList(var SQL: RawUtf8): boolean;
public
// overridden methods calling the external engine with SQL via Execute
function EngineRetrieve(TableModelIndex: integer; ID: TID): RawUtf8; override;
function EngineExecute(const aSql: RawUtf8): boolean; override;
function EngineLockedNextID: TID; virtual;
function EngineAdd(TableModelIndex: integer; const SentData: RawUtf8): TID; override;
function EngineUpdate(TableModelIndex: integer; ID: TID; const
SentData: RawUtf8): boolean; override;
function EngineDeleteWhere(TableModelIndex: integer; const SqlWhere: RawUtf8;
const IDs: TIDDynArray): boolean; override;
function EngineList(TableModelIndex: integer; const SQL: RawUtf8;
ForceAjax: boolean = false; ReturnedRowCount: PPtrInt = nil): RawUtf8; override;
// BLOBs should be access directly, not through slower JSON Base64 encoding
function EngineRetrieveBlob(TableModelIndex: integer; aID: TID;
BlobField: PRttiProp; out BlobData: RawBlob): boolean; override;
function EngineUpdateBlob(TableModelIndex: integer; aID: TID;
BlobField: PRttiProp; const BlobData: RawBlob): boolean; override;
function EngineSearchField(const FieldName: ShortString;
const FieldValue: array of const; out ResultID: TIDDynArray): boolean;
// overridden method returning TRUE for next calls to EngineAdd/Update/Delete
// will properly handle operations until InternalBatchStop is called
function InternalBatchStart(Encoding: TRestBatchEncoding;
BatchOptions: TRestBatchOptions): boolean; override;
// internal method called by TRestServer.RunBatch() to process fast sending
// to remote database engine (e.g. Oracle bound arrays or MS SQL Bulk insert)
procedure InternalBatchStop; override;
/// called internally by EngineAdd/EngineUpdate/EngineDelete in batch mode
procedure InternalBatchAppend(const aValue: RawUtf8; aID: TID);
/// TRestServer.Uri use it for Static.EngineList to by-pass virtual table
// - overridden method to handle most potential simple queries, e.g. like
// $ SELECT Field1,RowID FROM table WHERE RowID=... AND/OR/NOT Field2=
// - change 'RowID' into 'ID' column name, internal field names into
// mapped external field names ('AS [InternalFieldName]' if needed), and
// SqlTableName into fTableName
// - any 'LIMIT #' clause will be changed into the appropriate SQL statement
// - handle also statements to avoid slow virtual table full scan, e.g.
// $ SELECT count(*) FROM table
function AdaptSqlForEngineList(var SQL: RawUtf8): boolean; override;
public
/// initialize the remote database connection
// - you should not use this, but rather call OrmMapExternal()
// - OrmProps.ExternalDatabase will map the associated TSqlDBConnectionProperties
// - OrmProps.ExternalTableName will retrieve the real full table name,
// e.g. including any databas<e schema prefix
constructor Create(aClass: TOrmClass; aServer: TRestOrmServer); override;
/// delete a row, calling the external engine with SQL
// - made public since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestServer
function EngineDelete(TableModelIndex: integer; ID: TID): boolean; override;
/// search for a numerical field value
// - return true on success (i.e. if some values have been added to ResultID)
// - store the results into the ResultID dynamic array
function SearchField(const FieldName: RawUtf8; FieldValue: Int64;
out ResultID: TIDDynArray): boolean; overload; override;
/// search for a field value, according to its SQL content representation
// - return true on success (i.e. if some values have been added to ResultID)
// - store the results into the ResultID dynamic array
function SearchField(const FieldName, FieldValue: RawUtf8;
out ResultID: TIDDynArray): boolean; overload; override;
/// overridden method for direct external database engine call
function TableRowCount(Table: TOrmClass): Int64; override;
/// overridden method for direct external database engine call
function TableHasRows(Table: TOrmClass): boolean; override;
/// overridden method for direct external database engine call
function MemberExists(Table: TOrmClass; ID: TID): boolean; override;
/// begin a transaction (implements REST BEGIN Member)
// - to be used to speed up some SQL statements like Insert/Update/Delete
// - must be ended with Commit on success
// - must be aborted with Rollback if any SQL statement failed
// - return true if no transaction is active, false otherwise
function TransactionBegin(aTable: TOrmClass;
SessionID: cardinal = 1): boolean; override;
/// end a transaction (implements REST END Member)
// - write all pending SQL statements to the external database
procedure Commit(SessionID: cardinal = 1; RaiseException: boolean = false); override;
/// abort a transaction (implements REST ABORT Member)
// - restore the previous state of the database, before the call to TransactionBegin
procedure RollBack(SessionID: cardinal = 1); override;
/// overridden method for direct external database engine call
function UpdateBlobFields(Value: TOrm): boolean; override;
/// overridden method for direct external database engine call
function RetrieveBlobFields(Value: TOrm): boolean; override;
/// update a field value of the external database
function EngineUpdateField(TableModelIndex: integer;
const SetFieldName, SetValue, WhereFieldName, WhereValue: RawUtf8): boolean; override;
/// update a field value of the external database
function EngineUpdateFieldIncrement(TableModelIndex: integer; ID: TID;
const FieldName: RawUtf8; Increment: Int64): boolean; override;
/// create one index for all specific FieldNames at once
// - this method will in fact call the SqlAddIndex method, if the index
// is not already existing
// - for databases which do not support indexes on BLOB fields (i.e. all
// engine but SQLite3), such FieldNames will be ignored
function CreateSqlMultiIndex(Table: TOrmClass;
const FieldNames: array of RawUtf8;
Unique: boolean; IndexName: RawUtf8 = ''): boolean; override;
/// this method is called by TRestServer.EndCurrentThread method just
// before a thread is finished to ensure that the associated external DB
// connection will be released for this thread
// - this overridden implementation will clean thread-specific connections,
// i.e. call TSqlDBConnectionPropertiesThreadSafe.EndCurrentThread method
// - this method shall be called directly, nor from the main thread
procedure EndCurrentThread(Sender: TThread); override;
/// reset the internal cache of external table maximum ID
// - next EngineAdd/BatchAdd will execute SELECT max(ID) FROM externaltable
// - is a lighter alternative to EngineAddUseSelectMaxID=TRUE, since this
// method may be used only once, when some records have been inserted into
// the external database outside this class scope (e.g. by legacy code)
procedure EngineAddForceSelectMaxID;
/// compute the SQL query corresponding to a prepared request
// - can be used internally e.g. for debugging purposes
function ComputeSql(var Prepared: TOrmVirtualTablePrepared): RawUtf8;
/// retrieve the REST server instance corresponding to an external TOrm
// - just map aServer.GetVirtualStorage(aClass) and will return nil if not
// a TRestStorageExternal
// - you can use it e.g. to call MapField() method in a fluent interface
class function Instance(aClass: TOrmClass;
aServer: TRestOrmServer): TRestStorageExternal;
/// retrieve the external database connection associated to a TOrm
// - just map aServer.GetVirtualStorage(aClass) and will return nil if not
// a TRestStorageExternal
class function ConnectionProperties(aClass: TOrmClass;
aServer: TRestOrmServer): TSqlDBConnectionProperties; overload;
/// disable internal ID generation for INSERT
// - by default, a new ID will be set (either with 'select max(ID)' or via
// the OnEngineLockedNextID event)
// - if the client supplies a forced ID within its JSON content, it would
// be used for adding
// - define this property to a non 0 value if no such ID is expected to be
// supplied, but a fixed "fake ID" is returned by the Add() method; at
// external DB level, no such ID field would be computed nor set at INSERT -
// this feature may be useful when working with a legacy database - of
// course any ID-based ORM method would probably fail to work
property EngineAddForcedID: TID
read fEngineAddForcedID write fEngineAddForcedID;
/// define an alternate method of compute the ID for INSERT
// - by default, a new ID will be with 'select max(ID)', and an internal
// counter (unless EngineAddUseSelectMaxID is true)
// - you can specify a custom callback, which may compute the ID as
// expected (e.g. using a SQL sequence)
property OnEngineAddComputeID: TOnEngineAddComputeID
read fOnEngineAddComputeID write fOnEngineAddComputeID;
published
/// the associated external mormot.db.sql database connection properties
property Properties: TSqlDBConnectionProperties
read GetConnectionProperties;
/// by default, any INSERT will compute the new ID from an internal variable
// - it is very fast and reliable, unless external IDs can be created
// outside this engine
// - you can set EngineAddUseSelectMaxID=true to execute a slower
// 'select max(ID) from TableName' SQL statement before each EngineAdd()
// - a lighter alternative may be to call EngineAddForceSelectMaxID only
// when required, i.e. when the external DB has just been modified
// by a third-party/legacy SQL process
property EngineAddUseSelectMaxID: boolean
read fEngineAddUseSelectMaxID write fEngineAddUseSelectMaxID;
end;
{ *********** TOrmVirtualTableExternal for External SQL Virtual Tables }
type
/// A Virtual Table cursor for reading a TSqlDBStatement content
// - this is the cursor class associated to TOrmVirtualTableExternal
TOrmVirtualTableCursorExternal = class(TOrmVirtualTableCursor)
protected
fStatement: ISqlDBStatement;
fSql: RawUtf8;
fHasData: boolean;
// on exception, release fStatement and optionally clear the pool
procedure HandleClearPoolOnConnectionIssue;
public
/// finalize the external cursor by calling ReleaseRows
destructor Destroy; override;
/// called to begin a search in the virtual table, creating a SQL query
// - the TOrmVirtualTablePrepared parameters were set by
// TOrmVirtualTable.Prepare and will contain both WHERE and ORDER BY statements
// (retrieved by x_BestIndex from a TSqlite3IndexInfo structure)
// - Prepared will contain all prepared constraints and the corresponding
// expressions in the Where[].Value field
// - will move cursor to first row of matching data
// - will return false on low-level database error (but true in case of a
// valid call, even if HasData will return false, i.e. no data match)
// - all WHERE and ORDER BY clauses are able to be translated into a plain
// SQL statement calling the external DB engine
// - will create the internal fStatement from a SQL query, bind the
// parameters, then execute it, ready to be accessed via HasData/Next
function Search(var Prepared: TOrmVirtualTablePrepared): boolean; override;
/// called to retrieve a column value of the current data row
// - if aColumn=VIRTUAL_TABLE_ROWID_COLUMN(-1), will return the row ID
// as varInt64 into aResult
// - will return false in case of an error, true on success
function Column(aColumn: integer; var aResult: TSqlVar): boolean; override;
/// called after Search() to check if there is data to be retrieved
// - should return false if reached the end of matching data
function HasData: boolean; override;
/// called to go to the next row of matching data
// - should return false on low-level database error (but true in case of a
// valid call, even if HasData will return false, i.e. no data match)
function Next: boolean; override;
/// read-only access to the SELECT statement
property SQL: RawUtf8
read fSql;
end;
/// mormot.db.sql-based virtual table for accessing any external database
// - for ORM access, you should use the OrmMapExternal() function to
// associate this virtual table module to any TOrm class
// - transactions are handled by this module, according to the external database
TOrmVirtualTableExternal = class(TOrmVirtualTable)
public { overridden methods }
/// returns the main specifications of the associated TOrmVirtualTableModule
// - this is a read/write table, without transaction (yet), associated to the
// TOrmVirtualTableCursorExternal cursor type, with 'External' as module name
// and TRestStorageExternal as the related Static class
// - no particular class is supplied here, since it will depend on the
// associated Static TRestStorageExternal instance
class procedure GetTableModuleProperties(
var aProperties: TVirtualTableModuleProperties); override;
/// called to determine the best way to access the virtual table
// - will prepare the request for TOrmVirtualTableCursor.Search()
// - this overridden method will let the external DB engine perform the search,
// using a standard SQL "SELECT * FROM .. WHERE .. ORDER BY .." statement
// - in Where[], Expr must be set to not 0 if needed for Search method,
// and OmitCheck always set to true since double check is not necessary
// - OmitOrderBy will be set to true since double sort is not necessary
// - EstimatedCost/EstimatedRows will receive the estimated cost, with
// lowest value if fStatic.fFieldsExternal[].ColumnIndexed is set
// (i.e. if column has an index)
function Prepare(var Prepared: TOrmVirtualTablePrepared): boolean; override;
/// called when a DROP TABLE statement is executed against the virtual table
// - returns true on success, false otherwise
function Drop: boolean; override;
/// called to delete a virtual table row
// - returns true on success, false otherwise
function Delete(aRowID: Int64): boolean; override;
/// called to insert a virtual table row content
// - column order follows the Structure method, i.e. StoredClassProps.Fields[] order
// - returns true on success, false otherwise
// - returns the just created row ID in insertedRowID on success
function Insert(aRowID: Int64; var Values: TSqlVarDynArray;
out insertedRowID: Int64): boolean; override;
/// called to update a virtual table row content
// - column order follows the Structure method, i.e. StoredClassProps.Fields[] order
// - returns true on success, false otherwise
function Update(oldRowID, newRowID: Int64;
var Values: TSqlVarDynArray): boolean; override;
end;
{ *********** External SQL Database Engines Registration }
/// register on the Server-side an external database for an ORM class
// - will associate the supplied class with a TOrmVirtualTableExternal module
// (calling aModel.VirtualTableRegister method), even if the class does not
// inherit from TOrmVirtualTableAutoID (it can be any plain TOrm or
// TOrmMany sub-class for instance)
// - note that TOrmModel.Create() will reset all supplied classes to be defined
// as non virtual (i.e. Kind=ovkSQLite3)
// - this function shall be called BEFORE TRestServer.Create (the server-side
// ORM must know if the database is to be managed as internal or external)
// - this function (and the whole unit) is NOT to be used on the client-side
// - the TSqlDBConnectionProperties instance should be shared by all classes,
// and released globaly when the ORM is no longer needed
// - the full table name, as expected by the external database, could be
// provided here (SqlTableName will be used internally as table name when
// called via the associated SQLite3 Virtual Table) - if no table name is
// specified (''), will use SqlTableName (e.g. 'Customer' for 'TOrmCustomer')
// - typical usage is therefore for instance:
// ! Props := TOleDBMSSQLConnectionProperties.Create('.\SQLEXPRESS','AdventureWorks2008R2','','');
// ! Model := TOrmModel.Create([TOrmCustomer],'root');
// ! OrmMapExternal(Model,TOrmCustomer,Props,'Sales.Customer');
// ! Server := TRestServerDB.Create(aModel,'application.db'),true)
// - the supplied aExternalDB parameter is stored within aClass.OrmProps, so
// the instance must stay alive until all database access to this external table
// is finished (e.g. use a private/protected property)
// - aMappingOptions can be specified now, or customized later
// - server-side may omit a call to OrmMapExternal() if the need of
// an internal database is expected: it will allow custom database configuration
// at runtime, depending on the customer's expectations (or license)
// - after registration, you can tune the field-name mapping by calling
// ! aModel.Props[aClass].ExternalDB.MapField(..)
// - this method would allow to chain MapField() or MapAutoKeywordFields
// definitions, in a fluent interface, to refine the fields mapping
function OrmMapExternal(aModel: TOrmModel; aClass: TOrmClass;
aExternalDB: TSqlDBConnectionProperties; const aExternalTableName: RawUtf8 = '';
aMappingOptions: TOrmMappingOptions = []): POrmMapping; overload;
/// register several tables of the model to be external
// - just a wrapper over the overloaded OrmMapExternal() method
function OrmMapExternal(aModel: TOrmModel;
const aClass: array of TOrmClass; aExternalDB: TSqlDBConnectionProperties;
aMappingOptions: TOrmMappingOptions = []): boolean; overload;
type
/// all possible options for OrmMapExternalAll/TRestExternalDBCreate
// - by default, TAuthUser and TAuthGroup tables will be handled via the
// external DB, but you can avoid it for speed when handling session and security
// by setting regDoNotRegisterUserGroupTables - it would also allow to encrypt
// the SQLite3 instance and its authentication information for higher security
// - you can set regMapAutoKeywordFields to ensure that the mapped field names
// won't conflict with a SQL reserved keyword on the external database by
// mapping a name with a trailing '_' character for the external column
// - regClearPoolOnConnectionIssue will call ClearConnectionPool when a
// connection-linked exception is discovered
TOrmMapExternalOption = (
regDoNotRegisterUserGroupTables,
regMapAutoKeywordFields,
regClearPoolOnConnectionIssue);
/// set of options for OrmMapExternalAll/TRestExternalDBCreate functions
TOrmMapExternalOptions = set of TOrmMapExternalOption;
/// register all tables of the model to be external, with some options
// - by default, all tables are handled by the SQLite3 engine, unless they
// are explicitly declared as external via OrmMapExternal: this
// function can be used to register all tables to be handled by an external DBs
// - this function shall be called BEFORE TRestServer.Create (the server-side
// ORM must know if the database is to be managed as internal or external)
// - this function (and the whole unit) is NOT to be used on the client-side
// - the TSqlDBConnectionProperties instance should be shared by all classes,
// and released globaly when the ORM is no longer needed
// - by default, TAuthUser and TAuthGroup tables will be handled via the
// external DB, but you can avoid it for speed when handling session and security
// by setting regDoNotRegisterUserGroupTables in aExternalOptions
// - other aExternalOptions can be defined to tune the ORM process e.g. about
// mapping or connection loss detection
// - after registration, you can tune the field-name mapping by calling
// ! aModel.Props[aClass].ExternalDB.MapField(..)
function OrmMapExternalAll(aModel: TOrmModel;
aExternalDB: TSqlDBConnectionProperties;
aExternalOptions: TOrmMapExternalOptions): boolean; overload;
/// create a new TRest instance, and possibly an external database, from its
// Model and stored values
// - if aDefinition.Kind matches a TRest registered class, one new instance
// of this kind will be created and returned
// - if aDefinition.Kind is a registered TSqlDBConnectionProperties class name,
// it will instantiate an in-memory TRestServerDB or a TRestServerFullMemory
// instance, then call OrmMapExternalAll() on this connection
// - will return nil if the supplied aDefinition does not match any registered
// TRest or TSqlDBConnectionProperties types
function TRestExternalDBCreate(aModel: TOrmModel;
aDefinition: TSynConnectionDefinition; aHandleAuthentication: boolean;
aExternalOptions: TOrmMapExternalOptions): TRest; overload;
// backward compatibility types redirections
{$ifndef PUREMORMOT2}
type
TVirtualTableExternalRegisterOptions = TOrmMappingOptions;
function VirtualTableExternalRegister(aModel: TOrmModel; aClass: TOrmClass;
aExternalDB: TSqlDBConnectionProperties; const aExternalTableName: RawUtf8 = '';
aMappingOptions: TVirtualTableExternalRegisterOptions = []): boolean; overload;
function VirtualTableExternalRegister(aModel: TOrmModel;
const aClass: array of TOrmClass; aExternalDB: TSqlDBConnectionProperties;
aMappingOptions: TVirtualTableExternalRegisterOptions = []): boolean; overload;
function VirtualTableExternalMap(aModel: TOrmModel;
aClass: TOrmClass; aExternalDB: TSqlDBConnectionProperties;
const aExternalTableName: RawUtf8 = '';
aMapping: TVirtualTableExternalRegisterOptions = []): POrmMapping;
function VirtualTableExternalRegisterAll(aModel: TOrmModel;
aExternalDB: TSqlDBConnectionProperties;
aExternalOptions: TOrmMapExternalOptions): boolean; overload;
function VirtualTableExternalRegisterAll(aModel: TOrmModel;
aExternalDB: TSqlDBConnectionProperties;
DoNotRegisterUserGroupTables: boolean = false;
ClearPoolOnConnectionIssue: boolean = false): boolean; overload;
{$endif PUREMORMOT2}
implementation
{ *********** TRestStorageExternal for ORM/REST Storage over SQL }
{ TRestStorageExternal }
procedure TRestStorageExternal.FieldsInternalInit;
var
i, n, f: PtrInt;
begin
n := length(fFieldsExternal);
SetLength(fFieldsExternalToInternal, n);
with fStoredClassMapping^ do
begin
SetLength(fFieldsInternalToExternal, length(ExtFieldNames) + 1);
for i := 0 to high(fFieldsInternalToExternal) do
fFieldsInternalToExternal[i] := -1;
for i := 0 to n - 1 do
begin
f := ExternalToInternalIndex(fFieldsExternal[i].ColumnName);
fFieldsExternalToInternal[i] := f;
inc(f);
if f >= 0 then
// fFieldsInternalToExternal[0]=RowID, then follows fFieldsExternal[]
fFieldsInternalToExternal[f] := i;
end;
end;
end;
function TRestStorageExternal.PropInfoToExternalField(Prop: TOrmPropInfo;
var Column: TSqlDBColumnCreate): boolean;
begin
case Prop.OrmFieldType of
oftUnknown,
oftMany:
begin
// ignore unknown/virtual fields
result := false;
exit;
end;
// ftUnknown identify 32-bit values, ftInt64=SqlDBFieldType for 64-bit
oftEnumerate,
oftBoolean:
Column.DBType := ftUnknown;
else
// Prop may have identified e.g. T*ObjArray as ftUtf8
Column.DBType := Prop.SqlDBFieldType;
end;
if Column.DBType = ftUtf8 then
Column.Width := Prop.FieldWidth
else
Column.Width := 0;
Column.Unique := aIsUnique in Prop.Attributes;
Column.PrimaryKey := false;
Column.Name := fStoredClassMapping^.ExtFieldNames[Prop.PropertyIndex];
result := true;
end;
procedure TRestStorageExternal.LogFields(const log: ISynLog);
begin
fProperties.GetFields(UnQuotedSQLSymbolName(fTableName), fFieldsExternal);
log.Log(sllDebug, 'GetFields', TypeInfo(TSqlDBColumnDefineDynArray),
fFieldsExternal, self);
end;
function TRestStorageExternal.FieldsExternalIndexOf(
const ColName: RawUtf8; CaseSensitive: boolean): PtrInt;
begin
if CaseSensitive then
begin
for result := 0 to high(fFieldsExternal) do
if fFieldsExternal[result].ColumnName = ColName then
exit;
end
else
for result := 0 to high(fFieldsExternal) do // with proper inlining
if IdemPropNameU(fFieldsExternal[result].ColumnName, ColName) then
exit;
result := -1;
end;
procedure TRestStorageExternal.InitializeExternalDB(const log: ISynLog);
var
s: RawUtf8;
i, f: PtrInt;
nfo: TOrmPropInfo;
Field: TSqlDBColumnCreate;
TableCreated, TableModified: boolean;
CreateColumns: TSqlDBColumnCreateDynArray;
options: TOrmMappingOptions;
begin
// initialize external DB properties
options := fStoredClassMapping^.options;
fTableName := fStoredClassMapping^.TableName;
fProperties :=
fStoredClassMapping^.ConnectionProperties as TSqlDBConnectionProperties;
log.Log(sllInfo, '% as % % Server=%',
[StoredClass, fTableName, fProperties, Owner], self);
if fProperties = nil then
ERestStorage.RaiseUtf8('%.Create: no external DB defined for %',
[self, StoredClass]);
// ensure external field names are compatible with the external DB keywords
for f := 0 to StoredClassRecordProps.Fields.Count - 1 do
begin
nfo := StoredClassRecordProps.Fields.List[f];
if nfo.OrmFieldType in COPIABLE_FIELDS then // ignore oftMany
begin
s := fStoredClassMapping^.ExtFieldNames[f];
if rpmQuoteFieldName in options then
fStoredClassMapping^.MapField(nfo.Name, '"' + s + '"')
else if fProperties.IsSqlKeyword(s) then
begin
log.Log(sllWarning, '%.%: Field name % is not compatible with %',
[fStoredClass, nfo.Name, s, fProperties.DbmsEngineName], self);
if rpmAutoMapKeywordFields in options then
begin
log.Log(sllWarning, '-> %.% mapped to %_',
[fStoredClass, nfo.Name, s], self);
fStoredClassMapping^.MapField(nfo.Name, s + '_');
end
else
log.Log(sllWarning, '-> you should better use MapAutoKeywordFields', self);
end;
end;
end;
// create corresponding external table if necessary, and retrieve its fields info
TableCreated := false;
LogFields(log);
if not (rpmNoCreateMissingTable in options) then
if fFieldsExternal = nil then
begin
// table is not yet existing -> try to create it
with fStoredClass.OrmProps do
begin
SetLength(CreateColumns, Fields.Count + 1);
CreateColumns[0].Name := fStoredClassMapping^.RowIDFieldName;
CreateColumns[0].DBType := ftInt64;
CreateColumns[0].Unique := true;
CreateColumns[0].NonNullable := true;
CreateColumns[0].PrimaryKey := true;
f := 1;
for i := 0 to Fields.Count - 1 do
if PropInfoToExternalField(Fields.List[i], CreateColumns[f]) then
inc(f);
if f <> Length(CreateColumns) then
// just ignore non handled field types
SetLength(CreateColumns, f);
end;
s := fProperties.SqlCreate(fTableName, CreateColumns, false);
if Assigned(fProperties.OnTableCreate) then
TableCreated := fProperties.OnTableCreate(
fProperties, fTableName, CreateColumns, s)
else if s <> '' then
TableCreated := ExecuteDirect(s, [], [], false) <> nil;
if TableCreated then
begin
LogFields(log);
if fFieldsExternal = nil then
ERestStorage.RaiseUtf8(
'%.Create: external table creation % failed: GetFields() ' +
'returned nil - sql=[%]', [self, StoredClass, fTableName, s]);
end;
end;
FieldsInternalInit;
// create any missing field if necessary
if not (rpmNoCreateMissingField in options) then
if not TableCreated then
begin
TableModified := false;
with StoredClassRecordProps do
for f := 0 to Fields.Count - 1 do
if Fields.List[f].OrmFieldType in COPIABLE_FIELDS then // ignore oftMany
/// real database columns exist for Simple + Blob fields (not Many)
if FieldsExternalIndexOf(
fStoredClassMapping^.ExtFieldNamesUnQuotedSql[f],
rpmMissingFieldNameCaseSensitive in options) < 0 then
begin
// add new missing Field
Finalize(Field);
FillcharFast(Field, SizeOf(Field), 0);
if PropInfoToExternalField(Fields.List[f], Field) then
begin
s := fProperties.SqlAddColumn(fTableName, Field);
if Assigned(fProperties.OnTableAddColumn) then
begin
if fProperties.OnTableAddColumn(
fProperties, fTableName, Field, s) then
TableModified := true; // don't raise ERestStorage from here
end
else if s <> '' then
if ExecuteDirect(s, [], [], false) <> nil then
TableModified := true
else
ERestStorage.RaiseUtf8('%.Create: %: ' +
'unable to create external missing field %.% - sql=[%]',
[self, StoredClass, fTableName, Fields.List[f].Name, s]);
end;
end;
if TableModified then
begin
// retrieve raw field information from DB after ALTER TABLE
LogFields(log);
FieldsInternalInit;
end;
end;
// compute the sql statements used internally for external DB requests
with fStoredClassMapping^ do
begin
FormatUtf8('select % from % where %=?',
[Sql.TableSimpleFields[{withid=}true, {withtablename=}false],
fTableName, RowIDFieldName], fSelectOneDirectSQL); // return ID field
FormatUtf8('select %,% from %', [sql.InsertSet, RowIDFieldName, fTableName],
fSelectAllDirectSQL);
fRetrieveBlobFieldsSQL := InternalCsvToExternalCsv(
StoredClassRecordProps.SqlTableRetrieveBlobFields);
fUpdateBlobFieldsSQL := InternalCsvToExternalCsv(
StoredClassRecordProps.SqlTableUpdateBlobFields, '=?,', '=?');
end;
fSelectTableHasRowsSQL := FormatUtf8('select ID from % limit 1',
[StoredClassRecordProps.SqlTableName]);
DoAdaptSqlForEngineList(fSelectTableHasRowsSQL);
fSelectAllWithID := fStoredClassProps.Sql.SelectAllWithRowID;
DoAdaptSqlForEngineList(fSelectAllWithID);
end;
constructor TRestStorageExternal.Create(aClass: TOrmClass; aServer: TRestOrmServer);
var
log: ISynLog;
begin
if aServer = nil then
ERestStorage.RaiseUtf8('%.Create(%): aServer=%', [self, aClass, aServer]);
log := aServer.LogClass.Enter('Create %', [aClass], self);
inherited Create(aClass, aServer);
// initialize external DB process: setup ORM mapping, and create table/columns
InitializeExternalDB(log);
end;
function TRestStorageExternal.AdaptSqlForEngineList(var SQL: RawUtf8): boolean;
begin
if SQL = '' then
result := false
else if PropNameEquals(fStoredClassProps.Sql.SelectAllWithRowID, SQL) or
PropNameEquals(fStoredClassProps.Sql.SelectAllWithID, SQL) then
begin
SQL := fSelectAllWithID; // pre-computed for this common statement
result := true;
end
else
result := DoAdaptSqlForEngineList(SQL);
end;
function TRestStorageExternal.DoAdaptSqlForEngineList(var SQL: RawUtf8): boolean;
var
stmt: TSelectStatement;
W: TJsonWriter;
limit: TSqlDBDefinitionLimitClause;
limitSQL, name: RawUtf8;
f, n: PtrInt;
temp: TTextWriterStackBuffer; // shared fTempBuffer is not protected now
begin
result := false;
// parse the ORM-level SQL statement
stmt := TSelectStatement.Create(SQL,
fStoredClassRecordProps.Fields.IndexByName,
fStoredClassRecordProps.SimpleFieldSelect);
try
if (stmt.SqlStatement = '') or // parsing failed
not PropNameEquals(stmt.TableName, fStoredClassRecordProps.SqlTableName) then
begin
{$ifdef DEBUGSQLVIRTUALTABLE}
InternalLog('AdaptSqlForEngineList: complex statement -> switch to ' +
'SQLite3 virtual engine - check efficiency', [], sllDebug);
{$endif DEBUGSQLVIRTUALTABLE}
exit;
end;
if stmt.Offset <> 0 then
begin
fRest.InternalLog('AdaptSqlForEngineList: unsupported OFFSET for [%]',
[SQL], sllWarning);
exit;
end;
if stmt.Limit = 0 then
limit.Position := posNone
else
begin
limit := fProperties.SqlLimitClause(stmt);
if limit.Position = posNone then
begin
fRest.InternalLog('AdaptSqlForEngineList: unknown % LIMIT syntax for [%]',
[ToText(fProperties.Dbms)^, SQL], sllWarning);
exit;
end;
if limit.Position = posOuter then
FormatUtf8(limit.InsertFmt, ['%', stmt.Limit], limitSQL)
else
FormatUtf8(limit.InsertFmt, [stmt.Limit], limitSQL);
end;
// generate the SQL statement matching the external database
W := TJsonWriter.CreateOwnedStream(temp);
try
W.AddShorter('select ');
if limit.Position = posSelect then
W.AddString(limitSQL);
for f := 0 to high(stmt.Select) do
with stmt.Select[f] do
begin
if FunctionName <> '' then
begin
W.AddString(FunctionName);
W.AddDirect('(');
end;
if FunctionKnown = funcCountStar then
W.AddDirect('*')
else
begin
W.AddString(fStoredClassMapping^.FieldNameByIndex(Field - 1));
W.AddString(SubField);
end;
if FunctionName <> '' then
W.AddDirect(')');
if ToBeAdded <> 0 then
begin
if ToBeAdded > 0 then
W.AddDirect('+');
W.Add(ToBeAdded);
end;
if Alias <> '' then
begin
W.AddShorter(' as ');
W.AddString(Alias);
end
else if not (Field in fStoredClassMapping^.FieldNamesMatchInternal) then
begin
if Field = 0 then
name := ID_TXT
else
// RowID may be reserved (e.g. for Oracle)
name := fStoredClassRecordProps.Fields.List[Field - 1].name;
W.AddShorter(' as ');
if (FunctionName = '') or
(FunctionKnown in [funcDistinct, funcMax]) then
W.AddString(name)
else
begin
W.AddDirect('"');
W.AddString(FunctionName);
W.AddDirect('(');
W.AddString(name);
W.AddDirect(')', '"');
end;
end;
W.AddComma;
end;
W.CancelLastComma;
W.AddShorter(' from ');
W.AddString(fTableName);
n := length(stmt.Where);
if n = 0 then
begin
if limit.Position = posWhere then
begin
W.AddShorter(' where ');
W.AddString(limitSQL);
end;
end
else
begin
dec(n);
W.AddShorter(' where ');
if limit.Position = posWhere then
begin
W.AddString(limitSQL);
W.AddShorter(' and ');
end;
for f := 0 to n do
with stmt.Where[f] do
begin
if (FunctionName <> '') or
(Operation > high(DB_SQLOPERATOR)) then
begin
fRest.InternalLog(
'AdaptSqlForEngineList: unsupported function %() for [%]',
[FunctionName, SQL], sllWarning);
exit;
end;
if f > 0 then
if JoinedOR then
W.AddShorter(' or ')
else
W.AddShorter(' and ');
if NotClause then
W.AddShorter('not ');
if ParenthesisBefore <> '' then
W.AddString(ParenthesisBefore);
W.AddString(fStoredClassMapping^.FieldNameByIndex(Field - 1));
W.AddString(SubField);
W.AddString(DB_SQLOPERATOR[Operation]);
if not (Operation in [opIsNull, opIsNotNull]) then
W.AddNoJsonEscape(ValueSql, ValueSqlLen);
if ParenthesisAfter <> '' then
W.AddString(ParenthesisAfter);
end;
end;
if stmt.GroupByField <> nil then
begin
W.AddShort(' group by ');
for f := 0 to high(stmt.GroupByField) do
begin
W.AddString(fStoredClassMapping^.FieldNameByIndex(stmt.GroupByField[f] - 1));
W.AddComma;
end;
W.CancelLastComma;
end;
if stmt.OrderByField <> nil then
begin
W.AddShort(' order by ');
for f := 0 to high(stmt.OrderByField) do
begin
W.AddString(fStoredClassMapping^.FieldNameByIndex(stmt.OrderByField[f] - 1));
if FieldBitGet(stmt.OrderByFieldDesc, f) then
W.AddShorter(' desc');
W.AddComma;
end;
W.CancelLastComma;
end;
if limit.Position = posAfter then
W.AddString(limitSQL);
W.SetText(SQL);
if limit.Position = posOuter then
SQL := FormatUtf8(limitSQL, [SQL]);
result := true;
finally
W.Free;
end;
finally
stmt.Free;
end;
end;
function TRestStorageExternal.EngineLockedNextID: TID;
procedure RetrieveFromDB;
// fProperties.SqlCreate: ID Int64 PRIMARY KEY -> compute unique RowID
// (not all DB engines handle autoincrement feature - e.g. Oracle does not)
var
rows: ISqlDBRows;
begin
fEngineLockedMaxID := 0;
rows := ExecuteDirect('select max(%) from %',
[fStoredClassMapping^.RowIDFieldName, fTableName], [], true);
if rows = nil then
exit;
if rows.Step then
fEngineLockedMaxID := rows.ColumnInt(0);
rows.ReleaseRows;
end;
var
handled: boolean;
begin
if fEngineAddForcedID <> 0 then
begin
result := fEngineAddForcedID;
exit;
end;
if Assigned(fOnEngineAddComputeID) then
begin
result := fOnEngineAddComputeID(self, handled);
if handled then
exit;