forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmormot.orm.rest.pas
2921 lines (2746 loc) · 97.1 KB
/
mormot.orm.rest.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
/// Object-Relational-Mapping (ORM) Abstract REST Implementation
// - 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.rest;
{
*****************************************************************************
IRestOrm Implementation as used by TRest
- Some definitions Used by TRestOrm Implementation
- TRestOrm Parent Class for abstract REST client/server
- TOrmTableWritable Read/Write TOrmTable
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
variants,
contnrs,
mormot.core.base,
mormot.core.os,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.text,
mormot.core.datetime,
mormot.core.variants,
mormot.crypt.secure,
mormot.core.data,
mormot.core.rtti,
mormot.core.log,
mormot.core.json,
mormot.orm.base,
mormot.orm.core,
mormot.rest.core,
mormot.db.core;
{ ************ Some definitions Used by TRestOrm Implementation }
const
/// convert a TRestBatch encoding scheme into the corresponding ORM TUriMethod
BATCH_METHOD: array[TRestBatchEncoding] of TUriMethod = (
mPOST, // encPost
mPOST, // encSimple
mPOST, // encPostHex
mPOST, // encPostHexID
mPUT, // encPut
mPUT, // encPutHex
mDELETE); // encDelete
/// convert a TRestBatch encoding scheme into the corresponding ORM TUriMethod
BATCH_EVENT: array[TRestBatchEncoding] of TOrmEvent = (
oeAdd, // encPost
oeAdd, // encSimple
oeAdd, // encPostHex
oeAdd, // encPostHexID
oeUpdate, // encPut
oeUpdate, // encPutHex
oeDelete); // encDelete
{ ************ TRestOrm Parent Class for abstract REST client/server }
type
/// low-level TRestOrm.InternalBatchDirectSupport response
TRestOrmBatchDirect = (
dirUnsupported,
dirWriteLock,
dirWriteNoLock);
/// abtract state-engine used internally by TRestOrm.NewEngineRetrieveAsync
TRestOrmEngineRetrieveAsync = class
public
Context: TObject;
Table: TOrmClass;
TableIndex: PtrInt;
ID: TID;
Sql: RawUtf8;
ResultOne: TOnRestOrmRetrieveOne;
ResultJson: TOnRestOrmRetrieveJson;
ResultArray: TOnRestOrmRetrieveArray;
procedure Execute; virtual; abstract; // override calls OnResult then Free
procedure OnResult(const Json: RawUtf8);
end;
{$M+}
/// implements TRest.ORM process for abstract REST client/server
TRestOrm = class(TRestOrmParent, IRestOrm)
protected
fTempJsonWriterLock: TLightLock; // topmost to ensure proper aarch64 align
fRest: TRest;
fModel: TOrmModel; // owned by the TRest associated instance
fCache: TOrmCache;
fTransactionActiveSession: cardinal;
fTransactionTable: TOrmClass;
fTempJsonWriter: TJsonWriter;
/// compute SELECT ... FROM TABLE WHERE ...
function SqlComputeForSelect(TableModelIndex: integer; Table: TOrmClass;
const FieldNames, WhereClause: RawUtf8): RawUtf8;
/// used by all overloaded Add/Delete methods
procedure GetJsonValuesForAdd(TableIndex: integer; Value: TOrm;
ForceID, DoNotAutoComputeFields, WithBlobs: boolean;
CustomFields: PFieldBits; var result: RawUtf8);
function InternalAdd(Value: TOrm; SendData: boolean;
CustomFields: PFieldBits;
ForceID, DoNotAutoComputeFields: boolean): TID; virtual;
function InternalDeleteNotifyAndGetIDs(Table: TOrmClass;
const SqlWhere: RawUtf8; var IDs: TIDDynArray): boolean;
public
// ------- abstract methods to be overriden by the real database engine
/// retrieve a list of members as JSON encoded data
// - implements REST GET collection
// - returns '' on error, or JSON data, even with no result rows
// - override this method for direct data retrieval from the database engine
// and direct JSON export, avoiding a TOrmTable which allocates memory for every
// field values before the JSON export
// - can be called for a single Table (ModelRoot/Table), or with low level SQL
// query (ModelRoot + SQL sent as request body)
// - if ReturnedRowCount points to an integer variable, it must be filled with
// the number of row data returned (excluding field names)
// - this method must be implemented in a thread-safe manner
function EngineList(TableModelIndex: integer; const SQL: RawUtf8;
ForceAjax: boolean = false; ReturnedRowCount: PPtrInt = nil): RawUtf8; virtual; abstract;
/// Execute directly a SQL statement, without any result
// - implements POST SQL on ModelRoot URI
// - return true on success
// - override this method for proper calling the database engine
// - don't call this method in normal cases
// - this method must be implemented to be thread-safe
function EngineExecute(const aSql: RawUtf8): boolean; virtual; abstract;
/// get a member from its ID
// - implements REST GET member
// - returns the data of this object as JSON
// - override this method for proper data retrieval from the database engine
// - this method must be implemented in a thread-safe manner
function EngineRetrieve(TableModelIndex: integer; ID: TID): RawUtf8; virtual; abstract;
/// raw factory from the underlying database engine, using a callback as result
// - this default implementation will raise an EOrmAsyncException
function NewEngineRetrieveAsync(
Context: TObject; Table: TOrmClass): TRestOrmEngineRetrieveAsync; virtual;
/// create a new member
// - implements REST POST collection
// - SentData can contain the JSON object with field values to be added
// - class is taken from Model.Tables[TableModelIndex]
// - returns the TOrm ID/RowID value, 0 on error
// - if a "RowID":.. or "ID":.. member is set in SentData, it shall force
// this value as insertion ID
// - override this method for proper calling the database engine
// - this method must be implemented in a thread-safe manner
function EngineAdd(TableModelIndex: integer; const SentData: RawUtf8): TID; virtual; abstract;
/// update a member
// - implements REST PUT collection
// - SentData can contain the JSON object with field values to be added
// - returns true on success
// - override this method for proper calling the database engine
// - this method must be implemented in a thread-safe manner
function EngineUpdate(TableModelIndex: integer; ID: TID; const SentData: RawUtf8): boolean; virtual; abstract;
/// delete a member
// - implements REST DELETE collection
// - returns true on success
// - override this method for proper calling the database engine
// - this method must be implemented in a thread-safe manner
function EngineDelete(TableModelIndex: integer; ID: TID): boolean; virtual; abstract;
/// delete several members, from a WHERE clause
// - IDs[] contains the already-computed matching IDs for SqlWhere
// - returns true on success
// - override this method for proper calling the database engine, i.e.
// using either IDs[] or a faster SQL statement
// - this method must be implemented in a thread-safe manner
function EngineDeleteWhere(TableModelIndex: integer; const SqlWhere: RawUtf8;
const IDs: TIDDynArray): boolean; virtual; abstract;
/// get a blob field content from its member ID and field name
// - implements REST GET member with a supplied blob field name
// - returns TRUE on success
// - returns the data of this blob as raw binary (not JSON) in BlobData
// - override this method for proper data retrieval from the database engine
// - this method must be implemented in a thread-safe manner
function EngineRetrieveBlob(TableModelIndex: integer; aID: TID;
BlobField: PRttiProp; out BlobData: RawBlob): boolean; virtual; abstract;
/// update a blob field content from its member ID and field name
// - implements REST PUT member with a supplied blob field name
// - returns TRUE on success
// - the data of this blob must be specified as raw binary (not JSON) in BlobData
// - override this method for proper data retrieval from the database engine
// - this method must be implemented in a thread-safe manner
function EngineUpdateBlob(TableModelIndex: integer; aID: TID;
BlobField: PRttiProp; const BlobData: RawBlob): boolean; virtual; abstract;
/// update an individual record field value from a specified ID or Value
// - return true on success
// - will allow execution of requests like
// $ UPDATE tablename SET setfieldname=setvalue WHERE wherefieldname=wherevalue
// - SetValue and WhereValue parameters must match our inline format, i.e.
// by double quoted with " for strings, or be plain text for numbers - e.g.
// $ Client.EngineUpdateField(TOrmMyRecord,'FirstName','"Smith"','RowID','10')
// but you should better use the UpdateField() overload methods instead
// - WhereFieldName and WhereValue must be set: for security reasons,
// implementations of this method will reject an UPDATE without any WHERE
// clause, so you won't be able to use it to execute such statements:
// $ UPDATE tablename SET setfieldname=setvalue
// - this method must be implemented in a thread-safe manner
function EngineUpdateField(TableModelIndex: integer;
const SetFieldName, SetValue, WhereFieldName, WhereValue: RawUtf8): boolean; virtual; abstract;
/// increments one integer field value
// - this default implementation is just a wrapper around OneFieldValue +
// UpdateField methods
function EngineUpdateFieldIncrement(TableModelIndex: integer; ID: TID;
const FieldName: RawUtf8; Increment: Int64): boolean; virtual;
/// send/execute the supplied JSON BATCH content, and return the expected array
// - this method will be implemented for TRestClient and TRestServer only
// - this default implementation will trigger an EOrmException
// - warning: supplied JSON Data can be parsed in-place, so modified
function EngineBatchSend(Table: TOrmClass; var Data: RawUtf8;
var Results: TIDDynArray; ExpectedResultsCount: integer): integer; virtual;
/// internal method called by TRestServer.Batch() to process fast sending
// to remote database engine (e.g. Oracle bound arrays or MS SQL Bulk insert)
// - returns TRUE if this method is handled by the engine, or FALSE if
// individual calls to Engine*() are expected
// - this default implementation returns FALSE
// - an overridden method returning TRUE shall ensure that calls to
// EngineAdd / EngineUpdate / EngineDelete (depending of supplied Method)
// will properly handle operations until InternalBatchStop() is called
function InternalBatchStart(Encoding: TRestBatchEncoding;
BatchOptions: TRestBatchOptions): boolean; virtual;
/// internal method called by TRestServer.Batch() to process fast sending
// to remote database engine (e.g. Oracle bound arrays or MS SQL Bulk insert)
// - this default implementation will raise an EOrmException (since
// InternalBatchStart returns always FALSE at this TRest level)
// - InternalBatchStart/Stop may safely use a lock for multithreading:
// implementation in TRestServer.Batch use a try..finally block
procedure InternalBatchStop; virtual;
/// internal method called by TRestServer.Batch() to process SIMPLE input
// - an optimized storage engine could override it to process the Sent
// JSON array values directly from the memory buffer
// - called first to return if supported in overriden methods
function InternalBatchDirectSupport(Encoding: TRestBatchEncoding;
RunTableIndex: integer): TRestOrmBatchDirect; virtual;
/// internal method called by TRestServer.Batch() to process SIMPLE input
// - an optimized storage engine could override it to process the Sent
// JSON array values directly from the memory buffer
// - called a second time with the proper Sent JSON array of values,
// returning the inserted ID or 200 after proper update
function InternalBatchDirectOne(Encoding: TRestBatchEncoding;
RunTableIndex: integer; const Fields: TFieldBits; Sent: PUtf8Char): TID; virtual;
public
// ------- TRestOrm main methods
/// initialize the class, and associated to a TRest and its TOrmModel
constructor Create(aRest: TRest); reintroduce; virtual;
/// initialize the class, and associated to TOrmModel with no main TRest
constructor CreateWithoutRest(aModel: TOrmModel); reintroduce; virtual;
/// release internal used instances
destructor Destroy; override;
/// internal TOrm value serialization to a JSON object
// - will use shared AcquireJsonWriter instance if available
procedure GetJsonValue(Value: TOrm; withID: boolean;
const Fields: TFieldBits; out Json: RawUtf8); overload;
/// internal TOrm value serialization to a JSON object
// - will use shared AcquireJsonWriter instance if available
procedure GetJsonValue(Value: TOrm; withID: boolean; Occasion: TOrmOccasion;
var Json: RawUtf8); overload;
{$ifdef FPC} inline; {$endif} // avoid URW1111 on Delphi 2010
/// access to a thread-safe internal cached TJsonWriter instance
function AcquireJsonWriter(var tmp: TTextWriterStackBuffer): TJsonWriter;
{$ifdef HASINLINE} inline; {$endif}
/// release the thread-safe cached TJsonWriter returned by AcquireJsonWriter
procedure ReleaseJsonWriter(WR: TJsonWriter);
{$ifdef HASINLINE} inline; {$endif}
/// low-level access to the current TOrm class holding a transaction
// - equals nil outside of a TransactionBegin/Commit scope
property TransactionTable: TOrmClass
read fTransactionTable;
public
// ------- IRestOrm interface implementation methods
// calls internally the "SELECT Count(*) FROM TableName;" SQL statement
function TableRowCount(Table: TOrmClass): Int64; virtual;
// calls internally a "SELECT RowID FROM TableName LIMIT 1" SQL statement,
// which is much faster than testing if "SELECT count(*)" equals 0 - see
// @http://stackoverflow.com/questions/8988915
function TableHasRows(Table: TOrmClass): boolean; virtual;
// executes by default "SELECT max(rowid) FROM TableName"
function TableMaxID(Table: TOrmClass): TID; virtual;
// try from cache, then from DB
function MemberExists(Table: TOrmClass; ID: TID): boolean; virtual;
{$ifdef ORMGENERICS}
function RetrieveIList(T: TOrmClass; var IList;
const FieldsCsv: RawUtf8 = ''): boolean; overload;
function RetrieveIList(T: TOrmClass; var IList;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const FieldsCsv: RawUtf8 = ''): boolean; overload;
{$endif ORMGENERICS}
function OneFieldValue(Table: TOrmClass;
const FieldName, WhereClause: RawUtf8): RawUtf8; overload;
function OneFieldValueInt64(Table: TOrmClass;
const FieldName, WhereClause: RawUtf8; Default: Int64 = 0): Int64;
function OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const): RawUtf8; overload;
function OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
const WhereClauseFmt: RawUtf8; const Args, Bounds: array of const): RawUtf8; overload;
function OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
const WhereClauseFmt: RawUtf8; const Args, Bounds: array of const;
out Data: Int64): boolean; overload;
function OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
WhereID: TID): RawUtf8; overload;
function MultiFieldValue(Table: TOrmClass;
const FieldName: array of RawUtf8; var FieldValue: array of RawUtf8;
const WhereClause: RawUtf8): boolean; overload;
function MultiFieldValue(Table: TOrmClass;
const FieldName: array of RawUtf8; var FieldValue: array of RawUtf8;
WhereID: TID): boolean; overload;
function OneFieldValues(Table: TOrmClass; const FieldName: RawUtf8;
const WhereClause: RawUtf8; out Data: TRawUtf8DynArray): boolean; overload;
function OneFieldValues(Table: TOrmClass; const FieldName: RawUtf8;
const WhereClause: RawUtf8; var Data: TInt64DynArray;
SQL: PRawUtf8 = nil): boolean; overload;
function OneFieldValues(Table: TOrmClass; const FieldName: RawUtf8;
const WhereClause: RawUtf8 = ''; const Separator: RawUtf8 = ','): RawUtf8; overload;
function OneFieldValues(Table: TOrmClass; const FieldName, WhereClause:
RawUtf8; Strings: TStrings; IDToIndex: PID = nil): boolean; overload;
function MultiFieldValues(Table: TOrmClass; const FieldNames: RawUtf8;
const WhereClause: RawUtf8 = ''): TOrmTable; overload;
function MultiFieldValues(Table: TOrmClass; const FieldNames: RawUtf8;
const WhereClauseFormat: RawUtf8;
const BoundsSqlWhere: array of const): TOrmTable; overload;
function MultiFieldValues(Table: TOrmClass; const FieldNames: RawUtf8;
const WhereClauseFormat: RawUtf8;
const Args, Bounds: array of const): TOrmTable; overload;
function FtsMatch(Table: TOrmFts3Class; const WhereClause: RawUtf8;
var DocID: TIDDynArray): boolean; overload;
function FtsMatch(Table: TOrmFts3Class; const MatchClause: RawUtf8;
var DocID: TIDDynArray; const PerFieldWeight: array of double;
limit: integer = 0; offset: integer = 0): boolean; overload;
function MainFieldValue(Table: TOrmClass; ID: TID;
ReturnFirstIfNoUnique: boolean = false): RawUtf8;
function MainFieldID(Table: TOrmClass; const Value: RawUtf8): TID;
function MainFieldIDs(Table: TOrmClass; const Values: array of RawUtf8;
out IDs: TIDDynArray): boolean;
function Retrieve(const SqlWhere: RawUtf8; Value: TOrm;
const FieldsCsv: RawUtf8 = ''): boolean; overload; virtual;
function Retrieve(const WhereClauseFmt: RawUtf8;
const Args, Bounds: array of const; Value: TOrm;
const FieldsCsv: RawUtf8 = ''): boolean; overload;
function Retrieve(aID: TID; Value: TOrm;
ForUpdate: boolean = false): boolean; overload; virtual;
function Retrieve(Reference: TRecordReference;
ForUpdate: boolean = false): TOrm; overload;
function Retrieve(aPublishedRecord, aValue: TOrm): boolean; overload;
procedure RetrieveAsync(Context: TObject; Table: TOrmClass; const SqlWhere: RawUtf8;
const OnResult: TOnRestOrmRetrieveOne; const FieldsCsv: RawUtf8 = ''); overload;
procedure RetrieveAsync(Context: TObject; Table: TOrmClass; const WhereClauseFmt: RawUtf8;
const Args, Bounds: array of const; const OnResult: TOnRestOrmRetrieveOne;
const FieldsCsv: RawUtf8 = ''); overload;
procedure RetrieveAsync(Context: TObject; Table: TOrmClass; ID: TID;
const OnResult: TOnRestOrmRetrieveOne); overload;
procedure RetrieveAsyncListJson(Context: TObject; Table: TOrmClass;
const SqlWhere: RawUtf8; const OnResult: TOnRestOrmRetrieveJson;
const FieldsCsv: RawUtf8 = ''; aForceAjax: boolean = false); overload;
procedure RetrieveAsyncListObjArray(Context: TObject; Table: TOrmClass;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const OnResult: TOnRestOrmRetrieveArray; const FieldsCsv: RawUtf8 = '');
function RetrieveList(Table: TOrmClass;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const FieldsCsv: RawUtf8 = ''): TObjectList; overload;
function RetrieveListJson(Table: TOrmClass;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const FieldsCsv: RawUtf8 = ''; aForceAjax: boolean = false): RawJson; overload;
function RetrieveListJson(Table: TOrmClass;
const SqlWhere: RawUtf8; const FieldsCsv: RawUtf8 = '';
aForceAjax: boolean = false): RawJson; overload;
function RetrieveDocVariantArray(Table: TOrmClass;
const ObjectName, FieldsCsv: RawUtf8;
FirstRecordID: PID = nil; LastRecordID: PID = nil): variant; overload;
function RetrieveDocVariantArray(Table: TOrmClass;
const ObjectName: RawUtf8; const FormatSqlWhere: RawUtf8;
const BoundsSqlWhere: array of const; const FieldsCsv: RawUtf8;
FirstRecordID: PID = nil; LastRecordID: PID = nil): variant; overload;
function RetrieveOneFieldDocVariantArray(Table: TOrmClass;
const FieldName, FormatSqlWhere: RawUtf8;
const BoundsSqlWhere: array of const): variant;
function RetrieveDocVariant(Table: TOrmClass;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const FieldsCsv: RawUtf8): variant;
function RetrieveListObjArray(var ObjArray; Table: TOrmClass;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const FieldsCsv: RawUtf8 = ''): boolean;
procedure AppendListAsJsonArray(Table: TOrmClass;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const OutputFieldName: RawUtf8; W: TOrmWriter;
const FieldsCsv: RawUtf8 = '');
function RTreeMatch(DataTable: TOrmClass;
const DataTableBlobFieldName: RawUtf8; RTreeTable: TOrmRTreeClass;
const DataTableBlobField: RawByteString; var DataID: TIDDynArray): boolean;
function ExecuteList(const Tables: array of TOrmClass;
const SQL: RawUtf8): TOrmTable; virtual;
function ExecuteJson(const Tables: array of TOrmClass;
const SQL: RawUtf8; ForceAjax: boolean = false;
ReturnedRowCount: PPtrInt = nil): RawJson; virtual;
function Execute(const aSql: RawUtf8): boolean; virtual;
function ExecuteFmt(const SqlFormat: RawUtf8;
const Args: array of const): boolean; overload;
function ExecuteFmt(const SqlFormat: RawUtf8;
const Args, Bounds: array of const): boolean; overload;
function UnLock(Table: TOrmClass; aID: TID): boolean; overload; virtual; abstract;
function UnLock(Rec: TOrm): boolean; overload;
function Add(Value: TOrm; SendData: boolean;
ForceID: boolean = false; DoNotAutoComputeFields: boolean = false): TID; overload;
function Add(Value: TOrm; const CustomCsvFields: RawUtf8;
ForceID: boolean = false; DoNotAutoComputeFields: boolean = false): TID; overload;
function Add(Value: TOrm; const CustomFields: TFieldBits;
ForceID: boolean = false; DoNotAutoComputeFields: boolean = false): TID; overload;
function AddWithBlobs(Value: TOrm;
ForceID: boolean = false; DoNotAutoComputeFields: boolean = false): TID; virtual;
function AddSimple(aTable: TOrmClass;
const aSimpleFields: array of const; ForcedID: TID = 0): TID;
function Update(Value: TOrm; const CustomFields: TFieldBits = [];
DoNotAutoComputeFields: boolean = false): boolean; overload; virtual;
function Update(Value: TOrm; const CustomCsvFields: RawUtf8;
DoNotAutoComputeFields: boolean = false): boolean; overload;
function Update(aTable: TOrmClass; aID: TID;
const aSimpleFields: array of const): boolean; overload;
function AddOrUpdate(Value: TOrm; ForceID: boolean = false): TID;
function UpdateField(Table: TOrmClass; ID: TID;
const FieldName: RawUtf8; const FieldValue: array of const): boolean; overload;
function UpdateField(Table: TOrmClass; const WhereFieldName: RawUtf8;
const WhereFieldValue: array of const; const FieldName: RawUtf8;
const FieldValue: array of const): boolean; overload;
function UpdateField(Table: TOrmClass; ID: TID;
const FieldName: RawUtf8; const FieldValue: variant): boolean; overload;
function UpdateField(Table: TOrmClass;
const WhereFieldName: RawUtf8; const WhereFieldValue: variant;
const FieldName: RawUtf8; const FieldValue: variant): boolean; overload;
function UpdateFieldAt(Table: TOrmClass; const IDs: array of TID;
const FieldName: RawUtf8; const FieldValue: variant): boolean;
function UpdateFieldIncrement(Table: TOrmClass; ID: TID;
const FieldName: RawUtf8; Increment: Int64 = 1): boolean;
function RecordCanBeUpdated(Table: TOrmClass; ID: TID;
Action: TOrmEvent; ErrorMsg: PRawUtf8 = nil): boolean; virtual;
function Delete(Table: TOrmClass; ID: TID): boolean; overload; virtual;
function Delete(Table: TOrmClass; const SqlWhere: RawUtf8): boolean; overload; virtual;
function Delete(Table: TOrmClass; const FormatSqlWhere: RawUtf8;
const BoundsSqlWhere: array of const): boolean; overload;
function RetrieveBlob(Table: TOrmClass; aID: TID; const BlobFieldName: RawUtf8;
out BlobData: RawBlob): boolean; overload;
function RetrieveBlob(Table: TOrmClass; aID: TID; const BlobFieldName: RawUtf8;
out BlobStream: TCustomMemoryStream): boolean; overload; virtual;
function UpdateBlob(Table: TOrmClass; aID: TID;
const BlobFieldName: RawUtf8; const BlobData: RawBlob): boolean; overload; virtual;
function UpdateBlob(Table: TOrmClass; aID: TID;
const BlobFieldName: RawUtf8; BlobData: TStream): boolean; overload;
function UpdateBlob(Table: TOrmClass; aID: TID;
const BlobFieldName: RawUtf8; BlobData: pointer; BlobSize: integer): boolean; overload;
function UpdateBlobFields(Value: TOrm): boolean; virtual;
function RetrieveBlobFields(Value: TOrm): boolean; virtual;
function TransactionBegin(aTable: TOrmClass; SessionID: cardinal): boolean; virtual;
function TransactionActiveSession: cardinal;
procedure Commit(SessionID: cardinal; RaiseException: boolean = false); virtual;
procedure RollBack(SessionID: cardinal); virtual;
procedure WriteLock;
{$ifdef HASINLINE}inline;{$endif}
procedure WriteUnLock;
{$ifdef HASINLINE}inline;{$endif}
function BatchSend(Batch: TRestBatch; var Results: TIDDynArray): integer; overload;
function BatchSend(Batch: TRestBatch): integer; overload;
function BatchSend(Table: TOrmClass; var Data: RawUtf8;
var Results: TIDDynArray; ExpectedResultsCount: integer): integer; overload;
function AsyncBatchStart(Table: TOrmClass; SendSeconds: integer;
PendingRowThreshold: integer = 500; AutomaticTransactionPerRow: integer = 1000;
Options: TRestBatchOptions = [boExtendedJson]): boolean;
function AsyncBatchStop(Table: TOrmClass): boolean;
function AsyncBatchAdd(Value: TOrm; SendData: boolean;
ForceID: boolean = false; const CustomFields: TFieldBits = [];
DoNotAutoComputeFields: boolean = false): integer;
function AsyncBatchRawAdd(Table: TOrmClass; const SentData: RawUtf8): integer;
procedure AsyncBatchRawAppend(Table: TOrmClass; SentData: TJsonWriter);
function AsyncBatchUpdate(Value: TOrm; const CustomFields: TFieldBits = [];
DoNotAutoComputeFields: boolean = false): integer;
function AsyncBatchDelete(Table: TOrmClass; ID: TID): integer;
function Model: TOrmModel;
{$ifdef HASINLINE}inline;{$endif}
function Cache: TOrmCache;
function CacheOrNil: TOrmCache;
{$ifdef HASINLINE}inline;{$endif}
function CacheWorthItForTable(aTableIndex: cardinal): boolean; virtual;
function LogClass: TSynLogClass;
{$ifdef HASINLINE}inline;{$endif}
function LogFamily: TSynLogFamily;
{$ifdef HASINLINE}inline;{$endif}
procedure InternalLog(const Text: RawUtf8; Level: TSynLogLevel); overload;
{$ifdef HASINLINE}inline;{$endif}
procedure InternalLog(const Format: RawUtf8; const Args: array of const;
Level: TSynLogLevel = sllTrace); overload;
function GetServerTimestamp: TTimeLog;
{$ifdef HASINLINE}inline;{$endif}
function GetCurrentSessionUserID: TID; virtual;
end;
{$M-}
/// a dynamic array of TRestOrm instances
TRestOrmDynArray = array of TRestOrm;
/// a dynamic array of TRestOrm instances, owning the instances
TRestOrmObjArray = array of TRestOrm;
{ ************ TOrmTableWritable Read/Write TOrmTable }
type
/// store a writable ORM result table, optionally read from a JSON message
// - in respect to TOrmTableJson, this class allows to modify field values,
// and add some new fields on the fly, even joined from another TOrmTable
TOrmTableWritable = class(TOrmTableJson)
protected
fUpdatedValues: TRawUtf8DynArray;
fUpdatedValuesCount: integer;
fUpdatedRowsCount: integer;
fUpdatedValuesInterning: TRawUtf8Interning;
fUpdatedRows, fUpdatedRowsFields: TIntegerDynArray;
fNoUpdateTracking: boolean;
public
/// modify a field value in-place, using a RawUtf8 text value
procedure Update(Row, Field: PtrInt; const Value: RawUtf8); overload;
/// modify a field value in-place, using a RawUtf8 text value
procedure Update(Row: PtrInt; const FieldName, Value: RawUtf8); overload;
/// modify a field value in-place, using a variant value
procedure Update(Row, Field: PtrInt; const Value: variant); overload;
/// modify a field value in-place, using a variant value
procedure Update(Row: PtrInt; const FieldName: RawUtf8;
const Value: variant); overload;
/// define a new field to be stored in this table
// - returns the internal index of the newly created field
function AddField(const FieldName: RawUtf8): integer; overload;
/// define a new field to be stored in this table
// - returns the internal index of the newly created field
function AddField(const FieldName: RawUtf8; FieldType: TOrmFieldType;
FieldTypeInfo: pointer = nil; FieldSize: integer = -1): integer; overload;
/// define a TOrm property to be stored as new table field
// - returns the internal index of the newly created field
function AddField(const FieldName: RawUtf8; FieldTable: TOrmClass;
const FieldTableName: RawUtf8 = ''): integer; overload;
/// append/merge data from a secondary TOrmTable
// - you should specify the primary keys on which the data rows are merged
// - merged data will point to From.fResults[] content: so the From instance
// should remain available as long as you use this TOrmTableWritable
// - warning: will call From.SortFields(FromKeyField) for faster process
procedure Join(From: TOrmTable; const FromKeyField, KeyField: RawUtf8);
/// append tracked Update() values to a BATCH process
// - will only work if this table has a single associated TOrmClass
function UpdatesToBatch(Batch: TRestBatch;
aServerTimeStamp: TTimeLog = 0): integer;
/// generate a JSON of tracked Update() values
// - will only work if this table has a single associated TOrmClass
// - BATCH-compatible JSON is possible if boOnlyObjects is not part
// of the supplied options, e.g. as [boExtendedJson] - in this context any
// TModTime field will be processed; set aServerTimeStamp e.g. from
// TRestClientUri.GetServerTimestamp, if TimeLogNowUtc is not enough
function UpdatesToJson(aOptions: TRestBatchOptions = [boOnlyObjects];
aServerTimeStamp: TTimeLog = 0): RawJson;
/// optionaly de-duplicate Update() values
property UpdatedValuesInterning: TRawUtf8Interning
read fUpdatedValuesInterning write fUpdatedValuesInterning;
/// how many values have been written via Update() overloaded methods
// - is not updated if UpdatedValuesInterning was defined
property UpdatedValuesCount: integer
read fUpdatedValuesCount;
/// the rows numbers (1..RowCount) which have been modified by Update()
// - Join() and AddField() are not tracked by this list - just Update()
// - the numbers are stored in increasing order
// - track the modified rows using UpdatedRows[0..UpdatedRowsCount - 1] and
// UpdatedRowsFields[0..UpdatedRowsCount - 1] - unless NoUpdateTracking was set
property UpdatedRows: TIntegerDynArray
read fUpdatedRows;
/// how many rows (0..RowCount) have been modified by Update()
property UpdatedRowsCount: integer
read fUpdatedRowsCount;
/// 32-bit field bits which have been modified by Update()
// - Join() and AddField() are not tracked by this list - just Update()
// - follow UpdatedRows[0..UpdatedRowsCount - 1] row numbers
// - if more than 32 field indexes were updated, contains 0
property UpdatedRowsFields: TIntegerDynArray
read fUpdatedRowsFields;
/// if UpdatedRows/UpdatedRowsFields should not be tracked during Update()
property NoUpdateTracking: boolean
read fNoUpdateTracking write fNoUpdateTracking;
end;
implementation
{ ************ TRestOrm Parent Class for abstract REST client/server }
{ TRestOrm }
// ------- TRestOrm main methods
constructor TRestOrm.Create(aRest: TRest);
begin
inherited Create;
fTempJsonWriter := TJsonWriter.CreateOwnedStream(16384, {nosharedstream=}true);
if aRest = nil then
exit;
fRest := aRest;
fModel := fRest.Model;
fRest.SetOrmInstance(self); // inject this ORM instance to the main TRest
end;
constructor TRestOrm.CreateWithoutRest(aModel: TOrmModel);
begin
fModel := aModel;
Create(nil);
end;
destructor TRestOrm.Destroy;
begin
FreeAndNilSafe(fCache);
inherited Destroy;
if (fModel <> nil) and
(fModel.Owner = self) then
// make sure we are the Owner (TRestStorage has fModel<>nil e.g.)
FreeAndNilSafe(fModel);
fTempJsonWriter.Free;
end;
function TRestOrm.SqlComputeForSelect(TableModelIndex: integer; Table: TOrmClass;
const FieldNames, WhereClause: RawUtf8): RawUtf8;
begin
result := '';
if (self = nil) or
(Table = nil) then
exit;
if FieldNames = '' then
result := fModel.TableProps[TableModelIndex].
SqlFromSelectWhere('*', WhereClause)
else
with Table.OrmProps do
if FieldNames = '*' then
result := SqlFromSelect(
SqlTableName, SqlTableRetrieveAllFields, WhereClause, '')
else if (PosExChar(',', FieldNames) = 0) and
(PosExChar('(', FieldNames) = 0) and
not IsFieldName(pointer(FieldNames)) then
// prevent SQL error
result := ''
else
result := SqlFromSelect(SqlTableName, FieldNames, WhereClause, '');
end;
function TRestOrm.AcquireJsonWriter(var tmp: TTextWriterStackBuffer): TJsonWriter;
begin
if fTempJsonWriterLock.TryLock then
result := fTempJsonWriter
else
result := TJsonWriter.CreateOwnedStream(tmp);
end;
procedure TRestOrm.ReleaseJsonWriter(WR: TJsonWriter);
begin
if WR = fTempJsonWriter then
begin
WR.CancelAllAsNew;
fTempJsonWriterLock.UnLock;
end
else
WR.Free;
end;
procedure TRestOrm.GetJsonValue(Value: TOrm; withID: boolean;
Occasion: TOrmOccasion; var Json: RawUtf8);
begin
GetJsonValue(
Value, withID, Value.Orm.SimpleFieldsBits[Occasion], Json);
end;
procedure TRestOrm.GetJsonValue(Value: TOrm; withID: boolean;
const Fields: TFieldBits; out Json: RawUtf8);
var
WR: TJsonWriter;
tmp: TTextWriterStackBuffer;
begin
// faster than Json := Value.GetJsonValues(true, withID, Fields);
WR := AcquireJsonWriter(tmp);
{$ifdef HASFASTTRYFINALLY}
try
{$else}
begin
{$endif HASFASTTRYFINALLY}
Value.AppendAsJsonObject(WR, Fields, withID);
WR.SetText(Json);
{$ifdef HASFASTTRYFINALLY}
finally
{$endif HASFASTTRYFINALLY}
ReleaseJsonWriter(WR);
end;
end;
procedure TRestOrm.GetJsonValuesForAdd(TableIndex: integer; Value: TOrm;
ForceID, DoNotAutoComputeFields, WithBlobs: boolean;
CustomFields: PFieldBits; var result: RawUtf8);
var
fields: TFieldBits;
props: TOrmProperties;
begin
if not DoNotAutoComputeFields then // update TModTime/TCreateTime fields
Value.ComputeFieldsBeforeWrite(self, oeAdd);
if fModel.TableProps[TableIndex].Kind in INSERT_WITH_ID then
ForceID := true;
if (fModel.IDGenerator <> nil) and
(fModel.IDGenerator[TableIndex] <> nil) then
begin
if (Value.IDValue = 0) or
not ForceID then
begin
Value.IDValue := fModel.IDGenerator[TableIndex].ComputeNew;
ForceID := true;
end;
end
else if Value.IDValue = 0 then
ForceID := false;
props := Value.Orm;
if CustomFields <> nil then
if DoNotAutoComputeFields then
fields := CustomFields^ * props.CopiableFieldsBits
else
fields := CustomFields^ * props.CopiableFieldsBits + props.ComputeBeforeAddFieldsBits
else if WithBlobs then
fields := props.CopiableFieldsBits
else
fields := props.SimpleFieldsBits[ooInsert];
if not ForceID and
IsZero(fields) then
result := ''
else
GetJsonValue(Value, ForceID, fields, result);
end;
function TRestOrm.InternalAdd(Value: TOrm; SendData: boolean;
CustomFields: PFieldBits; ForceID, DoNotAutoComputeFields: boolean): TID;
var
json: RawUtf8;
t: integer;
begin
if Value = nil then
begin
result := 0;
exit;
end;
t := fModel.GetTableIndexExisting(POrmClass(Value)^);
if SendData then
GetJsonValuesForAdd(t, Value, ForceID, DoNotAutoComputeFields,
false, CustomFields, json)
else
json := '';
// on success, returns the new RowID value; on error, returns 0
fRest.AcquireExecution[execOrmWrite].Safe.Lock;
try
// may be within a batch in another thread -> use execOrmWrite lock
result := EngineAdd(t, json); // will call static if necessary
finally
fRest.AcquireExecution[execOrmWrite].Safe.UnLock;
end;
// on success, Value.ID is updated with the new RowID
Value.IDValue := result;
if (result <> 0) and
SendData then
fCache.NotifyAllFields(t, Value);
end;
// ------- IRestOrm interface implementation methods
function TRestOrm.Model: TOrmModel;
begin
result := fModel;
end;
function TRestOrm.CacheOrNil: TOrmCache;
begin
result := fCache;
end;
function TRestOrm.LogClass: TSynLogClass;
begin
result := fRest.LogClass;
end;
function TRestOrm.LogFamily: TSynLogFamily;
begin
result := fRest.LogFamily;
end;
procedure TRestOrm.InternalLog(const Text: RawUtf8; Level: TSynLogLevel);
begin
fRest.InternalLog(Text, Level);
end;
function TRestOrm.GetServerTimestamp: TTimeLog;
begin
result := fRest.GetServerTimeStamp(0);
end;
procedure TRestOrm.WriteLock;
begin
fRest.AcquireExecution[execOrmWrite].Safe.Lock;
end;
procedure TRestOrm.WriteUnLock;
begin
fRest.AcquireExecution[execOrmWrite].Safe.UnLock;
end;
{$ifdef ORMGENERICS}
function TRestOrm.RetrieveIList(T: TOrmClass; var IList;
const FieldsCsv: RawUtf8): boolean;
begin
result := RetrieveIList(T, IList, '', [], FieldsCsv);
end;
function TRestOrm.RetrieveIList(T: TOrmClass; var IList;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const;
const FieldsCsv: RawUtf8): boolean;
var
table: TOrmTable;
begin
result := false;
IInterface(IList) := nil;
if self = nil then
exit;
table := MultiFieldValues(T, FieldsCsv, FormatSqlWhere, BoundsSqlWhere);
if table <> nil then
try
table.ToNewIList(T, IList);
result := true;
finally
table.Free;
end;
end;
{$endif ORMGENERICS}
function TRestOrm.TableRowCount(Table: TOrmClass): Int64;
var
T: TOrmTable;
begin
if (self = nil) or
(Table = nil) then
T := nil
else
T := ExecuteList([Table], 'SELECT Count(*) FROM ' +
Table.OrmProps.SqlTableName);
if T <> nil then
try
result := T.GetAsInt64(1, 0);
finally
T.Free;
end
else
result := -1;
end;
function TRestOrm.TableHasRows(Table: TOrmClass): boolean;
var
T: TOrmTable;
begin
if (self = nil) or
(Table = nil) then
T := nil
else
T := ExecuteList([Table], 'SELECT RowID FROM ' +
Table.OrmProps.SqlTableName + ' LIMIT 1');
if T <> nil then
try
result := T.RowCount > 0;
finally
T.Free;
end
else
result := false;
end;
function TRestOrm.TableMaxID(Table: TOrmClass): TID;
var
T: TOrmTable;
begin
if (self = nil) or
(Table = nil) then
T := nil
else
T := ExecuteList([Table], 'SELECT max(RowID) FROM ' +
Table.OrmProps.SqlTableName);
if T <> nil then
try
result := T.GetAsInt64(1, 0);
finally
T.Free;
end
else
result := -1;
end;
function TRestOrm.MemberExists(Table: TOrmClass; ID: TID): boolean;
var
t: PtrInt;
begin
t := fModel.GetTableIndexExisting(Table);
if fCache.Exists(t, ID) then
result := true
else
result := EngineRetrieve(t, ID) <> ''; // try from DB
end;
function TRestOrm.OneFieldValue(Table: TOrmClass; const FieldName,
WhereClause: RawUtf8): RawUtf8;
var
res: array[0..0] of RawUtf8;
begin
if MultiFieldValue(Table, [FieldName], res, WhereClause) then
result := res[0]
else
result := '';
end;
function TRestOrm.OneFieldValueInt64(Table: TOrmClass; const FieldName,
WhereClause: RawUtf8; Default: Int64): Int64;
var
res: array[0..0] of RawUtf8;
begin
if not MultiFieldValue(Table, [FieldName], res, WhereClause) or
not ToInt64(res[0], result) then
result := Default;
end;
function TRestOrm.OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
const FormatSqlWhere: RawUtf8; const BoundsSqlWhere: array of const): RawUtf8;
begin
result := OneFieldValue(Table, FieldName,
FormatSql(FormatSqlWhere, [], BoundsSqlWhere));
end;
function TRestOrm.OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
const WhereClauseFmt: RawUtf8; const Args, Bounds: array of const): RawUtf8;
begin
result := OneFieldValue(Table, FieldName,
FormatSql(WhereClauseFmt, Args, Bounds));
end;
function TRestOrm.OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
const WhereClauseFmt: RawUtf8; const Args, Bounds: array of const;
out Data: Int64): boolean;
var
res: array[0..0] of RawUtf8;
err: integer;
where: RawUtf8;
begin
result := false;
where := FormatSql(WhereClauseFmt, Args, Bounds);
if MultiFieldValue(Table, [FieldName], res, where) then
if res[0] <> '' then
begin
Data := GetInt64(pointer(res[0]), err);
if err = 0 then
result := true;
end;
end;
function TRestOrm.OneFieldValue(Table: TOrmClass; const FieldName: RawUtf8;
WhereID: TID): RawUtf8;
var
res: array[0..0] of RawUtf8;
begin
if (WhereID > 0) and
MultiFieldValue(Table, [FieldName], res,
'RowID=:(' + Int64ToUtf8(WhereID) + '):') then
result := res[0]
else
result := '';
end;
function TRestOrm.MultiFieldValue(Table: TOrmClass;
const FieldName: array of RawUtf8; var FieldValue: array of RawUtf8;
const WhereClause: RawUtf8): boolean;
var
sql, where: RawUtf8;
v, f: PtrInt;
T: TOrmTable;
begin
result := false;
if (self <> nil) and
(Table <> nil) and
(high(FieldName) = high(FieldValue)) then
with Table.OrmProps do
begin
where := SqlTableName + SqlFromWhere(WhereClause);