-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathmormot.orm.mongodb.pas
1785 lines (1705 loc) · 61.2 KB
/
mormot.orm.mongodb.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/ODM Types and Classes for direct MongoDB NoSQL Database Access
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.orm.mongodb;
{
*****************************************************************************
ORM/ODM MongoDB Database Access using mormot.db.nosql.mongodb unit
- TRestStorageMongoDB for REST Storage Over MongoDB
- High-Level Functions to Initialize MongoDB ORM
*****************************************************************************
}
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.orm.base,
mormot.orm.core,
mormot.orm.rest,
mormot.orm.client,
mormot.orm.server,
mormot.orm.storage,
mormot.rest.core,
mormot.rest.server,
mormot.rest.memserver,
mormot.soa.server,
mormot.db.core,
mormot.db.nosql.bson,
mormot.db.nosql.mongodb;
{ *********** TRestStorageMongoDB for REST Storage Over MongoDB }
type
/// exception class raised by this units
EOrmMongoDB = class(EOrmException);
/// how TRestStorageMongoDB would compute the next ID to be inserted
// - you may choose to retrieve the last inserted ID via
// $ {$query:{},$orderby:{_id:-1}}
// or search for the current maximum ID in the collection via
// $ {$group:{_id:null,max:{$max:"$_id"}}}
// - eacLastIDOnce and eacMaxIDOnce would execute the request once when
// the storage instance is first started, whereas eacLastIDEachTime and
// eacMaxIDEachTime would be execute before each insertion
// - with big amount of data, retrieving the maximum ID (eacMaxID*) performs
// a full scan, which would be very slow: the last inserted ID (eacLastID*)
// would definitively be faster
// - in all cases, to ensure that a centralized MongoDB server has unique
// ID, you should better pre-compute the ID using your own algorithm
// depending on your nodes topology, and not rely on the ORM, e.g. using
// SetEngineAddComputeIdentifier() method, which would allocate a
// TSynUniqueIdentifierGenerator and associate eacSynUniqueIdentifier
TRestStorageMongoDBEngineAddComputeID = (
eacLastIDOnce,
eacLastIDEachTime,
eacMaxIDOnce,
eacMaxIDEachTime,
eacSynUniqueIdentifier);
/// REST server with direct access to a MongoDB external database
// - handle all REST commands via direct SynMongoDB call
// - is used by TRestServer.Uri for faster RESTful direct access
// - JOINed SQL statements are not handled yet
TRestStorageMongoDB = class(TRestStorage)
protected
fCollection: TMongoCollection;
fEngineLastID: TID;
fEngineGenerator: TSynUniqueIdentifierGenerator;
fEngineAddCompute: TRestStorageMongoDBEngineAddComputeID;
fBsonProjectionSimpleFields: variant;
fBsonProjectionBlobFields: variant;
fBsonProjectionBlobFieldsNames: TRawUtf8DynArray;
// multi-thread BATCH process is secured via Lock/UnLock critical section
fBatchMethod: TUriMethod;
fBatchWriter: TBsonWriter;
fBatchIDs: TIDDynArray;
fBatchIDsCount: integer;
function EngineNextID: TID;
function DocFromJson(const Json: RawUtf8; Occasion: TOrmOccasion;
var Doc: TDocVariantData): TID;
procedure JsonFromDoc(var doc: TDocVariantData; var result: RawUtf8);
function BsonProjectionSet(var Projection: variant; WithID: boolean;
const Fields: TFieldBits; BsonFieldNames: PRawUtf8DynArray;
const SubFields: TRawUtf8DynArray): integer;
function GetJsonValues(const Res: TBsonDocument;
const extFieldNames: TRawUtf8DynArray; W: TOrmWriter): integer;
public
// overridden methods calling the MongoDB external server
function EngineRetrieve(TableModelIndex: integer; ID: TID): RawUtf8; override;
function EngineList(TableModelIndex: integer; const SQL: RawUtf8;
ForceAjax: boolean = false; ReturnedRowCount: PPtrInt = nil): RawUtf8; override;
function EngineAdd(TableModelIndex: integer;
const SentData: RawUtf8): TID; override;
function EngineUpdate(TableModelIndex: integer; ID: TID;
const SentData: RawUtf8): boolean; override;
function EngineUpdateField(TableModelIndex: integer;
const SetFieldName, SetValue,
WhereFieldName, WhereValue: RawUtf8): boolean; override;
function EngineUpdateFieldIncrement(TableModelIndex: integer; ID: TID;
const FieldName: RawUtf8; Increment: Int64): boolean; override;
function EngineDeleteWhere(TableModelIndex: integer;
const SqlWhere: RawUtf8; const IDs: TIDDynArray): boolean; override;
// BLOBs should be accessed directly, not through slower JSON Base64 encoding
function EngineRetrieveBlob(TableModelIndex: integer; aID: TID;
BlobField: PRttiProp; out BlobData: RawBlob): boolean; override;
function EngineUpdateBlob(TableModelIndex: integer; aID: TID;
BlobField: PRttiProp; const BlobData: RawBlob): boolean; override;
// method not implemented: always return false
function EngineExecute(const aSql: RawUtf8): boolean; override;
/// TRestServer.Uri use it for Static.EngineList to by-pass virtual table
// - overridden method which allows return TRUE, i.e. always by-pass
// virtual tables process
function AdaptSqlForEngineList(var SQL: RawUtf8): boolean; override;
public
/// initialize the direct access to the MongoDB collection
// - in practice, you should not have to call this constructor, but rather
// OrmMapMongoDB() with a TMongoDatabase instance
constructor Create(aClass: TOrmClass; aServer: TRestOrmServer); override;
/// release used memory
destructor Destroy; override;
/// overridden method for one single update call to the MongoDB server
function UpdateBlobFields(Value: TOrm): boolean; override;
/// overridden method for one single read call to the MongoDB server
function RetrieveBlobFields(Value: TOrm): boolean; override;
/// get the row count of a specified table
// - return -1 on error
// - return the row count of the table on success
function TableRowCount(Table: TOrmClass): Int64; override;
/// check if there is some data rows in a specified table
function TableHasRows(Table: TOrmClass): boolean; override;
/// check if there is given ID in a specified table
function MemberExists(Table: TOrmClass; ID: TID): boolean; override;
/// delete a row, calling the current MongoDB server
// - made public since a TRestStorage instance may be created
// stand-alone, i.e. without any associated Model/TRestServer
function EngineDelete(TableModelIndex: integer; ID: TID): boolean; override;
/// search for a 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;
/// create one index for all specific FieldNames at once
function CreateSqlMultiIndex(Table: TOrmClass;
const FieldNames: array of RawUtf8; Unique: boolean;
IndexName: RawUtf8 = ''): boolean; override;
// overridden method returning TRUE for next calls to EngineAdd/Delete
// will properly handle operations until InternalBatchStop is called
// BatchOptions is ignored with MongoDB (yet)
function InternalBatchStart(Encoding: TRestBatchEncoding;
BatchOptions: TRestBatchOptions): boolean; override;
// internal method called by TRestServer.RunBatch() to process fast
// BULK sending to remote MongoDB database
procedure InternalBatchStop; override;
/// drop the whole table content
// - in practice, dropping the whole MongoDB database would be faster
// - but you can still add items to it - whereas Collection.Drop would
// trigger GPF issues
procedure Drop;
/// initialize an internal time-based unique ID generator, linked to
// a genuine process identifier
// - will allocate a local TSynUniqueIdentifierGenerator
// - EngineAddCompute would be set to eacSynUniqueIdentifier
procedure SetEngineAddComputeIdentifier(aIdentifier: word);
published
/// the associated MongoDB collection instance
property Collection: TMongoCollection
read fCollection;
/// how the next ID would be compute at each insertion
// - default eacLastIDOnce may be the fastest, but other options are
// available, and may be used in some special cases
// - consider using SetEngineAddComputeIdentifier() which is both safe
// and fast, with a cloud of servers sharing the same MongoDB collection
property EngineAddCompute: TRestStorageMongoDBEngineAddComputeID
read fEngineAddCompute write fEngineAddCompute;
end;
{ *********** High-Level Functions to Initialize MongoDB ORM }
/// creates and register a static class on the Server-side to let a given
// ORM class be stored on a remote MongoDB server
// - will associate the supplied class with a MongoDB collection for a
// specified MongoDB database
// - to be called before IRestOrmServer.CreateMissingTables
// - by default, the collection name will match TOrm.SqlTableName, but
// you can customize it with the corresponding parameter
// - the TOrm.ID (RowID) field is always mapped to MongoDB's _id field
// - will call create needed indexes
// - you can later call aServer.InitializeTables to create any missing index and
// initialize the void tables (e.g. default TSqlAuthGroup and TSqlAuthUser records)
// - after registration, you can tune the field-name mapping by calling
// ! aModel.Props[aClass].ExternalDB.MapField(..)
// (just a regular external DB as defined in mormot.orm.sql.pas unit) - it may be
// a good idea to use short field names on MongoDB side, to reduce the space
// used for storage (since they will be embedded within the document data)
// - it will return the corresponding TRestStorageMongoDB instance -
// you can access later to it and its associated collection e.g. via:
// ! (aServer.GetStaticStorage(TMyOrm) as TRestStorageMongoDB)
// - you can set aMapAutoFieldsIntoSmallerLength to compute a field name
// mapping with minimal length, so that the stored BSON would be smaller:
// by definition, ID/RowID will be mapped as 'id', but other fields will
// use their first letter, and another other letter if needed (after a '_',
// or in uppercase, or the next one) e.g. FirstName -> 'f', LastName -> 'l',
// LockedAccount: 'la'...
function OrmMapMongoDB(aClass: TOrmClass; aServer: TRestOrm;
aMongoDatabase: TMongoDatabase; aMongoCollectionName: RawUtf8 = '';
aMapAutoFieldsIntoSmallerLength: boolean = false): TRestStorageMongoDB;
type
/// all possible options for OrmMapMongoDBAll/TRestMongoDBCreate functions
// - by default, TSqlAuthUser and TSqlAuthGroup tables will be handled via the
// external DB, but you can avoid it for speed when handling session and security
// by setting mrDoNotRegisterUserGroupTables
// - you can set mrMapAutoFieldsIntoSmallerLength to compute a field name
// mapping with minimal length, so that the stored BSON would be smaller:
// by definition, ID/RowID will be mapped as 'id', but other fields will
// use their first letter, and another other letter if needed (after a '_',
// or in uppercase, or the next one) e.g. FirstName -> 'f', LastName -> 'l',
// LockedAccount: 'la'... - WARNING: not yet implemented
TOrmMapMongoDBOption = (
mrDoNotRegisterUserGroupTables,
mrMapAutoFieldsIntoSmallerLength);
/// set of options for OrmMapMongoDBAll/TRestMongoDBCreate functions
TOrmMapMongoDBOptions = set of TOrmMapMongoDBOption;
/// create and register ALL classes of a given model to access a MongoDB server
// - the collection names will follow the class names
// - this function will call aServer.InitializeTables to create any missing
// index or populate default collection content
// - if aMongoDBIdentifier is not 0, then SetEngineAddComputeIdentifier()
// would be called
function OrmMapMongoDBAll(aServer: TRestOrm;
aMongoDatabase: TMongoDatabase; aOptions: TOrmMapMongoDBOptions = [];
aMongoDBIdentifier: word = 0): boolean;
/// create a new TRest instance, possibly using MongoDB for its ORM process
// - if aDefinition.Kind matches a TRest registered class, one new instance
// of this kind will be created and returned
// - if aDefinition.Kind is 'MongoDB' or 'MongoDBS', it will instantiate an
// in-memory TRestServerDB or a TRestServerFullMemory instance (calling
// CreateInMemoryServer), then OrmMapMongoDBAll()
// with a TMongoClient initialized from aDefinition.ServerName
// ('server' or 'server:port') - optionally with TLS enabled if Kind equals
// 'MongoDBS' - and a TMongoDatabase created from aDefinition.DatabaseName,
// using authentication if aDefinition.User/Password credentials are set
// - it will return nil if the supplied aDefinition is invalid
// - if aMongoDBIdentifier is not 0, then SetEngineAddComputeIdentifier()
// would be called for all created TRestStorageMongoDB
function TRestMongoDBCreate(aModel: TOrmModel;
aDefinition: TSynConnectionDefinition; aHandleAuthentication: boolean;
aOptions: TOrmMapMongoDBOptions;
aMongoDBIdentifier: word = 0): TRest; overload;
function ToText(eac: TRestStorageMongoDBEngineAddComputeID): PShortString; overload;
implementation
{ *********** TRestStorageMongoDB for REST Storage Over MongoDB }
{ TRestStorageMongoDB }
constructor TRestStorageMongoDB.Create(aClass: TOrmClass; aServer: TRestOrmServer);
begin
inherited Create(aClass, aServer);
// ConnectionProperties should have been set in OrmMapMongoDB()
fCollection := fStoredClassMapping^.ConnectionProperties as TMongoCollection;
fRest.InternalLog('will store % using %', [aClass, Collection], sllInfo);
BsonProjectionSet(fBsonProjectionSimpleFields, true,
fStoredClassRecordProps.SimpleFieldsBits[ooSelect], nil, nil);
BsonProjectionSet(fBsonProjectionBlobFields, false,
fStoredClassRecordProps.FieldBits[oftBlob],
@fBsonProjectionBlobFieldsNames, nil);
end;
function TRestStorageMongoDB.BsonProjectionSet(var Projection: variant;
WithID: boolean; const Fields: TFieldBits; BsonFieldNames: PRawUtf8DynArray;
const SubFields: TRawUtf8DynArray): integer;
var
i, n, sf: integer;
W: TBsonWriter;
name: RawUtf8;
temp: TTextWriterStackBuffer; // shared fTempBuffer is not protected now
begin
sf := length(SubFields);
W := TBsonWriter.Create(temp{%H-});
try
W.BsonDocumentBegin;
if WithID then
result := 1
else
result := 0;
name := fStoredClassMapping^.RowIDFieldName;
if sf > 0 then
name := name + SubFields[0];
W.BsonWrite(name, result);
for i := 0 to fStoredClassRecordProps.Fields.Count - 1 do
if FieldBitGet(Fields, i) then
begin
name := fStoredClassMapping^.ExtFieldNames[i];
if i + 1 < sf then
name := name + SubFields[i + 1];
W.BsonWrite(name, 1);
inc(result);
end;
W.BsonDocumentEnd;
W.ToBsonVariant(Projection);
if BsonFieldNames <> nil then
with fStoredClassMapping^ do
begin
SetLength(BsonFieldNames^, result);
if WithID then
begin
BsonFieldNames^[0] := RowIDFieldName;
n := 1;
end
else
n := 0;
for i := 0 to fStoredClassRecordProps.Fields.Count - 1 do
if FieldBitGet(Fields, i) then
begin
BsonFieldNames^[n] := ExtFieldNames[i];
inc(n);
end;
end;
finally
W.Free;
end;
end;
function TRestStorageMongoDB.CreateSqlMultiIndex(Table: TOrmClass;
const FieldNames: array of RawUtf8; Unique: boolean;
IndexName: RawUtf8): boolean;
begin
if (self = nil) or
(fCollection = nil) or
(Table <> fStoredClass) then
begin
result := false;
exit;
end;
result := true;
if (high(FieldNames) = 0) and
IsRowID(pointer(FieldNames[0])) then
exit; // ID primary key is always indexed by MongoDB
try
fCollection.EnsureIndex(FieldNames, true, Unique);
except
result := false;
end;
end;
procedure TRestStorageMongoDB.Drop;
var
DB: TMongoDatabase;
CollName: RawUtf8;
begin
DB := Collection.Database;
CollName := Collection.Name;
Collection.Drop;
fCollection := DB.CollectionOrCreate[CollName];
fEngineLastID := 0;
end;
destructor TRestStorageMongoDB.Destroy;
begin
inherited;
FreeAndNilSafe(fBatchWriter);
fEngineGenerator.Free;
fRest.InternalLog('Destroy for % using %', [fStoredClass, Collection], sllInfo);
end;
function TRestStorageMongoDB.TableHasRows(Table: TOrmClass): boolean;
begin
if (fCollection = nil) or
(Table <> fStoredClass) then
result := false
else
result := not fCollection.IsEmpty;
end;
function TRestStorageMongoDB.TableRowCount(Table: TOrmClass): Int64;
begin
if (fCollection = nil) or
(Table <> fStoredClass) then
result := 0
else
result := fCollection.Count;
end;
function TRestStorageMongoDB.MemberExists(Table: TOrmClass; ID: TID): boolean;
begin
if (fCollection = nil) or
(Table <> fStoredClass) then
result := false
else
result := fCollection.ExistOne(ID);
end;
procedure TRestStorageMongoDB.SetEngineAddComputeIdentifier(aIdentifier: word);
begin
fEngineGenerator.Free;
fEngineGenerator := TSynUniqueIdentifierGenerator.Create(aIdentifier);
fEngineAddCompute := eacSynUniqueIdentifier;
end;
function TRestStorageMongoDB.EngineNextID: TID;
procedure ComputeMax_ID;
var
res: variant;
start: Int64;
begin
QueryPerformanceMicroSeconds(start);
case fEngineAddCompute of
eacLastIDOnce,
eacLastIDEachTime:
begin
res := fCollection.FindDoc(BsonVariant(
'{$query:{},$orderby:{_id:-1}}'), BsonVariant(['_id', 1]));
if not VarIsEmptyOrNull(res) then
fEngineLastID := _Safe(res)^.I['_id'];
end;
eacMaxIDOnce,
eacMaxIDEachTime:
begin
res := fCollection.AggregateDocFromJson(
'{$group:{_id:null,max:{$max:"$_id"}}}');
if not VarIsEmptyOrNull(res) then
fEngineLastID := _Safe(res)^.I['max'];
end;
else
EOrmMongoDB.RaiseUtf8(
'Unexpected %.EngineNextID with %', [self, ToText(fEngineAddCompute)^]);
end;
if sllInfo in fRest.LogLevel then
fRest.InternalLog('ComputeMax_ID=% in % using %',
[fEngineLastID, MicroSecFrom(start), ToText(fEngineAddCompute)^], sllInfo);
end;
begin
if (fEngineAddCompute = eacSynUniqueIdentifier) and
(fEngineGenerator <> nil) then
begin
result := fEngineGenerator.ComputeNew; // this is preferred if several nodes
fEngineLastID := result;
exit;
end;
fStorageSafe.Lock;
if (fEngineLastID = 0) or
(fEngineAddCompute in [eacLastIDEachTime, eacMaxIDEachTime]) then
ComputeMax_ID;
inc(fEngineLastID);
result := fEngineLastID;
fStorageSafe.UnLock;
end;
function TRestStorageMongoDB.DocFromJson(const Json: RawUtf8;
Occasion: TOrmOccasion; var Doc: TDocVariantData): TID;
var
i, ndx: PtrInt;
dt: TDateTime;
blob: RawBlob;
info: TOrmPropInfo;
rtti: TRttiJson;
js, RecordVersionName: RawUtf8;
MissingID: boolean;
V: PSynVarData;
begin
// parse input JSON
Doc.InitJson(Json, [dvoValueCopiedByReference, dvoAllowDoubleValue]);
if (Doc.Kind <> dvObject) and
(Occasion <> ooInsert) then
EOrmMongoDB.RaiseUtf8('%.DocFromJson: invalid Json context', [self]);
if not (Occasion in [ooInsert, ooUpdate]) then
EOrmMongoDB.RaiseUtf8(
'Unexpected %.DocFromJson(Occasion=%)', [self, ToText(Occasion)^]);
// handle fields names and values
MissingID := true;
for i := Doc.Count - 1 downto 0 do // downwards for doc.Delete(i) below
if IsRowID(pointer(Doc.Names[i])) then
begin
// extract and rename ID/RowID input field
Doc.Names[i] := fStoredClassMapping^.RowIDFieldName;
VariantToInt64(Doc.Values[i], Int64(result)); // extract
if (Occasion = ooUpdate) or
(result = 0) then
// update does not expect any $set:{_id:..}
Doc.Delete(i)
else
// leave true if value is not an integer (=0)
MissingID := false;
end
else
begin
// change field name to the external mapped name
ndx := fStoredClassRecordProps.Fields.IndexByNameU(pointer(Doc.Names[i]));
if ndx < 0 then
EOrmMongoDB.RaiseUtf8(
'%.DocFromJson: unknown field name [%]', [self, Doc.Names[i]]);
Doc.Names[i] := fStoredClassMapping^.ExtFieldNames[ndx];
// normalize values from JSON high-level types into MongoDB native types
// using the ORM/pascal declared types
info := fStoredClassRecordProps.Fields.List[ndx];
V := @Doc.Values[i];
case V^.Data.VType of // 32-bit overlapped V^.VType is not correct here
varInteger:
// normalize 32-bit integer values into MongoDB boolean or date/time
case info.OrmFieldType of
oftBoolean:
begin
// normalize to boolean BSON
if V^.VInteger <> 0 then
V^.Data.VBoolean := true;
// doc.InitJson/GetVariantFromJson store 0,1 as varInteger
V^.VType := varBoolean;
end;
oftUnixTime:
begin
V^.VDate := UnixTimeToDateTime(V^.VInteger);
V^.VType := varDate; // direct set to avoid unexpected EInvalidOp
end;
oftUnixMSTime: // (very unlikely for actual time)
begin
V^.VDate := UnixMSTimeToDateTime(V^.VInteger);
V^.VType := varDate;
end;
end;
varInt64:
// normalize some 64-bit integer values into MongoDB date/time
case info.OrmFieldType of
oftUnixTime:
begin
V^.VDate := UnixTimeToDateTime(V^.VInt64);
V^.VType := varDate; // direct set to avoid unexpected EInvalidOp
end;
oftUnixMSTime:
begin
V^.VDate := UnixMSTimeToDateTime(V^.VInt64);
V^.VType := varDate;
end;
end;
varString:
// handle some TEXT values
case info.OrmFieldType of
oftDateTime,
oftDateTimeMS:
begin
// ISO-8601 text as MongoDB date/time
Iso8601ToDateTimePUtf8CharVar(
V^.VAny, length(RawByteString(V^.VAny)), dt);
FastAssignNew(V^.VAny);
V^.VDate := dt;
V^.VType := varDate; // direct set to avoid EInvalidOp
end;
oftBlob,
oftBlobCustom:
begin
// store Base64-encoded BLOB as binary
blob := BlobToRawBlob(RawByteString(V^.VAny));
BsonVariantType.FromBinary(blob, bbtGeneric, Variant(V^));
end;
oftBlobDynArray:
begin
// store dynamic array as object (if has any Json)
blob := BlobToRawBlob(RawByteString(V^.VAny));
if blob = '' then
SetVariantNull(Variant(V^))
else
begin
rtti := (info as TOrmPropInfoRttiDynArray).PropRtti;
if rtti.ArrayRtti.Cache.RttiOrd = roUByte then
// TBytes or TByteDynArray stored as BSON binary
js := ''
else
// try to store dynamic array as BSON array (via Json)
js := DynArrayBlobSaveJson(rtti.Info, pointer(blob), length(blob));
if (js <> '') and
(PInteger(js)^ and $00ffffff <> JSON_BASE64_MAGIC_C) then
BsonVariantType.FromJson(pointer(js), Variant(V^))
else
BsonVariantType.FromBinary(blob, bbtGeneric, Variant(V^));
end;
end;
end;
// oftObject,oftVariant,oftUtf8Custom were already converted to object from Json
end;
end;
if Occasion = ooInsert then
if MissingID then
begin
result := EngineNextID;
Doc.AddValue(fStoredClassMapping^.RowIDFieldName, result);
end
else
begin
if fEngineAddCompute = eacSynUniqueIdentifier then
EOrmMongoDB.RaiseUtf8('%.DocFromJson: unexpected set ' +
'%.ID=% with %', [self, fStoredClass, result, fEngineGenerator]);
fStorageSafe.Lock;
if result > fEngineLastID then
fEngineLastID := result;
fStorageSafe.UnLock;
end;
if fStoredClassRecordProps.RecordVersionField <> nil then
begin
RecordVersionName := fStoredClassMapping^.ExtFieldNames[
fStoredClassRecordProps.RecordVersionField.PropertyIndex];
if Doc.GetValueIndex(RecordVersionName) < 0 then
if Owner = nil then
EOrmMongoDB.RaiseUtf8(
'%.DocFromJson: unexpected Owner=nil with %.%: TRecordVersion',
[self, fStoredClass, fStoredClassRecordProps.RecordVersionField.Name])
else
// compute new monotonic TRecordVersion value if not supplied by sender
Doc.AddValue(RecordVersionName,
Owner.RecordVersionCompute(fStoredClassProps.TableIndex));
if (Owner <> nil) and
(Owner.Owner <> nil) and
(Owner.Owner.Services <> nil) then
(Owner.Owner.Services as TServiceContainerServer).
RecordVersionNotifyAddUpdate(Occasion, fStoredClassProps.TableIndex, Doc);
end;
if Doc.Kind <> dvObject then
EOrmMongoDB.RaiseUtf8(
'%.DocFromJson: Invalid Json context', [self]);
end;
function TRestStorageMongoDB.EngineAdd(TableModelIndex: integer;
const SentData: RawUtf8): TID;
var
doc: TDocVariantData;
begin
if (fCollection = nil) or
(TableModelIndex < 0) or
(fModel.Tables[TableModelIndex] <> fStoredClass) then
result := 0
else
try
result := DocFromJson(SentData, ooInsert, doc);
if fBatchMethod <> mNone then
if (fBatchMethod <> mPOST) or
(fBatchWriter = nil) then
result := 0
else
begin
{$ifdef MONGO_OLDPROTOCOL}
// OP_INSERT layout: just the documents the one after the other
fBatchWriter.BsonWriteDoc(doc);
{$else}
// insert command layout: as a JSON array of documents
fBatchWriter.BsonWrite(UInt32ToUtf8(fBatchIDsCount), doc);
{$endif MONGO_OLDPROTOCOL}
inc(fBatchIDsCount);
end
else
begin
fCollection.Insert([variant(doc)]);
if Owner <> nil then
begin
Owner.InternalUpdateEvent(oeAdd, TableModelIndex, result, SentData, nil, nil);
Owner.FlushInternalDBCache;
end;
end;
except
result := 0;
end;
end;
function TRestStorageMongoDB.EngineUpdate(TableModelIndex: integer; ID: TID;
const SentData: RawUtf8): boolean;
var
doc: TDocVariantData;
query, update: variant; // use explicit TBsonVariant for type safety
begin
if (fCollection = nil) or
(ID <= 0) or
(TableModelIndex < 0) or
(Model.Tables[TableModelIndex] <> fStoredClass) then
result := false
else
try
DocFromJson(SentData, ooUpdate, doc);
query := BsonVariant(['_id', ID]);
update := BsonVariant(['$set', variant(doc)]);
fCollection.Update(query, update);
if Owner <> nil then
begin
Owner.InternalUpdateEvent(oeUpdate, TableModelIndex, ID, SentData, nil, nil);
Owner.FlushInternalDBCache;
end;
result := true;
except
result := false;
end;
end;
function TRestStorageMongoDB.EngineUpdateField(TableModelIndex: integer;
const SetFieldName, SetValue, WhereFieldName, WhereValue: RawUtf8): boolean;
var
json: RawUtf8;
query, update: variant; // use explicit TBsonVariant for type safety
id: TBsonIterator;
begin
if (fCollection = nil) or
(TableModelIndex < 0) or
(fModel.Tables[TableModelIndex] <> fStoredClass) or
(SetFieldName = '') or
(SetValue = '') or
(WhereFieldName = '') or
(WhereValue = '') then
result := false
else
try
// use {%:%} here since WhereValue/SetValue are already json encoded
query := BsonVariant('{%:%}',
[fStoredClassMapping^.InternalToExternal(WhereFieldName), WhereValue], []);
update := BsonVariant('{$set:{%:%}}',
[fStoredClassMapping^.InternalToExternal(SetFieldName), SetValue], []);
fCollection.Update(query, update);
if Owner <> nil then
begin
if Owner.InternalUpdateEventNeeded(oeUpdate, TableModelIndex) and
id.Init(fCollection.FindBson(query, BsonVariant(['_id', 1]))) then
begin
JsonEncodeNameSQLValue(SetFieldName, SetValue, json);
while id.Next do
Owner.InternalUpdateEvent(oeUpdate, TableModelIndex,
id.Item.DocItemToInteger('_id'), json, nil, nil);
end;
Owner.FlushInternalDBCache;
end;
result := true;
except
result := false;
end;
end;
function TRestStorageMongoDB.EngineUpdateFieldIncrement(TableModelIndex: integer;
ID: TID; const FieldName: RawUtf8; Increment: Int64): boolean;
var
Value: Int64;
begin
result := false;
if (ID <= 0) or
(TableModelIndex < 0) or
(Model.Tables[TableModelIndex] <> fStoredClass) then
exit;
if (Owner <> nil) and
Owner.InternalUpdateEventNeeded(oeUpdate, TableModelIndex) then
result := OneFieldValue(fStoredClass, FieldName, 'ID=?', [], [ID], Value) and
UpdateField(fStoredClass, ID, FieldName, [Value + Increment])
else
try
fCollection.Update(
BsonVariant(['_id', ID]),
BsonVariant('{$inc:{%:%}}',
[fStoredClassMapping^.InternalToExternal(FieldName), Increment], []));
if Owner <> nil then
Owner.FlushInternalDBCache;
result := true;
except
on Exception do
result := false;
end;
end;
function TRestStorageMongoDB.EngineUpdateBlob(TableModelIndex: integer;
aID: TID; BlobField: PRttiProp; const BlobData: RawBlob): boolean;
var
query, update, blob: variant; // use explicit TBsonVariant for type safety
FieldName: RawUtf8;
AffectedField: TFieldBits;
begin
if (fCollection = nil) or
(BlobField = nil) or
(aID <= 0) or
(TableModelIndex < 0) or
(Model.Tables[TableModelIndex] <> fStoredClass) then
result := false
else
try
query := BsonVariant(['_id', aID]);
FieldName := fStoredClassMapping^.InternalToExternal(BlobField);
BsonVariantType.FromBinary(BlobData, bbtGeneric, blob);
update := BsonVariant(['$set', BsonVariant([FieldName, blob])]);
fCollection.Update(query, update);
if Owner <> nil then
begin
fStoredClassRecordProps.FieldBitsFromBlobField(BlobField, AffectedField);
Owner.InternalUpdateEvent(oeUpdateBlob, TableModelIndex, aID, '',
@AffectedField, nil);
Owner.FlushInternalDBCache;
end;
result := true;
except
result := false;
end;
end;
function TRestStorageMongoDB.UpdateBlobFields(Value: TOrm): boolean;
var
query, blob: variant;
update: TDocVariantData;
info: TOrmPropInfo;
blobRaw: RawByteString;
aID: TID;
f: PtrInt;
begin
result := false;
if (fCollection = nil) or
(POrmClass(Value)^ <> fStoredClass) or
(Value = nil) then
exit;
aID := Value.ID;
if aID <= 0 then
exit;
query := BsonVariant(['_id', aID]);
update.Init(JSON_FAST);
for f := 0 to fStoredClassRecordProps.Fields.Count - 1 do
begin
info := fStoredClassRecordProps.Fields.List[f];
if info.OrmFieldType = oftBlob then
begin
(info as TOrmPropInfoRttiRawBlob).GetBlob(Value, blobRaw);
BsonVariantType.FromBinary(blobRaw, bbtGeneric, blob);
update.AddValue(fStoredClassMapping^.ExtFieldNames[f], blob);
end;
end;
if update.Count > 0 then
try
fCollection.Update(query, BsonVariant(['$set', variant(update)]));
if Owner <> nil then
begin
Owner.InternalUpdateEvent(oeUpdateBlob, fStoredClassProps.TableIndex, aID,
'', @fStoredClassRecordProps.FieldBits[oftBlob], nil);
Owner.FlushInternalDBCache;
end;
result := true;
except
result := false;
end;
end;
function TRestStorageMongoDB.EngineDelete(TableModelIndex: integer;
ID: TID): boolean;
begin
result := false;
if (fCollection <> nil) and
(TableModelIndex >= 0) and
(Model.Tables[TableModelIndex] = fStoredClass) and
(ID > 0) then
try
if fBatchMethod <> mNone then
if fBatchMethod <> mDelete then
exit
else
AddID(fBatchIDs, fBatchIDsCount, ID)
else
begin
if Owner <> nil then
begin
// notify BEFORE deletion
Owner.InternalUpdateEvent(oeDelete, TableModelIndex, ID, '', nil, nil);
Owner.FlushInternalDBCache;
end;
fCollection.RemoveOne(ID);
end;
result := true;
except
result := false;
end;
end;
function TRestStorageMongoDB.EngineDeleteWhere(TableModelIndex: integer;
const SqlWhere: RawUtf8; const IDs: TIDDynArray): boolean;
var
i: PtrInt;
begin
// here we use the pre-computed IDs[]
result := false;
if (fCollection <> nil) and
(TableModelIndex >= 0) and
(Model.Tables[TableModelIndex] = fStoredClass) and
(IDs <> nil) then
try
if Owner <> nil then // notify BEFORE deletion
for i := 0 to high(IDs) do
Owner.InternalUpdateEvent(oeDelete, TableModelIndex, IDs[i], '', nil, nil);
fCollection.Remove(
BsonVariant(['_id',
BsonVariant(['$in', BsonVariantFromInt64s(TInt64DynArray(IDs))])]));
if Owner <> nil then
Owner.FlushInternalDBCache;
result := true;
except
result := false;
end;
end;
procedure TRestStorageMongoDB.JsonFromDoc(var doc: TDocVariantData;
var result: RawUtf8);
var
i: PtrInt;
name: RawUtf8;
W: TJsonWriter;
temp: TTextWriterStackBuffer; // shared fTempBuffer is not protected now
begin
if (doc.VarType <> DocVariantType.VarType) or
(doc.Kind <> dvObject) or
(doc.Count = 0) then
begin
result := '';
exit;
end;
W := TJsonWriter.CreateOwnedStream(temp);
try
W.AddDirect('{');
for i := 0 to doc.Count - 1 do
begin
name := fStoredClassMapping^.ExternalToInternalOrNull(doc.Names[i]);
if name = '' then
EOrmMongoDB.RaiseUtf8('%.JsonFromDoc: Unknown field [%] for %',
[self, doc.Names[i], fStoredClass]);
W.AddProp(pointer(name), Length(name));
W.AddVariant(doc.Values[i], twJsonEscape);
W.AddComma;
end;
W.CancelLastComma('}');
W.SetText(result);
finally
W.Free;
end;
end;
function TRestStorageMongoDB.EngineRetrieve(TableModelIndex: integer;
ID: TID): RawUtf8;
var
doc: variant;
begin
result := '';
if (fCollection = nil) or
(ID <= 0) then
exit;
doc := fCollection.FindDoc(
BsonVariant(['_id', ID]), fBsonProjectionSimpleFields, 1);
JsonFromDoc(_Safe(doc)^, result);
end;
function TRestStorageMongoDB.EngineRetrieveBlob(TableModelIndex: integer;
aID: TID; BlobField: PRttiProp; out BlobData: RawBlob): boolean;
var
doc: variant;
data: TVarData;
FieldName: RawUtf8;
begin
if (fCollection = nil) or
(BlobField = nil) or
(aID <= 0) or
(TableModelIndex < 0) or
(Model.Tables[TableModelIndex] <> fStoredClass) then
result := false
else
try
FieldName := fStoredClassMapping^.InternalToExternal(BlobField);
doc := fCollection.FindDoc(
BsonVariant(['_id', aID]), BsonVariant([FieldName, 1]), 1);