forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmormot.db.nosql.mongodb.pas
4734 lines (4397 loc) · 181 KB
/
mormot.db.nosql.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
/// Database Framework MongoDB Direct Client
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.db.nosql.mongodb;
{
*****************************************************************************
MongoDB Client for NoSQL Data Access
- MongoDB Wire Protocol Definitions
- MongoDB Protocol Classes
- MongoDB Client Classes
Note: This driver uses the new OP_MSG/OP_COMPRESSED Wire protocol, mandatory
since MongoDB 5.1/6.0. Define MONGO_OLDPROTOCOL conditional for your project
if you want to connect to deprecated < 3.6 MongoDB instances.
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
variants,
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.buffers,
mormot.core.json,
mormot.core.variants,
mormot.core.datetime,
mormot.core.data,
mormot.core.perf,
mormot.core.log,
mormot.core.rtti,
mormot.lib.z,
mormot.crypt.core,
mormot.db.core,
mormot.db.nosql.bson,
mormot.net.sock;
{ ************ MongoDB Wire Protocol Definitions }
type
/// store the binary raw data of a database response to a client message
TMongoReply = RawByteString;
/// store the genuine identifier of a Mongo cursor
// - used to retrieve results in batches
TMongoCursorID = Int64;
/// internal low-level binary structure mapping all message headers
TMongoWireHeader = packed record
/// total message length, including the header
MessageLength: integer;
/// identifier of this message
RequestID: integer;
/// retrieve the RequestID from the original request
ResponseTo: integer;
/// low-level code of the message
// - equal to OP_MSG = 2013, unless MONGO_OLDPROTOCOL is set and
// SendAndGetReply() will map it to a high-level TMongoOperation,
// or equal to OP_COMPRESSED = 2012 for a compressed message
OpCode: integer;
end;
PMongoWireHeader = ^TMongoWireHeader;
{$ifdef MONGO_OLDPROTOCOL}
/// internal low-level binary structure mapping the TMongoReply header
// - used e.g. by TMongoReplyCursor and TMongoConnection.SendAndGetReply()
TMongoReplyHeader = packed record
/// standard message header
Header: TMongoWireHeader;
/// response flags
ResponseFlags: integer;
/// cursor identifier if the client may need to perform further opGetMore
CursorID: TMongoCursorID;
/// where in the cursor this reply is starting
StartingFrom: integer;
/// number of documents in the reply
NumberReturned: integer;
end;
/// points to an low-level binary structure mapping the TMongoReply header
// - so that you can write e.g.
// ! PMongoReplyHeader(aMongoReply)^.RequestID
PMongoReplyHeader = ^TMongoReplyHeader;
/// the available MongoDB driver Request Opcodes
// - opReply: database reply to a client request - ResponseTo shall be set
// - opMsgOld: generic msg command followed by a string (deprecated)
// - opUpdate: update document
// - opInsert: insert new document
// - opQuery: query a collection
// - opGetMore: get more data from a previous query
// - opDelete: delete documents
// - opKillCursors: notify database client is done with a cursor
// - opMsg: new OP_MSG layout introduced in MongoDB 3.6 - replaces all other
// opcodes, which are deprecated since 5.0, and removed since 5.1/6.0
TMongoOperation = (
opReply,
opMsgOld,
opUpdate,
opInsert,
opQuery,
opGetMore,
opDelete,
opKillCursors,
opMsg);
/// define how an opQuery operation will behave
// - if mqfTailableCursor is set, cursor is not closed when the last data
// is retrieved
// - if mqfSlaveOk is set, it will allow query of replica slave; normally
// this returns an error except for namespace "local"
// - mqfOplogReplay is internal replication use only - driver should not set
// - if mqfNoCursorTimeout is set, the server normally does not times out
// idle cursors after an inactivity period (10 minutes) to prevent
// excess memory use
// - if mqfAwaitData is to use with TailableCursor. If we are at the end
// of the data, block for a while rather than returning no data. After a
// timeout period, we do return as normal
// - if mqfExhaust is set, stream the data down full blast in multiple "more"
// packages, on the assumption that the client will fully read all data queried
// - if mqfPartial is set, it will get partial results from a mongos if
// some shards are down (instead of throwing an error)
TMongoQueryFlag = (
mqfTailableCursor = 1,
mqfSlaveOk,
mqfOplogReplay,
mqfNoCursorTimeout,
mqfAwaitData,
mqfExhaust,
mqfPartial);
/// define how a TMongoRequestQuery message will behave
TMongoQueryFlags = set of TMongoQueryFlag;
/// define an opReply message execution content
// - mrfCursorNotFound will be set when getMore is called but the cursor id
// is not valid at the server; returned with zero results
// - mrfQueryFailure is set when the query failed - results consist of one
// document containing an "$err" field describing the failure
// - mrfShardConfigStale should not be used by client, just by Mongos
// - mrfAwaitCapable is set when the server supports the AwaitData Query
// option (always set since Mongod version 1.6)
TMongoReplyCursorFlag = (
mrfCursorNotFound,
mrfQueryFailure,
mrfShardConfigStale,
mrfAwaitCapable);
/// define a TMongoReplyCursor message execution content
TMongoReplyCursorFlags = set of TMongoReplyCursorFlag;
/// ready-to-be displayed text of a TMongoOperation item
function ToText(op: TMongoOperation): PShortString; overload;
{$else}
/// flags that modify the format and behavior of opMsg execution content
// - mmfChecksumPresent indicates that a crc32c checksum is supplied
// - mmfMoreToCome is set when another message will follow this one without
// further action from the receiver. The receiver MUST NOT send another
// message until receiving one with mmfMoreToCome is not set as sends may
// block, causing deadlock. Requests with the mmfMoreToCome flag set will not
// receive a reply. Replies will only have this set in response to requests
// with the mmfExhaustAllowed bit set.
// - mmfExhaustAllowed indicates the client supports the mmfMoreToCome flag
// (currently never set, because we don't support it yet)
// - by definition, is used for TMongoQueryFlags and TMongoReplyCursorFlags
TMongoMsgFlag = (
mmfChecksumPresent,
mmfMoreToCome,
mmfExhaustAllowed = 16);
TMongoMsgFlags = set of TMongoMsgFlag;
/// the kind of sections for a opMsg content
// - mmkBody indicates that the section is encoded as a single BSON object:
// this is the standard command request and reply body
// - mmkSequence is used when there are several sections, encoded as the
// 32-bit size, then the ASCIIZ document identifier, then zero or more
// BSON objects, ending one the declared size has been reached
// - mmkInternal is used for internal purposes and rejected by the server
TMongoMsgKind = (
mmkBody,
mmkSequence,
mmkInternal);
TMongoQueryFlags = TMongoMsgFlags;
TMongoReplyCursorFlags = TMongoMsgFlags;
{$endif MONGO_OLDPROTOCOL}
{ ************ MongoDB Protocol Classes }
const
/// MongoDB server default IP port
MONGODB_DEFAULTPORT = 27017;
type
/// exception type used for MongoDB process
EMongoException = class(ECoreDBException);
/// define how an opUpdate operation will behave
// - if mufUpsert is set, the database will insert the supplied object into
// the collection if no matching document is found
// - if mufMultiUpdate is set, the database will update all matching objects
// in the collection; otherwise (by default) only updates first matching doc
// - if mufContinueOnError is set, the database will not stop processing
// bulk updates if one fails (e.g. due to duplicate IDs)
// - if mufBypassDocumentValidation is set, update would be allowed even
// if the content does not meet the validation requirements
TMongoUpdateFlag = (
mufUpsert,
mufMultiUpdate,
mufContinueOnError,
mufBypassDocumentValidation);
/// define how a TMongoRequestUpdate message will behave
TMongoUpdateFlags = set of TMongoUpdateFlag;
/// define how an opInsert operation will behave
// - if mifContinueOnError is set, the database will not stop processing
// bulk inserts if one fails (e.g. due to duplicate IDs); this makes bulk
// insert behave similarly to a series of single inserts, except lastError
// will be set if any insert fails, not just the last one
// - if mifBypassDocumentValidation is set, insertion would be allowed even
// if the content does not meet the validation requirements
TMongoInsertFlag = (
mifContinueOnError,
mifBypassDocumentValidation);
/// define how a TMongoRequestInsert message will behave
TMongoInsertFlags = set of TMongoInsertFlag;
/// define how an opDelete operation will behave
// - if mdfSingleRemove is set, the database will remove only the first
// matching document in the collection. Otherwise (by default) all matching
// documents will be removed
// - if mdfContinueOnError is set, the database will not stop processing
// bulk deletes if one fails
TMongoDeleteFlag = (
mdfSingleRemove,
mdfContinueOnError);
/// define how a TMongoRequestDelete message will behave
TMongoDeleteFlags = set of TMongoDeleteFlag;
/// abstract class used to create MongoDB Wire Protocol client messages
// - see http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol
// - this class is not tight to the connection class itself (which is one
// known limitation of TMongoWire for instance)
TMongoRequest = class(TBsonWriter)
protected
fRequestID: integer;
fResponseTo: integer;
fNumberToReturn: integer;
fDatabaseName, fCollectionName: RawUtf8;
fBsonDocument: TBsonDocument;
{$ifdef MONGO_OLDPROTOCOL}
fFullCollectionName: RawUtf8;
fRequestOpCode: TMongoOperation;
/// append a query parameter as a BSON document
// - param can be a TDocVariant, e.g. created with:
// ! _JsonFast('{name:"John",age:{$gt:21}}');
// ! _JsonFastFmt('{name:?,age:{$gt:?}}',[],['John',21]);
// ! _JsonFastFmt('{name:?,field:/%/i}',['acme.*corp'],['John']);
// - param can be a TBsonVariant containing a TBsonDocument raw binary block
// created e.g. from:
// ! BsonVariant(['BSON',_Arr(['awesome',5.05, 1986])])
// ! BsonVariantType[Bson(['BSON',_Arr(['awesome',5.05, 1986])])]
// - if param is null, it will append a void document
// - if param is a string, it will be converted as expected by most
// database commands, e.g.
// ! TMongoRequestQuery.Create('admin.$cmd','buildinfo',[],1)
// will query { buildinfo: 1 } to the admin.$cmd collection, i.e.
// $ admin.$cmd.findOne( { buildinfo: 1 } )
procedure BsonWriteParam(const paramDoc: variant);
{$endif MONGO_OLDPROTOCOL}
public
/// write a standard Message Header for MongoDB client
// - opCode is the type of the message
// - requestID is a client or database-generated identifier that uniquely
// identifies this message: in case of opQuery or opGetMore messages, it will
// be sent in the responseTo field from the database
// - responseTo is the requestID taken from previous opQuery or opGetMore
{$ifdef MONGO_OLDPROTOCOL}
constructor Create(const FullCollectionName: RawUtf8;
opCode: TMongoOperation; requestID, responseTo: integer); reintroduce;
{$else}
constructor Create(const Database, Collection: RawUtf8); reintroduce;
{$endif MONGO_OLDPROTOCOL}
/// flush the content and return the whole binary encoded stream
// - expect the TBsonWriter instance to have been created with reintroduced
// Create() specific constructors inheriting from this TMongoRequest class
// - this overridden version will adjust the size in the message header
procedure ToBsonDocument(var result: TBsonDocument); override;
/// write the main parameters of the request as JSON
procedure ToJson(W: TJsonWriter; Mode: TMongoJsonMode); overload; virtual;
/// write the main parameters of the request as JSON
function ToJson(Mode: TMongoJsonMode): RawUtf8; overload;
/// identify the message, after call to any reintroduced Create() constructor
property MongoRequestID: integer
read fRequestID;
/// retrieve the NumberToReturn parameter as set to the constructor
property NumberToReturn: integer
read fNumberToReturn;
/// the associated collection name, e.g. 'test'
// - for OP_MSG/OP_COMPRESSED, only set for "find", "aggregate" or "getMore"
property CollectionName: RawUtf8
read fCollectionName;
{$ifdef MONGO_OLDPROTOCOL}
/// the associated full collection name, e.g. 'db.test'
property FullCollectionName: RawUtf8
read fFullCollectionName;
{$endif MONGO_OLDPROTOCOL}
/// the associated full collection name, e.g. 'db'
property DatabaseName: RawUtf8
read fDatabaseName;
end;
{$ifdef MONGO_OLDPROTOCOL}
/// a MongoDB client abstract ancestor which is able to create a BULK
// command message for MongoDB >= 2.6 instead of older dedicated Wire messages
TMongoRequestWritable = class(TMongoRequest)
protected
public
end;
/// a MongoDB client message to update a document in a collection
TMongoRequestUpdate = class(TMongoRequestWritable)
protected
fSelector, fUpdate: TVarData;
public
/// initialize a MongoDB client message to update a document in a collection
// - FullCollectionName is e.g. 'dbname.collectionname'
// - how the update will be processed can be customized via Flags
// - Selector is the BSON document query to select the document, supplied as
// TDocVariant - i.e. created via _JsonFast() or _JsonFastFmt() - or as
// TBsonVariant - i.e. created via BsonVariant() - or null if all documents
// are to be updated
// - Update is the BSON document specification of the update to perform,
// supplied as TDocVariant or TBsonVariant
// - there is no response to an opUpdate message
constructor Create(const FullCollectionName: RawUtf8;
const Selector, Update: variant;
Flags: TMongoUpdateFlags = []); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJson(W: TJsonWriter; Mode: TMongoJsonMode); override;
end;
/// a MongoDB client message to insert one or more documents in a collection
TMongoRequestInsert = class(TMongoRequestWritable)
public
/// initialize a MongoDB client message to insert one or more documents in
// a collection, supplied as variants
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Documents is an array of TDocVariant or TBsonVariant - i.e. created via
// _JsonFast() _JsonFastFmt() or BsonVariant()
// - there is no response to an opInsert message
constructor Create(const FullCollectionName: RawUtf8;
const Documents: array of variant;
Flags: TMongoInsertFlags = []); reintroduce; overload;
/// initialize a MongoDB client message to insert one or more documents in
// a collection, supplied as raw BSON binary
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Documents is the low-level concatenation of BSON documents, created
// e.g. with a TBsonWriter stream
// - there is no response to an opInsert message
constructor Create(const FullCollectionName: RawUtf8;
const Documents: TBsonDocument;
Flags: TMongoInsertFlags = []); reintroduce; overload;
/// initialize a MongoDB client message to insert one or more documents in
// a collection, supplied as JSON objects
// - FullCollectionName is e.g. 'dbname.collectionname'
// - JSONDocuments is an array of JSON objects
// - there is no response to an opInsert message
// - warning: JSONDocuments[] buffer will be modified in-place during
// parsing, so a private copy may have to be made by the caller
constructor Create(const FullCollectionName: RawUtf8;
const JSONDocuments: array of PUtf8Char;
Flags: TMongoInsertFlags = []); reintroduce; overload;
end;
/// a MongoDB client message to delete one or more documents in a collection
TMongoRequestDelete = class(TMongoRequestWritable)
protected
fQuery: TVarData;
public
/// initialize a MongoDB client message to delete one or more documents in
// a collection
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Selector is the BSON document query to select the document, supplied as
// TDocVariant - i.e. created via _JsonFast() or _JsonFastFmt() - or as
// TBsonVariant - i.e. created via BsonVariant() - or null if all documents
// are to be deleted
// - warning: CreateDelete('db.coll',null) can be expensive so you should
// better drop the whole collection
// - there is no response to an opDelete message
constructor Create(const FullCollectionName: RawUtf8;
const Selector: variant;
Flags: TMongoDeleteFlags = []); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJson(W: TJsonWriter; Mode: TMongoJsonMode); override;
end;
/// a MongoDB client message to continue the query of one or more documents
// in a collection, after a TMongoRequestQuery message
TMongoRequestGetMore = class(TMongoRequest)
public
/// initialize a MongoDB client message to continue the query of one or more
// documents in a collection, after a opQuery / TMongoRequestQuery message
// - FullCollectionName is e.g. 'dbname.collectionname'
// - you can specify the number of documents to return (e.g. from previous
// opQuery response)
// - CursorID should have been retrieved within an opReply message from the
// database
constructor Create(const FullCollectionName: RawUtf8;
NumberToReturn: integer; CursorID: TMongoCursorID); reintroduce;
end;
/// a MongoDB client message to close one or more active cursors
TMongoRequestKillCursor = class(TMongoRequest)
protected
fCursors: TInt64DynArray;
public
/// initialize a MongoDB client message to close one or more active cursors
// in the database
// - it is mandatory to ensure that database resources are reclaimed by
// the client at the end of the query
// - if a cursor is read until exhausted (read until opQuery or opGetMore
// returns zero for the CursorId), there is no need to kill the cursor
// - there is no response to an opKillCursor message
constructor Create(const FullCollectionName: RawUtf8;
const CursorIDs: array of TMongoCursorID); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJson(W: TJsonWriter; Mode: TMongoJsonMode); override;
end;
/// a MongoDB client message to query one or more documents in a collection
// - implemented using opMsg - or opQuery with MONGO_OLDPROTOCOL conditional
TMongoRequestQuery = class(TMongoRequest)
protected
fNumberToSkip: integer;
fQuery, fReturnFieldsSelector: TVarData;
public
/// initialize a MongoDB client message to query one or more documents in
// a collection from a specified Cursor identifier
// - FullCollectionName is e.g. 'dbname.collectionname'
// - Query is the BSON document query to select the document, supplied as
// TDocVariant - i.e. created via _JsonFast() or _JsonFastFmt() - or null
// if all documents are to be retrieved - for instance:
// ! _JsonFast('{name:"John",age:{$gt:21}}');
// ! _JsonFastFmt('{name:?,age:{$gt:?}}',[],['John',21]);
// ! _JsonFastFmt('{name:?,field:/%/i}',['acme.*corp'],['John']);
// - if Query is a string, it will be converted as expected by most
// database commands, e.g.
// $ TMongoRequestQuery.Create('admin.$cmd','buildinfo',[],1)
// will query { buildinfo: 1 } to the admin.$cmd collection, i.e.
// $ admin.$cmd.findOne( { buildinfo: 1 } )
// - Query can also be a TBsonVariant, e.g. created with:
// ! BsonVariant('{name:?,age:{$gt:?}}',[],['John',21])
// - ReturnFieldsSelector is an optional selector (set to null if not
// applicable) as a BSON document that limits the fields in the returned
// documents, supplied as TDocVariant or TBsonVariant - e.g. created via:
// ! BsonVariantFieldSelector('a,b,c');
// ! BsonVariantFieldSelector(['a','b','c']);
// ! BsonVariant('{a:1,b:1,c:1}');
// ! _JsonFast('{a:1,b:1,c:1}');
// - if ReturnFieldsSelector is a string, it will be converted into
// $ { ReturnFieldsSelector: 1 }
constructor Create(const FullCollectionName: RawUtf8;
const Query, ReturnFieldsSelector: variant; NumberToReturn: integer;
NumberToSkip: integer = 0; Flags: TMongoQueryFlags = []); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJson(W: TJsonWriter; Mode: TMongoJsonMode); override;
/// retrieve the NumberToSkip parameter as set to the constructor
property NumberToSkip: integer
read fNumberToSkip;
end;
{$else}
/// a MongoDB client message to access a collection
// - implements the OP_MSG/OP_COMPRESSED opcodes for all its query or
// write process to the DB
TMongoMsg = class(TMongoRequest)
protected
fCommand: variant;
fCompressed: integer; // zlib compression ratio, 0 if uncompressed
public
/// initialize a MongoDB client message to access a database instance
// - Collection is set for "find" and "aggregate" commands, to unest any
// firstBatch/nextBatch arrays, and specify the collection name for "getMore"
constructor Create(Client: TObject; const Database, Collection: RawUtf8;
const Command: variant; Flags: TMongoMsgFlags; ToReturn: integer); reintroduce;
/// write the main parameters of the request as JSON
procedure ToJson(W: TJsonWriter; Mode: TMongoJsonMode); override;
end;
{$endif MONGO_OLDPROTOCOL}
/// map a MongoDB server reply message as sent back from the database
// - in response to TMongoMsg or TMongoRequestQuery / TMongoRequestGetMore
// for MONGO_OLDPROTOCOL
// - note: old opReply is removed since MongoDB 5.1 in favor of opMsg
// - you can use the record's methods to retrieve information about a given
// response, and navigate within all nested documents
// - several TMongoReplyCursor instances may map the same TMongoReply content
// - you can safely copy one TMongoReplyCursor instance to another
{$ifdef USERECORDWITHMETHODS}
TMongoReplyCursor = record
{$else}
TMongoReplyCursor = object
{$endif USERECORDWITHMETHODS}
private
fRequest: TMongoRequest;
fReply: TMongoReply;
fRequestID: integer;
fResponseTo: integer;
fResponseFlags: TMongoReplyCursorFlags;
fDocumentCount: integer;
fCursorID: TMongoCursorID;
fDocumentsOffset: TIntegerDynArray;
fFirstDocument, fCurrent: PByte;
fPosition: integer;
fLatestDocIndex: integer;
fLatestDocValue: variant;
fElapsedMS: Int64;
{$ifdef MONGO_OLDPROTOCOL}
fStartingFrom: integer;
procedure ComputeDocumentsList;
{$else}
fCompressed: integer; // zlib compression ratio, 0 if uncompressed
{$endif MONGO_OLDPROTOCOL}
function GetOneDocument(index: integer): variant;
public
/// initialize the cursor with a supplied binary reply from the server
// - will raise an EMongoException if the content is not valid
// - will populate all record fields with the supplied data
procedure Init(Request: TMongoRequest; const ReplyMessage: TMongoReply;
StartMS: Int64);
{$ifndef MONGO_OLDPROTOCOL}
/// extract the firstBatch/nextBatch: nested array after Init()
procedure ExtractBatch;
{$endif MONGO_OLDPROTOCOL}
/// iterate over the next document in the list, as a TDocVariant instance
// - return TRUE if the supplied document has been retrieved
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! doc: variant;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(doc) do
// ! writeln('Name: ',doc.Name,' FirstName: ',doc.FirstName);
function Next(out doc: variant;
option: TBsonDocArrayConversion = asDocVariantPerReference): boolean; overload;
/// iterate over the next document in the list, as BSON content
// - return TRUE if the supplied document has been retrieved - then doc
// points to a "int32 e_list #0" BSON document
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - this method is almost immediate, since the BSON raw binary is returned
// directly without any conversion
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! doc: PByte;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(doc) do
// ! writeln(BsonToJson(doc,0,modMongoShell)); // fast display
function Next(out doc: PByte): boolean; overload;
/// iterate over the next document in the list, as a BSON binary document
// - return TRUE if the supplied document has been retrieved - then doc
// points to a "int32 e_list #0" BSON document
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - this method is slightly slower than the one returning a PByte, since
// it will allocate a memory buffer to store the TBsonDocument binary
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! doc: TBsonDocument;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(doc) do
// ! writeln(BsonToJson(doc,0,modMongoShell)); // fast display
function Next(out Bson: TBsonDocument): boolean; overload;
/// iterate over the next document in the list, as JSON content
// - return TRUE if the supplied document has been retrieved
// - return FALSE if there is no more document to get - you can use the
// Rewind method to restart from the first document
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! json: RawUtf8;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! while Reply.Next(json,modMongoShell) do
// ! writeln(json); // fast display
function Next(out Json: RawUtf8;
Mode: TMongoJsonMode = modMongoStrict): boolean; overload;
/// let Next() overloaded methods point to the first document of this message
procedure Rewind;
/// retrieve a given document as a TDocVariant instance
// - this method won't use any cache (like Document[..] property), since
// it should be used with a local variant on stack as cache:
// ! var Reply: TMongoReply;
// ! doc: variant;
// ! i: integer;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! for i := 0 to Reply.DocumentCount-1 do
// ! begin
// ! GetDocument(i,doc);
// ! writeln('Name: ',doc.Name,' FirstName: ',doc.FirstName);
// ! end;
procedure GetDocument(index: integer; var result: variant);
/// return all documents content as a JSON array, or one JSON object
// if there is only one document in this reply
// - this method is very optimized and will convert the BSON binary content
// directly into JSON
procedure FetchAllToJson(W: TJsonWriter; Mode: TMongoJsonMode = modMongoStrict;
WithHeader: boolean = false; MaxSize: PtrUInt = 0);
/// return all documents content as a JSON array, or one JSON object
// if there is only one document in this reply
// - this method is very optimized and will convert the BSON binary content
// directly into JSON
function ToJson(Mode: TMongoJsonMode = modMongoStrict;
WithHeader: boolean = false; MaxSize: PtrUInt = 0): RawUtf8;
/// append all documents content to a dynamic array of TDocVariant
// - return the new size of the Dest[] array
function AppendAllToDocVariantDynArray(var Dest: TVariantDynArray): integer;
/// append all documents content to a TDocVariant array instance
// - if the supplied instance if not already a TDocVariant of kind dvArray,
// a new void instance will be created
// - return the new size of the Dest array
function AppendAllToDocVariant(var Dest: TDocVariantData): integer;
/// append all documents content to a BSON binary stream
// - Dest.Tag will be used to count the current item number in the resulting
// BSON array
procedure AppendAllToBson(Dest: TBsonWriter);
/// return a result as TDocVariant object or array
// - if there are no result, returns null
// - if there are one or several results, returns a TDocVariant array
procedure AppendAllAsDocVariant(var Dest: variant);
/// retrieve the context execution of this message
property ResponseFlags: TMongoReplyCursorFlags
read fResponseFlags;
/// identifier of this message
property RequestID: integer
read fRequestID;
/// retrieve the RequestID from the original request
property ResponseTo: integer
read fResponseTo;
/// access to the low-level binary reply message
property Reply: TMongoReply
read fReply;
/// cursor identifier if the client may need to perform further
// TMongoRequestGetMore messages
// - in the event that the result set of the query fits into one OP_REPLY
// message, CursorID will be 0
// - deprecated since MongoDB 5.0, and removed in MongoDB 6.0
property CursorID: TMongoCursorID
read fCursorID;
{$ifdef MONGO_OLDPROTOCOL}
/// where in the cursor this reply is starting
// - deprecated since MongoDB 5.0, and removed in MongoDB 6.0
property StartingFrom: integer
read fStartingFrom;
{$endif MONGO_OLDPROTOCOL}
/// number of documents in the reply
property DocumentCount: integer
read fDocumentCount;
/// points to the first document binary
// - i.e. just after the Reply header
property FirstDocument: PByte
read fFirstDocument;
/// direct access to the low-level BSON binary content of each document
property DocumentOffset: TIntegerDynArray
read fDocumentsOffset;
/// retrieve a given document as a TDocVariant instance
// - could be used e.g. as:
// ! var Reply: TMongoReply;
// ! i: integer;
// ! ...
// ! Reply.Init(ResponseMessage);
// ! for i := 0 to Reply.DocumentCount-1 do
// ! writeln('Name: ',Reply.Document[i].Name,' FirstName: ',Reply.Document[i].FirstName);
// - note that there is an internal cache for the latest retrieved document
// by this property, so that you can call Reply.Document[i] several times
// without any noticeable speed penalty
property Document[index: integer]: variant
read GetOneDocument;
/// position of the Next() call, starting at 0, up to DocumentCount
property Position: integer
read fPosition;
end;
{ ************ MongoDB Client Classes }
type
/// the available options for a TMongoClient client
// - mcoTls is to be defined if the TCP socket should use TLS encryption
// - mcoZlibCompressor is to be included if ZLIB compression is enabled
TMongoClientOption = (
mcoTls,
mcoZlibCompressor);
/// set of available options for a TMongoClient client
TMongoClientOptions = set of TMongoClientOption;
const
/// the TMongoClient.Create default options
// - we enable zlib compression by default for messages > 1KB
MONGODB_DEFAULTOPTIONS = [mcoZlibCompressor];
type
/// event callback signature for iterative process of TMongoConnection
TOnMongoConnectionReply = procedure(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque) of object;
{$M+}
TMongoClient = class;
TMongoDatabase = class;
TMongoCollection = class;
/// one TCP/IP connection to a MongoDB server
// - all access will be protected by a mutex (critical section): it is thread
// safe but you may use one TMongoClient per thread or a connection pool, for
// better performance
TMongoConnection = class
protected
fSafe: TOSLock;
fLocked: cardinal;
fClient: TMongoClient;
fSocket: TCrtSocket;
fServerAddress: RawUtf8;
fServerPort: integer;
procedure Lock;
procedure UnLock;
function Send(Request: TMongoRequest): boolean;
function GetOpened: boolean;
function GetLocked: boolean;
{$ifdef HASINLINE} inline; {$endif}
// will call TMongoReplyCursor.FetchAllToJson(TJsonWriter(Opaque))
procedure ReplyJsonStrict(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
procedure ReplyJsonExtended(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
procedure ReplyJsonNoMongo(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
// will call TMongoReplyCursor.AppendAllToDocVariantDynArray(TVariantDynArray(Opaque))
procedure ReplyDocVariants(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
// will call TMongoReplyCursor.AppendSingleAsDocVariant(TDocVariantData(Opaque))
procedure ReplyDocVariant(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
// will call TMongoReplyCursor.AppendAllToBson(TBsonWrite(Opaque))
procedure ReplyBson(Request: TMongoRequest;
const Reply: TMongoReplyCursor; var Opaque);
public
/// initialize the connection to the corresponding MongoDB server
// - the server address is either a host name, or an IP address
// - if no server address is specified, will try to connect to localhost
// - this won't create the connection, until Open method is executed
constructor Create(const aClient: TMongoClient; const aServerAddress: RawUtf8;
aServerPort: integer = MONGODB_DEFAULTPORT); reintroduce;
/// release the connection, including the socket
destructor Destroy; override;
/// connect to the MongoDB server
// - will raise an EMongoException on error
procedure Open;
/// disconnect from MongoDB server
// - will raise an EMongoException on error
procedure Close;
/// low-level method to send a request to the server
// - if Request is not either TMongoRequestQuery or TMongoRequestGetMore,
// will raise an EMongoException
// - then will return the reply message as sent back by the database,
// ready to be accessed using a TMongoReplyCursor wrapper
procedure SendAndGetReply(Request: TMongoRequest; out result: TMongoReply);
/// low-level method to send a request to the server, and return a cursor
// - if Request is not either TMongoRequestQuery or TMongoRequestGetMore,
// will raise an EMongoException
// - then will parse and return a cursor to the reply message as sent back
// by the database, with logging if necessary
// - raise an EMongoException if mrfQueryFailure flag is set in the reply
procedure SendAndGetCursor(Request: TMongoRequest; var Result: TMongoReplyCursor);
/// low-level method to send a query to the server, calling a callback event
// on each reply
// - is used by GetDocumentsAndFree, GetBsonAndFree and GetJsonAndFree
// methods to receive the whole document (you should better call those)
// - the supplied Query instance will be released when not needed any more
procedure SendAndGetRepliesAndFree(Request: TMongoRequest;
const OnEachReply: TOnMongoConnectionReply; var Opaque);
/// send a query to the server, returning a TDocVariant instance containing
// all the incoming data
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
// - if Query.NumberToReturn<>1, it will return either null or a dvArray
// kind of TDocVariant containing all returned items
// - if Query.NumberToReturn=1, then it will return either null or a
// single TDocVariant instance
function GetDocumentsAndFree(Query: TMongoRequest): variant; overload;
/// send a query to the server, returning a TDocVariant instance containing
// all the incoming data
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
// - if Query.NumberToReturn<>1, it will return either null or a dvArray
// kind of TDocVariant containing all returned items
// - if Query.NumberToReturn=1, then it will return either null or a
// single TDocVariant instance
procedure GetDocumentsAndFree(Query: TMongoRequest;
var result: variant); overload;
/// send a query to the server, returning a dynamic array of TDocVariant
// instance containing all the incoming data
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
procedure GetDocumentsAndFree(Query: TMongoRequest;
var result: TVariantDynArray); overload;
/// send a query to the server, returning a TBsonDocument instance containing
// all the incoming data, as raw binary BSON document containing an array
// of the returned items
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - the supplied Query instance will be released when not needed any more
function GetBsonAndFree(Query: TMongoRequest): TBsonDocument;
/// send a query to the server, returning all the incoming data as JSON
// - will send the Request message, and any needed TMongoRequestGetMore
// messages to retrieve all the data from the server
// - this method is very optimized and will convert the BSON binary content
// directly into JSON, in either modMongoStrict or modMongoShell layout
// (modNoMongo will do the same as modMongoStrict)
// - if Query.NumberToReturn<>1, it will return either 'null' or a '[..]'
// JSON array with all the incoming documents retrieved from the server
// - if Query.NumberToReturn=1, it will return either 'null' or a single
// '{...}' JSON object
// - the supplied Query instance will be released when not needed any more
function GetJsonAndFree(Query: TMongoRequest; Mode: TMongoJsonMode): RawUtf8;
{$ifdef MONGO_OLDPROTOCOL}
/// send a message to the MongoDB server
// - will apply Client.WriteConcern policy, and run an EMongoException
// in case of any error
// - the supplied Request instance will be released when not needed any more
// - by default, it will follow Client.WriteConcern pattern - but you can
// set NoAcknowledge = TRUE to avoid calling the getLastError command
// - will return the getLastError reply (if retrieved from server)
function SendAndFree(Request: TMongoRequest;
NoAcknowledge: boolean = false): variant;
{$endif MONGO_OLDPROTOCOL}
/// run a database command, supplied as a TDocVariant, TBsonVariant or a
// string, and return the a TDocVariant instance
// - see http://docs.mongodb.org/manual/reference/command for a list
// of all available commands
// - for instance:
// ! RunCommand('test',_ObjFast(['dbStats',1,'scale',1024],stats);
// ! RunCommand('test',BsonVariant(['dbStats',1,'scale',1024],stats);
// ! RunCommand('admin','buildinfo',fServerBuildInfo);
// - the message will be returned by the server as a single TDocVariant
// instance (since the associated TMongoRequestQuery.NumberToSkip=1)
// - in case of any error, the error message is returned as text
// - in case of success, this method will return ''
// - if you expects the result to return a cursor, e.g. for a "find" or
// "aggregate" command, you can specify aCollectionName so that the "cursor"
// response will be parsed and its nested batch array, and call "getMore"
// if needed
function RunCommand(const aDatabaseName: RawUtf8;
const command: variant; var returnedValue: variant;
flags: TMongoQueryFlags = []; const aCollectionName: RawUtf8 = ''): RawUtf8; overload;
/// run a database command, supplied as a TDocVariant, TBsonVariant or a
// string, and return the raw BSON document array of received items
// - this overloaded method can be used on huge content to avoid the slower
// conversion to an array of TDocVariant instances
// - in case of success, this method will return TRUE, or FALSE on error
// - if you expects the result to return a cursor, e.g. for a "find" or
// "aggregate" command, you can specify aCollectionName so that the "cursor"
// response will be parsed and its nested batch array, and call "getMore"
// if needed
function RunCommand(const aDatabaseName: RawUtf8;
const command: variant; var returnedValue: TBsonDocument;
flags: TMongoQueryFlags = []; const aCollectionName: RawUtf8 = ''): boolean; overload;
/// return TRUE if the Open method has successfully been called
property Opened: boolean
read GetOpened;
/// access to the corresponding MongoDB server
property Client: TMongoClient
read fClient;
/// direct access to the low-level TCP/IP communication socket
property Socket: TCrtSocket
read fSocket;
/// is TRUE when the connection is busy
property Locked: boolean
read GetLocked;
published
/// read-only access to the supplied server address
// - the server address is either a host name, or an IP address
property ServerAddress: RawUtf8
read fServerAddress;
/// read-only access to the supplied server port
// - the server Port is MONGODB_DEFAULTPORT (27017) by default
property ServerPort: integer
read fServerPort;
end;
/// array of TCP connection to a MongoDB Replica Set
// - first item [0] is the Primary member
// - other items [1..] are the Secondary members
TMongoConnectionDynArray = array of TMongoConnection;
/// define Read Preference Modes to a MongoDB replica set
// - Important: All read preference modes except rpPrimary may return stale
// data because secondaries replicate operations from the primary with some
// delay - ensure that your application can tolerate stale data if you choose
// to use a non-primary mode
// - rpPrimary: Default mode - all operations read from the current replica
// set primary
// - rpPrimaryPreferred: in most situations, operations read from the primary
// but if it is unavailable, operations read from secondary members.
// - rpPsecondary: all operations read from the secondary members
// of the replica set
// - rpPsecondaryPreferred: in most situations, operations read from
// secondary members but if no secondary members are available, operations
// read from the primary
// rpNearest: read from the member of the replica set with the least network
// latency, irrespective of whether that member is a primary or secondary
// (in practice, we won't use latency, just a random distribution)
TMongoClientReplicaSetReadPreference = (
rpPrimary,
rpPrimaryPreferred,
rpSecondary,
rpSecondaryPreferred,
rpNearest);
/// define Write Concern property of a MongoDB connection
// - Write concern describes the guarantee that MongoDB provides when
// reporting on the success of a write operation. The strength of the write
// concerns determine the level of guarantee. When inserts, updates and
// deletes have a weak write concern, write operations return quickly. In
// some failure cases, write operations issued with weak write concerns may
// not persist. With stronger write concerns, clients wait after sending a
// write operation for MongoDB to confirm the write operations. MongoDB
// provides different levels of write concern to better address the specific
// needs of applications. Clients may adjust write concern to ensure that
// the most important operations persist successfully to an entire
// MongoDB deployment. For other less critical operations, clients can
// adjust the write concern to ensure faster performance rather than
// ensure persistence to the entire deployment.
// - wcAcknowledged is the default safe mode: the mongod confirms the
// receipt of the write operation. Acknowledged write concern allows clients
// to catch network, duplicate key, and other errors.
// - with wcJournaled, the mongod acknowledges the write operation only
// after committing the data to the journal. This write concern ensures that
// MongoDB can recover the data following a shutdown or power interruption.
// - wcReplicaAcknowledged will guarantee that the write operation propagates
// to at least one member of a replica set
// - with wcUnacknowledged, MongoDB does not acknowledge the receipt of
// write operation. Unacknowledged is similar to errors ignored; however,
// drivers attempt to receive and handle network errors when possible. The
// driver's ability to detect network errors depends on the system's
// networking configuration.
// - with wcErrorsIgnored, MongoDB does not acknowledge write operations.
// With this level of write concern, the client cannot detect failed write
// operations. These errors include connection errors and mongod exceptions
// such as duplicate key exceptions for unique indexes. Although the errors
// ignored write concern provides fast performance, this performance gain
// comes at the cost of significant risks for data persistence and durability.
// WARNING: Do not use wcErrorsIgnored write concern in normal operation.
TMongoClientWriteConcern = (
wcAcknowledged,
wcJournaled,
wcReplicaAcknowledged,
wcUnacknowledged,