-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathmormot.orm.storage.pas
5533 lines (5185 loc) · 195 KB
/
mormot.orm.storage.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 Server side JSON/Binary Storage
// - 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.storage;
{
*****************************************************************************
Server-Side Storage Process using JSON or Binary Persistence
- Virtual Table ORM Support
- TRestStorage Abstract Class for ORM/REST Storage
- TRestStorageInMemory as Stand-Alone JSON/Binary Storage
- TOrmVirtualTableJson/TOrmVirtualTableBinary Virtual Tables
- TRestStorageRemote for CRUD Redirection
- TRestStorageShard as Abstract Sharded Storage Engine
- TRestStorageMulti as Abstract Multi-User Storage Engine
*****************************************************************************
}
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.core.data,
mormot.core.rtti,
mormot.core.json,
mormot.core.threads,
mormot.crypt.core,
mormot.crypt.jwt,
mormot.core.perf,
mormot.crypt.secure,
mormot.core.log,
mormot.core.interfaces,
mormot.orm.base,
mormot.orm.core,
mormot.orm.rest,
mormot.orm.client,
mormot.orm.server,
mormot.soa.core,
mormot.db.core,
mormot.rest.core,
mormot.rest.client;
// most types are defined as a single "type" statement due to classes coupling
type
// some forward class definitions
TRestStorage = class;
TOrmVirtualTable = class;
TRestStorageInMemory = class;
{ ************ Virtual Table ORM Support }
/// Record associated to a Virtual Table implemented in Delphi, with ID
// forced at INSERT
// - will use TOrmVirtualTableModule / TOrmVirtualTable / TOrmVirtualTableCursor
// classes for a generic Virtual table mechanism on the Server side
// - call Model.VirtualTableRegister() before TRestOrmServer.Create on the
// Server side (not needed for Client) to associate such a record with a
// particular Virtual Table module, otherwise an exception will be raised:
// ! Model.VirtualTableRegister(TOrmDali1,TOrmVirtualTableJson);
TOrmVirtualTableForcedID = class(TOrmVirtual);
/// Record associated to Virtual Table implemented in Delphi, with ID
// generated automatically at INSERT
// - will use TOrmVirtualTableModule / TOrmVirtualTable / TOrmVirtualTableCursor
// classes for a generic Virtual table mechanism
// - call Model.VirtualTableRegister() before TRestOrmServer.Create on the
// Server side (not needed for Client) to associate such a record with a
// particular Virtual Table module, otherwise an exception will be raised:
// ! Model.VirtualTableRegister(TOrmDali1,TOrmVirtualTableJson);
TOrmVirtualTableAutoID = class(TOrmVirtual);
/// class-reference type (metaclass) of our abstract table storage
// - may be e.g. TRestStorageInMemory, TRestStorageInMemoryExternal,
// TRestStorageExternal or TRestStorageMongoDB
TRestStorageClass = class of TRestStorage;
/// class-reference type (metaclass) of a virtual table implementation
TOrmVirtualTableClass = class of TOrmVirtualTable;
/// a WHERE constraint as set by the TOrmVirtualTable.Prepare() method
TOrmVirtualTablePreparedConstraint = packed record
/// Column on left-hand side of constraint
// - The first column of the virtual table is column 0
// - The RowID of the virtual table is column -1
// - Hidden columns are counted when determining the column index
// - if this field contains VIRTUAL_TABLE_IGNORE_COLUMN (-2), TOrmVirtualTable.
// Prepare() should ignore this entry
Column: integer;
/// The associated expression
// - TOrmVirtualTable.Prepare() must set Value.VType to not ftUnknown
// (e.g. to ftNull), if an expression is expected at vt_BestIndex() call
// - TOrmVirtualTableCursor.Search() will receive an expression value,
// to be retrieved e.g. via sqlite3_value_*() functions
Value: TSqlVar;
/// Constraint operator to be transmitted at SQL level
// - MATCH keyword is parsed into soBeginWith, and should be handled as
// soBeginWith, soContains or soSoundsLike* according to the effective
// expression text value ('text*', '%text'...)
Operation: TSqlCompareOperator;
/// If true, the constraint is assumed to be fully handled
// by the virtual table and is not checked again by SQLite
// - By default (OmitCheck=false), the SQLite core double checks all
// constraints on each row of the virtual table that it receives
// - TOrmVirtualTable.Prepare() can set this property to true
OmitCheck: boolean;
end;
POrmVirtualTablePreparedConstraint = ^TOrmVirtualTablePreparedConstraint;
/// an ORDER BY clause as set by the TOrmVirtualTable.Prepare() method
// - warning: this structure should match exactly TSqlite3IndexOrderBy as
// defined in mormot.db.raw.sqlite3
TOrmVirtualTablePreparedOrderBy = record
/// Column number
// - The first column of the virtual table is column 0
// - The RowID of the virtual table is column -1
// - Hidden columns are counted when determining the column index.
Column: integer;
/// True for DESCending order, false for ASCending order.
Desc: boolean;
end;
/// abstract planning execution of a query, as set by TOrmVirtualTable.Prepare
TOrmVirtualTablePreparedCost = (
costFullScan,
costScanWhere,
costSecondaryIndex,
costPrimaryIndex);
/// the WHERE and ORDER BY statements as set by TOrmVirtualTable.Prepare
// - Where[] and OrderBy[] are fixed sized arrays, for fast and easy code
{$ifdef USERECORDWITHMETHODS}
TOrmVirtualTablePrepared = record
{$else}
TOrmVirtualTablePrepared = object
{$endif USERECORDWITHMETHODS}
public
/// number of WHERE statement parameters in Where[] array
WhereCount: integer;
/// numver of ORDER BY statement parameters in OrderBy[]
OrderByCount: integer;
/// if true, the ORDER BY statement is assumed to be fully handled
// by the virtual table and is not checked again by SQLite
// - By default (OmitOrderBy=false), the SQLite core sort all rows of the
// virtual table that it receives according in order
OmitOrderBy: boolean;
/// Estimated cost of using this prepared index
// - SQLite uses this value to make a choice between several calls to
// the TOrmVirtualTable.Prepare() method with several expressions
EstimatedCost: TOrmVirtualTablePreparedCost;
/// Estimated number of rows of using this prepared index
// - does make sense only if EstimatedCost=costFullScan
// - SQLite uses this value to make a choice between several calls to
// the TOrmVirtualTable.Prepare() method with several expressions
// - is used only starting with SQLite 3.8.2
EstimatedRows: Int64;
/// WHERE statement parameters, in TOrmVirtualTableCursor.Search() order
Where: array[0 .. MAX_SQLFIELDS - 1] of TOrmVirtualTablePreparedConstraint;
/// ORDER BY statement parameters
OrderBy: array[0 .. MAX_SQLFIELDS - 1] of TOrmVirtualTablePreparedOrderBy;
/// returns TRUE if there is only one ID=? statement in this search
function IsWhereIDEquals(CalledFromPrepare: boolean): boolean;
{$ifdef HASINLINE}inline;{$endif}
/// returns TRUE if there is only one FieldName=? statement in this search
function IsWhereOneFieldEquals: boolean;
{$ifdef HASINLINE}inline;{$endif}
end;
POrmVirtualTablePrepared = ^TOrmVirtualTablePrepared;
TOrmVirtualTableCursor = class;
/// class-reference type (metaclass) of a cursor on an abstract Virtual Table
TOrmVirtualTableCursorClass = class of TOrmVirtualTableCursor;
/// the possible features of a Virtual Table
// - vtWrite is to be set if the table is not Read/Only
// - vtTransaction if handles vttBegin, vttSync, vttCommit, vttRollBack
// - vtSavePoint if handles vttSavePoint, vttRelease, vttRollBackTo
// - vtWhereIDPrepared if the ID=? WHERE statement will be handled in
// TOrmVirtualTableCursor.Search()
TOrmVirtualTableFeature = (
vtWrite,
vtTransaction,
vtSavePoint,
vtWhereIDPrepared);
/// a set of features of a Virtual Table
TOrmVirtualTableFeatures = set of TOrmVirtualTableFeature;
/// used to store and handle the main specifications of a TOrmVirtualTableModule
TVirtualTableModuleProperties = record
/// a set of features of a Virtual Table
Features: TOrmVirtualTableFeatures;
/// the associated cursor class
CursorClass: TOrmVirtualTableCursorClass;
/// the associated TOrm class
// - used to retrieve the field structure with all collations
RecordClass: TOrmClass;
/// the associated TRestStorage class used for storage
// - is e.g. TRestStorageInMemory for TOrmVirtualTableJson,
// TRestStorageExternal for TOrmVirtualTableExternal, or nil for
// TOrmVirtualTableLog
StaticClass: TRestStorageClass;
/// can be used to customize the extension of the filename
// - the '.' is not to be included
FileExtension: TFileName;
end;
/// parent class able to define a Virtual Table module
// - in order to implement a new Virtual Table type, you'll have to define a so
// called "Module" to handle the fields and data access and an associated
// TOrmVirtualTableCursorClass for handling the SELECT statements
// - for our framework, the SQLite3 unit will inherit from this class to define
// a TOrmVirtualTableModuleSQLite3 class, which will register the associated
// virtual table definition into a SQLite3 connection, on the server side
// - children should override abstract methods in order to implement the
// association with the database engine itself
TOrmVirtualTableModule = class
protected
fModuleName: RawUtf8;
fTableClass: TOrmVirtualTableClass;
fServer: TRestOrmServer;
fFeatures: TVirtualTableModuleProperties;
fFilePath: TFileName;
public
/// create the Virtual Table instance according to the supplied class
// - inherited constructors may register the Virtual Table to the specified
// database connection
constructor Create(aTableClass: TOrmVirtualTableClass;
aServer: TRestOrmServer); virtual;
/// retrieve the file name to be used for a specific Virtual Table
// - returns by default a file located in the executable folder, with the
// table name as file name, and module name as extension
function FileName(const aTableName: RawUtf8): TFileName; virtual;
/// the Virtual Table module features
property Features: TOrmVirtualTableFeatures
read fFeatures.Features;
/// the associated virtual table class
property TableClass: TOrmVirtualTableClass
read fTableClass;
/// the associated virtual table cursor class
property CursorClass: TOrmVirtualTableCursorClass
read fFeatures.CursorClass;
/// the associated TRestStorage class used for storage
// - e.g. returns TRestStorageInMemory for TOrmVirtualTableJson,
// or TRestStorageExternal for TOrmVirtualTableExternal, or
// either nil for TOrmVirtualTableLog
property StaticClass: TRestStorageClass
read fFeatures.StaticClass;
/// the associated TOrm class
// - is mostly nil, e.g. for TOrmVirtualTableJson
// - used to retrieve the field structure for TOrmVirtualTableLog e.g.
property RecordClass: TOrmClass
read fFeatures.RecordClass;
/// the extension of the filename (without any left '.')
property FileExtension: TFileName
read fFeatures.FileExtension;
/// the full path to be used for the filename
// - is '' by default, i.e. will use the executable path
// - you can specify here a custom path, which will be used by the FileName
// method to retrieve the .json/.data full file
property FilePath: TFileName
read fFilePath write fFilePath;
/// the associated Server instance
// - may be nil, in case of direct access to the virtual table
property Server: TRestOrmServer
read fServer;
/// the corresponding module name
property ModuleName: RawUtf8
read fModuleName;
end;
/// the available transaction levels
TOrmVirtualTableTransaction = (
vttBegin,
vttSync,
vttCommit,
vttRollBack,
vttSavePoint,
vttRelease,
vttRollBackTo);
/// abstract class able to access a Virtual Table content
// - override the Prepare/Structure abstract virtual methods for reading
// access to the virtual table content
// - you can optionaly override Drop/Delete/Insert/Update/Rename/Transaction
// virtual methods to allow content writing to the virtual table
// - the same virtual table mechanism can be used with several database module,
// with diverse database engines
TOrmVirtualTable = class
protected
fModule: TOrmVirtualTableModule;
fTableName: RawUtf8;
fStatic: TRestOrm;
fStaticStorage: TRestStorage;
fStaticTable: TOrmClass;
fStaticTableIndex: integer;
public
/// create the virtual table access instance
// - the created instance will be released when the virtual table will be
// disconnected from the DB connection (e.g. xDisconnect method for SQLite3)
// - shall raise an exception in case of invalid parameters (e.g. if the
// supplied module is not associated to a TRestOrmServer instance)
// - aTableName will be checked against the current aModule.Server.Model
// to retrieve the corresponding TOrmVirtualTableAutoID class and
// create any associated Static: TRestStorage instance
constructor Create(aModule: TOrmVirtualTableModule; const aTableName: RawUtf8;
FieldCount: integer; Fields: PPUtf8CharArray); virtual;
/// release the associated memory, especially the Static instance
destructor Destroy; override;
/// retrieve the corresponding module name
// - will use the class name, triming any T/TSql/TSqlVirtual/TOrmVirtualTable*
// - when the class is instanciated, it will be faster to retrieve the same
// value via Module.ModuleName
class function ModuleName: RawUtf8;
/// a generic method to get a 'CREATE TABLE' structure from a supplied
// TOrm class
// - is called e.g. by the Structure method
class function StructureFromClass(aClass: TOrmClass;
const aTableName: RawUtf8): RawUtf8;
/// the associated Virtual Table module
property Module: TOrmVirtualTableModule
read fModule;
/// the name of the Virtual Table, as specified following the TABLE keyword
// in the CREATE VIRTUAL TABLE statement
property TableName: RawUtf8
read fTableName;
public { virtual methods to be overridden }
/// should return the main specifications of the associated TOrmVirtualTableModule
class procedure GetTableModuleProperties(
var aProperties: TVirtualTableModuleProperties); virtual; abstract;
/// called to determine the best way to access the virtual table
// - will prepare the request for TOrmVirtualTableCursor.Search()
// - in Where[], Expr must be set to not 0 if needed for Search method,
// and OmitCheck to true if double check is not necessary
// - OmitOrderBy must be set to true if double sort is not necessary
// - EstimatedCost and EstimatedRows should receive the estimated cost
// - default implementation will let the DB engine perform the search,
// and prepare for ID=? statement if vtWhereIDPrepared was set
function Prepare(var Prepared: TOrmVirtualTablePrepared): boolean; virtual;
/// should retrieve the format (the names and datatypes of the columns) of
// the virtual table, as expected by sqlite3_declare_vtab()
// - default implementation is to retrieve the structure for the associated
// Module.RecordClass property (as set by GetTableModuleProperties) or
// the Static.StoredClass: in both cases, column numbering will follow
// the TOrm published field order (TOrm.Orm.Fields[])
function Structure: RawUtf8; virtual;
/// called when a DROP TABLE statement is executed against the virtual table
// - should return true on success, false otherwise
// - does nothing by default, and returns false, i.e. always fails
function Drop: boolean; virtual;
/// called to delete a virtual table row
// - should return true on success, false otherwise
// - does nothing by default, and returns false, i.e. always fails
function Delete(aRowID: Int64): boolean; virtual;
/// called to insert a virtual table row content from an array of TSqlVar
// - should return true on success, false otherwise
// - should return the just created row ID in insertedRowID on success
// - does nothing by default, and returns false, i.e. always fails
function Insert(aRowID: Int64; var Values: TSqlVarDynArray;
out insertedRowID: Int64): boolean; virtual;
/// called to update a virtual table row content from an array of TSqlVar
// - should return true on success, false otherwise
// - does nothing by default, and returns false, i.e. always fails
function Update(oldRowID, newRowID: Int64;
var Values: TSqlVarDynArray): boolean; virtual;
/// called to begin a transaction to the virtual table row
// - do nothing by default, and returns false in case of RollBack/RollBackto
// - aSavePoint is used for vttSavePoint, vttRelease and vttRollBackTo only
// - note that if you don't nest your writing within a transaction, SQLite
// will call vttCommit for each INSERT/UPDATE/DELETE, just like a regular
// SQLite database - it could make bad written code slow even with Virtual
// Tables
function Transaction(aState: TOrmVirtualTableTransaction;
aSavePoint: integer): boolean; virtual;
/// called to rename the virtual table
// - by default, returns false, i.e. always fails
function Rename(const NewName: RawUtf8): boolean; virtual;
/// the associated virtual table storage instance
// - can be e.g. a TRestStorageInMemory for TOrmVirtualTableJson,
// or a TRestStorageExternal for TOrmVirtualTableExternal, or nil
// for TOrmVirtualTableLog
property Static: TRestOrm
read fStatic;
/// the associated virtual table storage instance, if is a TRestStorage
property StaticStorage: TRestStorage
read fStaticStorage;
/// the associated virtual table storage table
property StaticTable: TOrmClass
read fStaticTable;
/// the associated virtual table storage index in its Model.Tables[] array
property StaticTableIndex: integer
read fStaticTableIndex;
end;
/// abstract class able to define a Virtual Table cursor
// - override the Search/HasData/Column/Next abstract virtual methods to
// implement the search process
TOrmVirtualTableCursor = class
protected
fTable: TOrmVirtualTable;
/// used internally between two Column() method calls for GetFieldSqlVar()
fColumnTemp: RawByteString;
/// easy set a TSqlVar content for the Column() method
procedure SetColumn(var aResult: TSqlVar; aValue: Int64); overload;
{$ifdef HASINLINE}inline;{$endif}
procedure SetColumn(var aResult: TSqlVar; const aValue: double); overload;
{$ifdef HASINLINE}inline;{$endif}
procedure SetColumn(var aResult: TSqlVar; const aValue: RawUtf8); overload;
{$ifdef HASINLINE}inline;{$endif}
procedure SetColumn(var aResult: TSqlVar; aValue: PUtf8Char; aValueLength: integer); overload;
{$ifdef HASINLINE}inline;{$endif}
procedure SetColumnBlob(var aResult: TSqlVar; aValue: pointer; aValueLength: integer);
{$ifdef HASINLINE}inline;{$endif}
procedure SetColumnDate(var aResult: TSqlVar; const aValue: TDateTime;
aWithMS: boolean); {$ifdef HASINLINE}inline;{$endif}
procedure SetColumnCurr64(var aResult: TSqlVar; aValue64: PInt64);
{$ifdef HASINLINE}inline;{$endif}
public
/// create the cursor instance
// - it will be destroyed when by the DB engine (e.g. via xClose in SQLite3)
constructor Create(aTable: TOrmVirtualTable); virtual;
/// the associated Virtual Table class instance
property Table: TOrmVirtualTable
read fTable;
public { abstract methods to be overridden }
/// called to begin a search in the virtual table
// - the TOrmVirtualTablePrepared parameters were set by
// TOrmVirtualTable.Prepare and will contain both WHERE and ORDER BY statements
// (retrieved e.g. by x_BestIndex() from a TSqlite3IndexInfo structure)
// - Prepared will contain all prepared constraints and the corresponding
// expressions in the Where[].Value field
// - should move cursor to first 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 Search(var Prepared: TOrmVirtualTablePrepared): boolean; virtual; abstract;
/// 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; virtual; abstract;
/// called to retrieve a column value of the current data row into a TSqlVar
// - if aColumn=-1, should return the row ID as varInt64 into aResult
// - should return false in case of an error, true on success
function Column(aColumn: integer; var aResult: TSqlVar): boolean; virtual; abstract;
/// 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; virtual; abstract;
end;
/// A generic Virtual Table cursor associated to Current/Max index properties
TOrmVirtualTableCursorIndex = class(TOrmVirtualTableCursor)
protected
fCurrent: integer;
fMax: integer;
public
/// called after Search() to check if there is data to be retrieved
// - will return false if reached the end of matching data, according to
// the fCurrent/fMax protected properties values
function HasData: boolean; override;
/// called to go to the next 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)
// - will check the fCurrent/fMax protected properties values
function Next: boolean; override;
/// called to begin a search in the virtual table
// - this no-op version will mark EOF, i.e. fCurrent=0 and fMax=-1
function Search(var Prepared: TOrmVirtualTablePrepared): boolean; override;
end;
{ ************ TRestStorage Abstract Class for ORM/REST Storage }
/// exception raised during ORM/REST Storage process
ERestStorage = class(EOrmException);
/// REST class with direct access to an external database engine
// - you can set an alternate per-table database engine by using this class
// - this abstract class is to be overridden with a proper implementation
// (e.g. TRestStorageInMemory in this unit, or TRestStorageExternal
// from mormot.orm.sql unit, or TRestStorageMongoDB from
// mormot.orm.mongodb.pas unit)
TRestStorage = class(TRestOrm)
protected
fStoredClass: TOrmClass;
fStoredClassProps: TOrmModelProperties;
fStoredClassRecordProps: TOrmProperties;
fStoredClassMapping: POrmMapping;
fStorageLockShouldIncreaseOwnerInternalState: boolean;
fModified: boolean;
fOutInternalStateForcedRefresh: boolean;
{$ifdef DEBUGSTORAGELOCK}
fStorageSafeCount: integer;
{$endif DEBUGSTORAGELOCK}
fOwner: TRestOrmServer;
fStorageVirtual: TOrmVirtualTable;
fBasicSqlCount: RawUtf8;
fBasicSqlHasRows: array[boolean] of RawUtf8;
fStorageSafe: TOSLock;
fTempBuffer: PTextWriterStackBuffer;
procedure RecordVersionFieldHandle(Occasion: TOrmOccasion;
var Decoder: TJsonObjectDecoder);
function GetStoredClassName: RawUtf8;
public
/// initialize the abstract storage data
constructor Create(aClass: TOrmClass; aServer: TRestOrmServer); reintroduce; virtual;
/// finalize the storage instance
destructor Destroy; override;
/// should be called before any access to the storage content
// - and protected with a try ... finally StorageUnLock; end section
procedure StorageLock(WillModifyContent: boolean
{$ifdef DEBUGSTORAGELOCK}; const msg: shortstring{$endif}); virtual;
/// should be called after any StorageLock-protected access to the content
// - e.g. protected with a try ... finally StorageUnLock; end section
procedure StorageUnLock;
{$ifndef DEBUGSTORAGELOCK} {$ifdef FPC} inline; {$endif} {$endif}
/// low-level access to how StorageLock(true) affetcs TRestServer.InternalState
property StorageLockShouldIncreaseOwnerInternalState: boolean
read fStorageLockShouldIncreaseOwnerInternalState
write fStorageLockShouldIncreaseOwnerInternalState;
/// implement Rest unlocking (UNLOCK verb)
// - to be called e.g. after a Retrieve() with forupdate=TRUE
// - locking is handled at (Owner.)Model level
// - returns true on success
function UnLock(Table: TOrmClass; aID: TID): boolean; override;
/// overridden method calling the owner (if any) to guess if this record
// can be updated or deleted
function RecordCanBeUpdated(Table: TOrmClass; ID: TID; Action: TOrmEvent;
ErrorMsg: PRawUtf8 = nil): boolean; override;
/// override this method if you want to update the refresh state
// - returns FALSE if the static table content was not modified (default
// method implementation is to always return FALSE)
// - returns TRUE if the table has been refreshed and its content was modified:
// therefore the client will know he'll need to refresh some content
function RefreshedAndModified: boolean; virtual;
/// TRestOrmServer.Uri use it for Static.EngineList to by-pass virtual table
// - this default implementation will return TRUE and replace SQL with
// Sql.SelectAll[true] if it SQL equals Sql.SelectAll[false] (i.e. 'SELECT *')
// - this method is called only if the WHERE clause of SQL refers to the
// static table name only (not needed to check it twice)
function AdaptSqlForEngineList(var SQL: RawUtf8): boolean; virtual;
/// create one index for all specific FieldNames at once
// - do nothing virtual/abstract method by default: will return FALSE (i.e. error)
function CreateSqlMultiIndex(Table: TOrmClass; const FieldNames: array of RawUtf8;
Unique: boolean; IndexName: RawUtf8 = ''): boolean; virtual;
/// 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
// - faster than OneFieldValues method, which creates a temporary JSON content
// - this default implementation will call the overloaded SearchField()
// value after conversion of the FieldValue into RawUtf8
function SearchField(const FieldName: RawUtf8; FieldValue: Int64;
out ResultID: TIDDynArray): boolean; overload; virtual;
/// 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
// - this virtual implementation redirect to OneFieldValues method, which
// creates a temporary JSON content
function SearchField(const FieldName, FieldValue: RawUtf8;
out ResultID: TIDDynArray): boolean; overload; virtual;
/// returns the current authentication session ID from TRestOrmServer owner
function GetCurrentSessionUserID: TID; override;
/// internal method returning 0 for 'ID'/'RowID' or the TOrm field index + 1
function GetFieldIndex(const FieldName: RawUtf8; out Index: integer): boolean;
/// read only access to a boolean value set to true if table data was modified
property Modified: boolean
read fModified write fModified;
/// read only access to the ORM properties of the associated record type
// - may be nil if this instance is not associated with a TOrmModel
property StoredClassProps: TOrmModelProperties
read fStoredClassProps;
/// read only access to the RTTI properties of the associated record type
property StoredClassRecordProps: TOrmProperties
read fStoredClassRecordProps;
/// read only access to the TRestOrmServer using this storage engine
property Owner: TRestOrmServer
read fOwner;
/// read only access to the class defining the record type stored in this
// REST storage
property StoredClass: TOrmClass
read fStoredClass;
/// allow to force refresh for a given Static table
// - default FALSE means to return the main TRestOrmServer.InternalState
// - TRUE indicates that OutInternalState := cardinal(-1) will be returned
property OutInternalStateForcedRefresh: boolean
read fOutInternalStateForcedRefresh;
published
/// name of the class defining the record type stored in this REST storage
property StoredClassName: RawUtf8
read GetStoredClassName;
end;
{ ************ TRestStorageInMemory as Stand-Alone JSON/Binary Storage }
/// event prototype called by TRestStorageInMemory.FindWhereEqual(),
// FindWhere() or ForEach() methods
// - aDest is an opaque pointer, as supplied to FindWhereEqual(), which may
// point e.g. to a result list, or a shared variable to apply the process
// - aRec will point to the corresponding item
// - aIndex will identify the item index in the internal list
TOnFindWhereEqual = procedure(
aDest: pointer; aRec: TOrm; aIndex: integer) of object;
/// abstract REST storage exposing some internal TOrm-based methods
TRestStorageTOrm = class(TRestStorage)
public
function EngineAdd(TableModelIndex: integer;
const SentData: RawUtf8): TID; override;
function EngineUpdate(TableModelIndex: integer; ID: TID;
const SentData: RawUtf8): boolean; override;
/// internal method called by TRestServer.Batch() to process SIMPLE input
// - overriden for optimized multi-insert of the supplied JSON array values
function InternalBatchDirectSupport(Encoding: TRestBatchEncoding;
RunTableIndex: integer): TRestOrmBatchDirect; override;
/// internal method called by TRestServer.Batch() to process SIMPLE input
// - overriden for optimized multi-insert of the supplied JSON array values
function InternalBatchDirectOne(Encoding: TRestBatchEncoding;
RunTableIndex: integer; const Fields: TFieldBits; Sent: PUtf8Char): TID; override;
/// manual Add of a TOrm
// - returns the ID created on success
// - returns -1 on failure (not UNIQUE field value e.g., optionally setting
// the index into ExistingIndex PtrInt)
// - on success, the Rec instance is added to the Values[] list: caller
// doesn't need to Free it
function AddOne(Rec: TOrm; ForceID: boolean;
const SentData: RawUtf8; ExistingIndex: PPtrInt = nil): TID; virtual; abstract;
/// manual Retrieval of a TOrm field values
// - an instance of the associated static class is created
// - and all its properties are filled from the Items[] values
// - caller can modify these properties, then use UpdateOne() if the changes
// have to be stored inside the Items[] list
// - calller must always free the returned instance
// - returns NIL if any error occurred, e.g. if the supplied aID was incorrect
// - method available since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function GetOne(aID: TID): TOrm; virtual; abstract;
/// manual Update of a TOrm field values
// - Rec.ID specifies which record is to be updated
// - will update bit-wise Fields specified properties
// - returns TRUE on success, FALSE on any error (e.g. invalid Rec.ID)
// - method available since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function UpdateOne(Rec: TOrm; const Fields: TFieldBits;
const SentData: RawUtf8): boolean; overload; virtual; abstract;
/// manual Update of a TOrm field values from an array of TSqlVar
// - will update all properties, including BLOB fields and such
// - returns TRUE on success, FALSE on any error (e.g. invalid Rec.ID)
// - method available since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
// - this default implementation will create a temporary TOrm instance
// with the supplied Values[], and will call overloaded UpdateOne() method
function UpdateOne(ID: TID;
const Values: TSqlVarDynArray): boolean; overload; virtual;
end;
/// class able to handle a O(1) hashed-based search of a property
// - used e.g. to hash TRestStorageInMemory field values
TRestStorageInMemoryUnique = class
protected
fHasher: TDynArrayHasher;
fOwner: TRestStorageInMemory;
fPropInfo: TOrmPropInfo;
fCaseInsensitive: boolean;
fLastFindHashCode: cardinal;
public
/// initialize a hash for a record array field
// - aField maps the "stored AS_UNIQUE" published property
constructor Create(aOwner: TRestStorageInMemory; aField: TOrmPropInfo);
/// fast search using O(1) internal hash table
// - returns -1 if not found or not indexed (self=nil)
function Find(Rec: TOrm): integer;
/// called by TRestStorageInMemory.AddOne after a precious Find()
function AddedAfterFind(Rec: TOrm): boolean;
{$ifdef HASINLINE} inline; {$endif}
/// the corresponding field RTTI
property PropInfo: TOrmPropInfo
read fPropInfo;
/// if the string comparison shall be case-insensitive
property CaseInsensitive: boolean
read fCaseInsensitive;
/// access to the internal hash table
property Hasher: TDynArrayHasher
read fHasher;
end;
/// REST storage with direct access to a TObjectList memory-stored table
// - store the associated TOrm values in memory
// - handle one TOrm per TRestStorageInMemory instance
// - must be registered individualy in a TRestOrmServer to access data from a
// common client, by using the TRestOrmServer.OrmMapInMemory method:
// it allows an unique access for both SQLite3 and Static databases
// - handle basic REST commands, no full SQL interpreter is implemented: only
// valid SQL command is "SELECT Field1,Field2 FROM Table WHERE ID=120;", i.e
// a one Table SELECT with one optional "WHERE fieldname operator value"
// statement, with = < <= <> != >= > operators, and IS / IS NULL / ID IN (...)
// - if used within a TOrmVirtualTableJson, you'll be able to handle any kind of
// SQL statement (even joined SELECT or such) with this memory-stored database
// via the SQlite3 virtual tables engine
// - data can be stored and retrieved from a file (JSON format is used by
// default, if BinaryFile parameter is left to false; a proprietary compressed
// binary format can be used instead) if a file name is supplied at creating
// the TRestStorageInMemory instance
// - our TRestStorageInMemory database engine is very optimized and is a lot
// faster than SQLite3 for such queries - but its values remain in RAM,
// therefore it is not meant to deal with more than 100,000 rows or if
// ACID commit on disk is required
TRestStorageInMemory = class(TRestStorageTOrm)
protected
fValue: TOrmObjArray;
fCount: integer;
fCommitShouldNotUpdateFile: boolean;
fBinaryFile: boolean;
fExpandedJson: boolean;
fUnSortedID: boolean;
fTrackChangesAndFlushRunning: boolean;
fFileName: TFileName;
fSearchRec: TOrm; // temporary record to store the searched value
fBasicUpperSqlSelect: array[boolean] of RawUtf8;
fUnique, fUniquePerField: array of TRestStorageInMemoryUnique;
fMaxID: TID;
fValues: TDynArrayHashed; // hashed by ID
fTrackChangesFieldBitsOffset: PtrUInt;
fTrackChangesPersistence: IRestOrm;
fTrackChangesDeleted: TInt64DynArray; // TIDDynArray
fTrackChangesDeletedCount: integer;
function UniqueFieldsUpdateOK(aRec: TOrm; aUpdateIndex: integer;
aFields: PFieldBits): boolean;
procedure RaiseGetItemOutOfRange(Index: integer);
function GetItem(Index: integer): TOrm;
{$ifdef HASINLINE}inline;{$endif}
function GetID(Index: integer): TID;
{$ifdef HASINLINE}inline;{$endif}
procedure InternalTrackChangeUpdated(aRec: TOrm; const Fields: TFieldBits);
{$ifdef HASINLINE}inline;{$endif}
procedure SetFileName(const aFileName: TFileName);
procedure ComputeStateAfterLoad(var loaded: TPrecisionTimer; binary: boolean);
procedure SetBinaryFile(aBinary: boolean);
procedure GetJsonValuesEvent(aDest: pointer; aRec: TOrm; aIndex: integer);
/// used to create the JSON content from a SELECT parsed command
// - WhereField index follows FindWhereEqual / TSelectStatement.WhereField
// - returns the number of data row added (excluding field names)
// - this method is very fast and optimized (for search and JSON serializing)
function GetJsonValues(Stream: TStream; Expand: boolean;
Stmt: TSelectStatement): PtrInt;
public
/// TRestOrmServer.Uri use it for Static.EngineList to by-pass virtual table
// - overridden method to handle basic queries as handled by EngineList()
function AdaptSqlForEngineList(var SQL: RawUtf8): boolean; override;
/// overridden methods for direct in-memory database engine thread-safe process
function EngineRetrieve(TableModelIndex: integer; ID: TID): RawUtf8; override;
function EngineList(TableModelIndex: integer; const SQL: RawUtf8;
ForceAjax: boolean = false; ReturnedRowCount: PPtrInt = nil): RawUtf8; override;
function EngineUpdate(TableModelIndex: integer; ID: TID;
const SentData: RawUtf8): boolean; override;
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 EngineDeleteWhere(TableModelIndex: integer; const SqlWhere: RawUtf8;
const IDs: TIDDynArray): boolean; override;
function EngineExecute(const aSql: RawUtf8): boolean; override;
public
/// initialize the table storage data, reading it from a file if necessary
// - data encoding on file is UTF-8 JSON format by default, or
// should be some binary format if aBinaryFile is set to true
constructor Create(aClass: TOrmClass; aServer: TRestOrmServer;
const aFileName: TFileName = ''; aBinaryFile: boolean = false); reintroduce; virtual;
/// free used memory
// - especially release all fValue[] instances
destructor Destroy; override;
/// clear all the values of this table
// - will reset the associated database file, if any
procedure DropValues(andUpdateFile: boolean = true);
/// load the values from JSON data
// - a temporary copy of aJson is made to ensure it won't be modified in-place
// - consider using the overlaoded PUtf8Char/len method if you don't need this copy
procedure LoadFromJson(const aJson: RawUtf8); overload;
/// load the values from JSON data
procedure LoadFromJson(JsonBuffer: PUtf8Char; JsonBufferLen: PtrInt); overload;
/// save the values into JSON data
function SaveToJson(Expand: boolean): RawUtf8; overload;
/// save the values into JSON data
procedure SaveToJson(Stream: TStream; Expand: boolean); overload;
/// load the values from binary file/stream
// - the binary format is a custom compressed format (using our SynLZ fast
// compression algorithm), with variable-length record storage
// - the binary content is first checked for consistency, before loading
// - warning: the field layout should be the same at SaveToBinary call;
// for instance, it won't be able to read a file content with a renamed
// or modified field type
// - will return false if the binary content is invalid
function LoadFromBinary(Stream: TStream): boolean; overload;
/// load the values from binary data
// - uses the same compressed format as the overloaded stream/file method
// - will return false if the binary content is invalid
function LoadFromBinary(const Buffer: RawByteString): boolean; overload;
/// load the values from binary resource
// - the resource name is expected to be the TOrm class name,
// with a resource type of 10
// - uses the same compressed format as the overloaded stream/file method
// - you can specify a library (dll) resource instance handle, if needed
procedure LoadFromResource(ResourceName: string = '';
Instance: TLibHandle = 0);
/// save the values into a binary file/stream
// - the binary format is a custom compressed format (using our SynLZ fast
// compression algorithm), with variable-length record storage: e.g. a 27 KB
// Dali1.json content is stored into a 6 KB Dali2.data file
// (this data has a text redundant field content in its FirstName field);
// 502 KB People.json content is stored into a 92 KB People.data file
// - returns the number of bytes written into Stream
function SaveToBinary(Stream: TStream): integer; overload;
/// save the values into a binary buffer
// - uses the same compressed format as the overloaded stream/file method
function SaveToBinary: RawByteString; overload;
/// if file was modified, the file is updated on disk
// - this method is called automaticaly when the TRestStorage
// instance is destroyed: should should want to call in in some cases,
// in order to force the data to be saved regularly
// - do nothing if the table content was not modified
// - will write JSON content by default, or binary content if BinaryFile
// property was set to true
procedure UpdateFile;
/// will reload all content from the current disk file
// - any not saved modification will be lost (e.g. if Updatefile has not
// been called since)
procedure ReloadFromFile;
/// retrieve the index in Items[] of a particular ID
// - return -1 if this ID was not found
// - use internally fast O(1) hashed search algorithm
// - warning: this method should be protected via StorageLock/StorageUnlock
function IDToIndex(ID: TID): PtrInt;
/// retrieve all IDs stored at once
// - will make a thread-safe copy, for unlocked use
procedure GetAllIDs(out ID: TIDDynArray);
/// low-level Add of a TOrm instance
// - returns the ID created on success
// - returns -1 on failure (not UNIQUE field value e.g.)
// - on success, the Rec instance is added to the Values[] list: caller
// doesn't need to Free it, since it will be owned by the storage
// - in practice, SentData is used only for OnUpdateEvent/OnBlobUpdateEvent
// and the history feature
// - warning: this method should be protected via StorageLock/StorageUnlock
function AddOne(Rec: TOrm; ForceID: boolean;
const SentData: RawUtf8; ExistingIndex: PPtrInt = nil): TID; override;
/// manual Retrieval of a TOrm field values
// - an instance of the associated static class is created, and filled with
// the actual properties values
// - and all its properties are filled from the Items[] values
// - caller can modify these properties, then use UpdateOne() if the changes
// have to be stored inside the Items[] list
// - calller must always free the returned instance
// - returns NIL if any error occurred, e.g. if the supplied aID was incorrect
// - method available since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function GetOne(aID: TID): TOrm; override;
/// manual Update of a TOrm field values
// - Rec.ID specifies which record is to be updated
// - will update bit-wise Fields specified properties
// - returns TRUE on success, FALSE on any error (e.g. invalid Rec.ID)
// - method available since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function UpdateOne(Rec: TOrm; const Fields: TFieldBits;
const SentData: RawUtf8): boolean; override;
/// manual Update of a TOrm field values from a TSqlVar array
// - will update all properties, including BLOB fields and such
// - returns TRUE on success, FALSE on any error (e.g. invalid Rec.ID)
// - method available since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function UpdateOne(ID: TID;
const Values: TSqlVarDynArray): boolean; override;
/// direct deletion of a TOrm, from its index in Values[]
// - warning: this method should be protected via StorageLock/StorageUnlock
function DeleteOne(aIndex: integer): boolean; virtual;
/// overridden method for direct in-memory database engine call
// - made public since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function EngineDelete(TableModelIndex: integer; ID: TID): boolean; override;
/// overridden method for direct in-memory database engine call
// - made public since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function EngineUpdateField(TableModelIndex: integer;
const SetFieldName, SetValue, WhereFieldName, WhereValue: RawUtf8): boolean; override;
/// overridden method for direct in-memory database engine call
// - made public since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestOrmServer
function EngineUpdateFieldIncrement(TableModelIndex: integer; ID: TID;
const FieldName: RawUtf8; Increment: Int64): boolean; override;
/// overridden method for direct in-memory database engine call
function UpdateBlobFields(Value: TOrm): boolean; override;
/// overridden method for direct in-memory database engine call
function RetrieveBlobFields(Value: TOrm): boolean; override;
/// overridden method for direct in-memory database engine call
function TableRowCount(Table: TOrmClass): Int64; override;
/// overridden method for direct in-memory database engine call
function TableHasRows(Table: TOrmClass): boolean; override;
/// overridden method for direct in-memory database engine call
function MemberExists(Table: TOrmClass; ID: TID): boolean; 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
// - faster than OneFieldValues method, which creates a temporary JSON content
function SearchField(const FieldName, FieldValue: RawUtf8;
out ResultID: TIDDynArray): boolean; override;
/// search for a field value, according to its SQL content representation
// - return the found TOrm on success, nil if none did match
// - warning: it returns a reference to one item of the unlocked internal
// list, so you should NOT use this on a read/write table, but rather
// use the slightly slower but safer SearchCopy() method or make explicit
// ! StorageLock ... try ... SearchInstance ... finally StorageUnlock end
function SearchInstance(const FieldName, FieldValue: RawUtf8;
CaseInsensitive: boolean = true;
Op: TSelectStatementOperator = opEqualTo): pointer; overload;
/// search for a field value, according to its SQL content representation
// - overloaded function using a FieldIndex (0=RowID,1..=RTTI)
function SearchInstance(FieldIndex: integer; const FieldValue: RawUtf8;
CaseInsensitive: boolean = true;
Op: TSelectStatementOperator = opEqualTo): pointer; overload;
/// search for a field value, according to its SQL content representation
// - return the found TOrm index on success, -1 if none did match
// - warning: it returns a reference to the current index of the unlocked
// internal list, so you should NOT use without StorageLock/StorageUnlock
function SearchIndex(const FieldName, FieldValue: RawUtf8;
CaseInsensitive: boolean = true;
Op: TSelectStatementOperator = opEqualTo): integer;
/// search for a field value, according to its SQL content representation
// - return a copy of the found TOrm on success, nil if no match
// - you should use SearchCopy() instead of SearchInstance(), unless you
// are sure that the internal TOrm list won't change
function SearchCopy(const FieldName, FieldValue: RawUtf8;
CaseInsensitive: boolean = true;
Op: TSelectStatementOperator = opEqualTo): pointer;
/// search and count for a field value, according to its SQL content representation
// - return the number of found entries on success, 0 if it was not found
function SearchCount(const FieldName, FieldValue: RawUtf8;
CaseInsensitive: boolean = true;
Op: TSelectStatementOperator = opEqualTo): integer;
/// search for a field value, according to its SQL content representation
// - call the supplied OnFind event on match
// - returns the number of found entries
// - is just a wrapper around FindWhere() with StorageLock protection
function SearchEvent(const FieldName, FieldValue: RawUtf8;
const OnFind: TOnFindWhereEqual; Dest: pointer;
FoundLimit, FoundOffset: PtrInt; CaseInsensitive: boolean = true;
Op: TSelectStatementOperator = opEqualTo): integer; overload;
/// search for a field value, according to its SQL content representation
// - overloaded function using a FieldIndex (0=RowID,1..=RTTI)
function SearchEvent(FieldIndex: integer; const FieldValue: RawUtf8;
const OnFind: TOnFindWhereEqual; Dest: pointer;
FoundLimit, FoundOffset: PtrInt; CaseInsensitive: boolean = true;
Op: TSelectStatementOperator = opEqualTo): integer; overload;
/// optimized search of WhereValue in WhereField (0=RowID,1..=RTTI)
// - will use fast O(1) hash for fUnique[] fields
// - will use SYSTEMNOCASE case-insensitive search for text values, unless
// CaseInsensitive is set to FALSE
// - warning: this method should be protected via StorageLock/StorageUnlock
function FindWhereEqual(WhereField: integer; const WhereValue: RawUtf8;
const OnFind: TOnFindWhereEqual; Dest: pointer;
FoundLimit, FoundOffset: PtrInt;
CaseInsensitive: boolean = true): PtrInt; overload;
/// optimized search of WhereValue in a field, specified by name
// - will use fast O(1) hash for fUnique[] fields
// - will use SYSTEMNOCASE case-insensitive search for text values, unless
// CaseInsensitive is set to FALSE
// - warning: this method should be protected via StorageLock/StorageUnlock
function FindWhereEqual(const WhereFieldName, WhereValue: RawUtf8;
const OnFind: TOnFindWhereEqual; Dest: pointer;
FoundLimit, FoundOffset: integer;
CaseInsensitive: boolean = true): PtrInt; overload;
/// comparison lookup of the WhereValue in a field, specified by name
// - this method won't use any index but brute force using the comparison
// function over each stored item to implement < <= <> > >= search
// - warning: this method should be protected via StorageLock/StorageUnlock
function FindWhere(WhereField: integer; const WhereValue: RawUtf8;
WhereOp: TSelectStatementOperator; const OnFind: TOnFindWhereEqual;
Dest: pointer; FoundLimit, FoundOffset: integer;
CaseInsensitive: boolean = true): PtrInt; overload;