forked from tuurke63/DelphiMongoDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrijjy.MongoDB.pas
2810 lines (2461 loc) · 101 KB
/
Grijjy.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
unit Grijjy.MongoDB;
{ < Main interface to MongoDB }
{$INCLUDE 'Grijjy.inc'}
interface
uses
System.SysUtils,
System.Generics.Collections,
Grijjy.Bson,
Grijjy.Bson.IO,
Grijjy.MongoDB.Protocol,
Grijjy.MongoDB.Queries;
type
{ MongoDB validation types
https://docs.mongodb.com/manual/reference/command/create/ }
TgoMongoValidationLevel = (vlOff, vlStrict, vlModerate);
TgoMongoValidationLevelHelper = record helper for TgoMongoValidationLevel
public
function ToString: string;
end;
TgoMongoValidationAction = (vaError, vaWarn);
TgoMongoValidationActionHelper = record helper for TgoMongoValidationAction
public
function ToString: string;
end;
{ MongoDB collation
https://docs.mongodb.com/manual/reference/collation/ }
TgoMongoCollationCaseFirst = (ccfUpper, ccfLower, ccfOff);
TgoMongoCollationCaseFirstHelper = record helper for TgoMongoCollationCaseFirst
public
function ToString: string;
end;
TgoMongoCollationAlternate = (caNonIgnorable, caShifted);
TgoMongoCollationAlternateHelper = record helper for TgoMongoCollationAlternate
public
function ToString: string;
end;
TgoMongoCollationMaxVariable = (cmvPunct, cmvSpace);
TgoMongoCollationMaxVariableHelper = record helper for TgoMongoCollationMaxVariable
public
function ToString: string;
end;
TgoMongoCollation = record
public
Locale: string;
CaseLevel: Boolean;
CaseFirst: TgoMongoCollationCaseFirst;
Strength: Integer;
NumericOrdering: Boolean;
Alternate: TgoMongoCollationAlternate;
MaxVariable: TgoMongoCollationMaxVariable;
Backwards: Boolean;
end;
{ MongoDb dbStats
https://docs.mongodb.com/manual/reference/command/dbStats/ }
TgoMongoStatistics = record
public
Database: string;
Collections: Integer;
Views: Integer;
Objects: Int64;
AvgObjSize: Double;
DataSize: Double;
StorageSize: Double;
NumExtents: Integer;
Indexes: Integer;
IndexSize: Double;
ScaleFactor: Double;
FsUsedSize: Double;
FsTotalSize: Double;
end;
{ MongoDb instances
https://docs.mongodb.com/manual/reference/command/isMaster/ }
TgoMongoInstance = record
public
Host: string;
Port: Word;
public
constructor Create(AInstance: string); overload;
constructor Create(AHost: string; APort: Word); overload;
end;
TgoMongoInstances = TArray<TgoMongoInstance>;
TgoMongoInstanceInfo = record
public
Hosts: TgoMongoInstances;
Arbiters: TgoMongoInstances;
Primary: TgoMongoInstance;
Me: TgoMongoInstance;
SetName: string;
SetVersion: Integer;
IsMaster: Boolean;
IsSecondary: Boolean;
ArbiterOnly: Boolean;
LocalTime: TDateTime;
ConnectionId: Integer;
ReadOnly: Boolean;
end;
const
MongoDefBatchSize = 101;
{ MongoDB collation default settings
https://docs.mongodb.com/manual/reference/collation-locales-defaults/#collation-languages-locales }
DEFAULTTGOMONGOCOLLATION: TgoMongoCollation = (Locale: 'en'; CaseLevel: false; CaseFirst: TgoMongoCollationCaseFirst.ccfOff; Strength: 1;
NumericOrdering: false; Alternate: TgoMongoCollationAlternate.caNonIgnorable; MaxVariable: TgoMongoCollationMaxVariable.cmvSpace;
Backwards: false;);
type
{ MongoDB error codes }
TgoMongoErrorCode = (OK = 0, InternalError = 1, BadValue = 2, OBSOLETE_DuplicateKey = 3, NoSuchKey = 4, GraphContainsCycle = 5,
HostUnreachable = 6, HostNotFound = 7, UnknownError = 8, FailedToParse = 9, CannotMutateObject = 10, UserNotFound = 11,
UnsupportedFormat = 12, Unauthorized = 13, TypeMismatch = 14, Overflow = 15, InvalidLength = 16, ProtocolError = 17,
AuthenticationFailed = 18, CannotReuseObject = 19, IllegalOperation = 20, EmptyArrayOperation = 21, InvalidBSON = 22,
AlreadyInitialized = 23, LockTimeout = 24, RemoteValidationError = 25, NamespaceNotFound = 26, IndexNotFound = 27, PathNotViable = 28,
NonExistentPath = 29, InvalidPath = 30, RoleNotFound = 31, RolesNotRelated = 32, PrivilegeNotFound = 33, CannotBackfillArray = 34,
UserModificationFailed = 35, RemoteChangeDetected = 36, FileRenameFailed = 37, FileNotOpen = 38, FileStreamFailed = 39,
ConflictingUpdateOperators = 40, FileAlreadyOpen = 41, LogWriteFailed = 42, CursorNotFound = 43, UserDataInconsistent = 45,
LockBusy = 46, NoMatchingDocument = 47, NamespaceExists = 48, InvalidRoleModification = 49, ExceededTimeLimit = 50,
ManualInterventionRequired = 51, DollarPrefixedFieldName = 52, InvalidIdField = 53, NotSingleValueField = 54, InvalidDBRef = 55,
EmptyFieldName = 56, DottedFieldName = 57, RoleModificationFailed = 58, CommandNotFound = 59, OBSOLETE_DatabaseNotFound = 60,
ShardKeyNotFound = 61, OplogOperationUnsupported = 62, StaleShardVersion = 63, WriteConcernFailed = 64, MultipleErrorsOccurred = 65,
ImmutableField = 66, CannotCreateIndex = 67, IndexAlreadyExists = 68, AuthSchemaIncompatible = 69, ShardNotFound = 70,
ReplicaSetNotFound = 71, InvalidOptions = 72, InvalidNamespace = 73, NodeNotFound = 74, WriteConcernLegacyOK = 75,
NoReplicationEnabled = 76, OperationIncomplete = 77, CommandResultSchemaViolation = 78, UnknownReplWriteConcern = 79,
RoleDataInconsistent = 80, NoMatchParseContext = 81, NoProgressMade = 82, RemoteResultsUnavailable = 83, DuplicateKeyValue = 84,
IndexOptionsConflict = 85, IndexKeySpecsConflict = 86, CannotSplit = 87, SplitFailed_OBSOLETE = 88, NetworkTimeout = 89,
CallbackCanceled = 90, ShutdownInProgress = 91, SecondaryAheadOfPrimary = 92, InvalidReplicaSetConfig = 93, NotYetInitialized = 94,
NotSecondary = 95, OperationFailed = 96, NoProjectionFound = 97, DBPathInUse = 98, CannotSatisfyWriteConcern = 100,
OutdatedClient = 101, IncompatibleAuditMetadata = 102, NewReplicaSetConfigurationIncompatible = 103, NodeNotElectable = 104,
IncompatibleShardingMetadata = 105, DistributedClockSkewed = 106, LockFailed = 107, InconsistentReplicaSetNames = 108,
ConfigurationInProgress = 109, CannotInitializeNodeWithData = 110, NotExactValueField = 111, WriteConflict = 112,
InitialSyncFailure = 113, InitialSyncOplogSourceMissing = 114, CommandNotSupported = 115, DocTooLargeForCapped = 116,
ConflictingOperationInProgress = 117, NamespaceNotSharded = 118, InvalidSyncSource = 119, OplogStartMissing = 120,
DocumentValidationFailure = 121, OBSOLETE_ReadAfterOptimeTimeout = 122, NotAReplicaSet = 123, IncompatibleElectionProtocol = 124,
CommandFailed = 125, RPCProtocolNegotiationFailed = 126, UnrecoverableRollbackError = 127, LockNotFound = 128,
LockStateChangeFailed = 129, SymbolNotFound = 130, RLPInitializationFailed = 131, OBSOLETE_ConfigServersInconsistent = 132,
FailedToSatisfyReadPreference = 133, ReadConcernMajorityNotAvailableYet = 134, StaleTerm = 135, CappedPositionLost = 136,
IncompatibleShardingConfigVersion = 137, RemoteOplogStale = 138, JSInterpreterFailure = 139, InvalidSSLConfiguration = 140,
SSLHandshakeFailed = 141, JSUncatchableError = 142, CursorInUse = 143, IncompatibleCatalogManager = 144, PooledConnectionsDropped = 145,
ExceededMemoryLimit = 146, ZLibError = 147, ReadConcernMajorityNotEnabled = 148, NoConfigMaster = 149, StaleEpoch = 150,
OperationCannotBeBatched = 151, OplogOutOfOrder = 152, ChunkTooBig = 153, InconsistentShardIdentity = 154,
CannotApplyOplogWhilePrimary = 155, NeedsDocumentMove = 156, CanRepairToDowngrade = 157, MustUpgrade = 158, DurationOverflow = 159,
MaxStalenessOutOfRange = 160, IncompatibleCollationVersion = 161, CollectionIsEmpty = 162, ZoneStillInUse = 163,
InitialSyncActive = 164, ViewDepthLimitExceeded = 165, CommandNotSupportedOnView = 166, OptionNotSupportedOnView = 167,
InvalidPipelineOperator = 168, CommandOnShardedViewNotSupportedOnMongod = 169, TooManyMatchingDocuments = 170,
CannotIndexParallelArrays = 171, TransportSessionClosed = 172, TransportSessionNotFound = 173, TransportSessionUnknown = 174,
QueryPlanKilled = 175, FileOpenFailed = 176, ZoneNotFound = 177, RangeOverlapConflict = 178, WindowsPdhError = 179,
BadPerfCounterPath = 180, AmbiguousIndexKeyPattern = 181, InvalidViewDefinition = 182, ClientMetadataMissingField = 183,
ClientMetadataAppNameTooLarge = 184, ClientMetadataDocumentTooLarge = 185, ClientMetadataCannotBeMutated = 186,
LinearizableReadConcernError = 187, IncompatibleServerVersion = 188, PrimarySteppedDown = 189, MasterSlaveConnectionFailure = 190,
OBSOLETE_BalancerLostDistributedLock = 191, FailPointEnabled = 192, NoShardingEnabled = 193, BalancerInterrupted = 194,
ViewPipelineMaxSizeExceeded = 195, InvalidIndexSpecificationOption = 197, OBSOLETE_ReceivedOpReplyMessage = 198,
ReplicaSetMonitorRemoved = 199, ChunkRangeCleanupPending = 200, CannotBuildIndexKeys = 201, NetworkInterfaceExceededTimeLimit = 202,
ShardingStateNotInitialized = 203, TimeProofMismatch = 204, ClusterTimeFailsRateLimiter = 205, NoSuchSession = 206, InvalidUUID = 207,
TooManyLocks = 208, StaleClusterTime = 209, CannotVerifyAndSignLogicalTime = 210, KeyNotFound = 211,
IncompatibleRollbackAlgorithm = 212, DuplicateSession = 213, AuthenticationRestrictionUnmet = 214, DatabaseDropPending = 215,
ElectionInProgress = 216, IncompleteTransactionHistory = 217, UpdateOperationFailed = 218, FTDCPathNotSet = 219,
FTDCPathAlreadySet = 220, IndexModified = 221, CloseChangeStream = 222, IllegalOpMsgFlag = 223, JSONSchemaNotAllowed = 224,
TransactionTooOld = 225,
SocketException = 9001, OBSOLETE_RecvStaleConfig = 9996, NotMaster = 10107, CannotGrowDocumentInCappedNamespace = 10003,
DuplicateKey = 11000, InterruptedAtShutdown = 11600, Interrupted = 11601, InterruptedDueToReplStateChange = 11602,
OutOfDiskSpace = 14031, KeyTooLong = 17280, BackgroundOperationInProgressForDatabase = 12586,
BackgroundOperationInProgressForNamespace = 12587, NotMasterOrSecondary = 13436, NotMasterNoSlaveOk = 13435, ShardKeyTooBig = 13334,
StaleConfig = 13388, DatabaseDifferCase = 13297, OBSOLETE_PrepareConfigsFailed = 13104);
type
{ Is raised when there is an error writing to the database }
EgoMongoDBWriteError = class(EgoMongoDBError)
{$REGION 'Internal Declarations'}
private
FErrorCode: TgoMongoErrorCode;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const AErrorCode: TgoMongoErrorCode; const AErrorMsg: string);
{ The MongoDB error code }
property ErrorCode: TgoMongoErrorCode read FErrorCode;
end;
type
{ Forward declarations }
IgoMongoDatabase = interface;
IgoMongoCollection = interface;
igoMongoCursor = interface;
tWriteCmd = Reference to procedure(Writer: IgoBsonWriter);
{ The client interface to MongoDB.
This is the entry point for the MongoDB API.
This interface is implemented in to TgoMongoClient class. }
IgoMongoClient = interface
['{66FF5346-48F6-44E1-A46F-D8B958F06EA0}']
{ Returns an array with the names of all databases available to the client. }
function ListDatabaseNames: TArray<string>;
{ Returns an array of documents describing all databases available to the
client (one document per database). The structure of each document is
described here:
https://docs.mongodb.com/manual/reference/command/listDatabases/ }
function ListDatabases: TArray<TgoBsonDocument>;
{ Returns a document that describes the role of the mongod instance. If the optional
field saslSupportedMechs is specified, the command also returns an array of
SASL mechanisms used to create the specified users credentials.
If the instance is a member of a replica set, then isMaster returns a subset
of the replica set configuration and status including whether or not the instance
is the primary of the replica set.
described here:
https://docs.mongodb.com/manual/reference/command/isMaster/
}
function GetInstanceInfo(const ASaslSupportedMechs: string = ''; const AComment: string = ''): TgoMongoInstanceInfo;
function IsMaster: Boolean;
{ Issue an admin command that is supposed to return ONE document }
function AdminCommand(CommandToIssue: tWriteCmd): igoMongoCursor;
{ Issue a logRotate command.
https://www.mongodb.com/docs/manual/reference/command/logRotate/ }
function LogRotate: Boolean;
{ Query build info of the current Mongod
https://www.mongodb.com/docs/manual/reference/command/buildInfo/ }
function BuildInfo: TgoBsonDocument;
{ Query system/platform info of the current Mongod server
https://www.mongodb.com/docs/manual/reference/command/hostInfo/ }
function HostInfo: TgoBsonDocument;
{ Query build-level feature settings
https://www.mongodb.com/docs/manual/reference/command/features/ }
function Features: TgoBsonDocument;
{ Query to find out MaxWireVersion }
function Hello: TgoBsonDocument;
{ Drops the database with the specified name.
Parameters:
AName: The name of the database to drop. }
procedure DropDatabase(const AName: string);
{ Gets a database.
Parameters:
AName: the name of the database.
Returns:
An implementation of the database.
NOTE: If a database with the given name does not exist, then it will be
automatically created as soon as you start writing to it.
NOTE: This method is light weight and doesn't actually open the database
yet. The database is only opened once you start reading, writing or
querying it. }
function GetDatabase(const AName: string): IgoMongoDatabase;
function GetGlobalReadPreference: tgoMongoReadPreference;
procedure SetGlobalReadPreference(const Value: tgoMongoReadPreference);
{ GlobalReadPreference sets the global ReadPreference for all objects (database, collection etc)
that do not have an individual specific ReadPreference. }
property GlobalReadPreference: tgoMongoReadPreference read GetGlobalReadPreference write SetGlobalReadPreference;
end;
{ Represents a database in MongoDB.
Instances of this interface are aquired by calling
IgoMongoClient.GetDatabase. }
IgoMongoDatabase = interface
['{5164D7B1-74F5-45F1-AE22-AB5FFC834590}']
{$REGION 'Internal Declarations'}
function _GetClient: IgoMongoClient;
function _GetName: string;
{$ENDREGION 'Internal Declarations'}
{ Returns an array with the names of all collections in the database. }
function ListCollectionNames: TArray<string>;
{ Returns an array of documents describing all collections in the database
(one document per collection). The structure of each document is
described here:
https://docs.mongodb.com/manual/reference/method/db.getCollectionInfos/ }
function ListCollections: TArray<TgoBsonDocument>;
{ Drops the collection with the specified name.
Parameters:
AName: The name of the collection to drop. }
procedure DropCollection(const AName: string);
{ Gets a collection.
Parameters:
AName: the name of the collection.
Returns:
An implementation of the collection.
NOTE: If a collection with the given name does not exist in this database,
then it will be automatically created as soon as you start writing to it.
NOTE: This method is light weight and doesn't actually open the collection
yet. The collection is only opened once you start reading, writing or
querying it. }
function GetCollection(const AName: string): IgoMongoCollection;
{ Creates a collection.
All parameters are described here:
https://docs.mongodb.com/manual/reference/command/create/ }
function CreateCollection(const AName: string; const ACapped: Boolean; const AMaxSize: Int64; const AMaxDocuments: Int64;
const AValidationLevel: TgoMongoValidationLevel; const AValidationAction: TgoMongoValidationAction; const AValidator: TgoBsonDocument;
const ACollation: TgoMongoCollation): Boolean;
{ Rename a collection.
All parameters are described here:
https://docs.mongodb.com/manual/reference/command/renameCollection/ }
function RenameCollection(const AFromNamespace, AToNamespace: string; const ADropTarget: Boolean = false): Boolean;
{ Get database statistics.
All parameters are described here:
https://docs.mongodb.com/manual/reference/command/dbStats/ }
function GetDbStats(const AScale: Integer): TgoMongoStatistics;
{ Issue a command against the MongoDB instance that returns a cursor. }
function AdminCommand(CommandToIssue: tWriteCmd): igoMongoCursor;
{ Issue a command against the database that returns a cursor.
Similar to AdminCommand. }
function Command(CommandToIssue: tWriteCmd): igoMongoCursor;
function GetReadPreference: tgoMongoReadPreference;
procedure SetReadPreference(const Value: tgoMongoReadPreference);
{ The client used for this database. }
property Client: IgoMongoClient read _GetClient;
{ The name of the database. }
property name: string read _GetName;
{ setting ReadPreference on the database will override the global readpreference }
property ReadPreference: tgoMongoReadPreference read GetReadPreference write SetReadPreference;
end;
{ Represents a cursor to the documents returned from one of the
IgoMongoCollection.Find methods. }
igoMongoCursor = interface
['{18813F27-1B41-453C-86FE-E98AFEB3D905}']
{ Allows for..in enumeration over all documents in the cursor. }
function GetEnumerator: TEnumerator<TgoBsonDocument>;
{ Converts all documents in the cursor to an array.
Note that this can be time consuming and result in a large array,
depending on the number of documents in the cursor.
Returns:
An array of documents in the cursor. }
function ToArray: TArray<TgoBsonDocument>;
end;
{ Fluent Interface for igoMongoCollection.find(),
see https://www.mongodb.com/docs/manual/reference/command/find/
the class factory is function "findOptions" }
igoMongoFindOptions = interface
['{5E3602BD-90EE-493A-9A91-50E7209707E4}']
function getfilter: tgoMongoFilter;
function getbatchSize: Integer;
{ Filter: Optional. The query predicate. If unspecified, then all documents
in the collection will match the predicate. }
function filter(const AValue: tgoMongoFilter): igoMongoFindOptions; overload;
function filter(const aJsonDoc: string): igoMongoFindOptions; overload;
{ Sort:Optional. The sort specification for the ordering of the results. }
function sort(const AValue: TgoMongoSort): igoMongoFindOptions; overload;
function sort(const aJsonDoc: string): igoMongoFindOptions; overload;
{ Projection: Optional. The projection specification to determine which fields to include
in the returned documents. See Projection and Projection Operators. }
function projection(const AValue: TgoMongoProjection): igoMongoFindOptions; overload;
function projection(const aJsonDoc: string): igoMongoFindOptions; overload;
{ hint:Optional. Index specification. Specify either the index name as a string or
the index key pattern. If specified, then the query system will only consider
plans using the hinted index. }
function hint(AValue: string): igoMongoFindOptions;
{ Skip: Optional. Number of documents to skip. Defaults to 0. }
function skip(AValue: Integer): igoMongoFindOptions;
{ limit: Optional. The maximum number of documents to return.
If unspecified, then defaults to no limit.
A limit of 0 is equivalent to setting no limit. }
function limit(AValue: Integer): igoMongoFindOptions;
{ batchSize: Optional. The number of documents to return in the first batch.
Defaults to 101. A batchSize of 0 means that the cursor will be established, but
no documents will be returned in the first batch. Unlike the previous wire protocol
version, a batchSize of 1 for the find command does not close the cursor. }
function batchSize(AValue: Integer): igoMongoFindOptions;
{ singleBatch: Optional. Determines whether to close the cursor
after the first batch. Defaults to false. }
function singleBatch(AValue: Boolean): igoMongoFindOptions;
function comment(const AValue: string): igoMongoFindOptions;
{ maxTimeMS: Optional. The cumulative time limit in milliseconds for processing
operations on the cursor. MongoDB aborts the operation at the earliest following
interrupt point. }
function maxTimeMS(AValue: Integer): igoMongoFindOptions;
{ readConcern: See https://www.mongodb.com/docs/manual/reference/glossary/#std-term-read-concern }
function readConcern(const AValue: TgoBsonDocument): igoMongoFindOptions; overload;
function readConcern(const aJsonDoc: string): igoMongoFindOptions; overload;
{ returnKey: Optional. If true, returns only the index keys in the resulting documents.
Default value is false. If returnKey is true and the find command does not use an
index, the returned documents will be empty. }
function returnKey(Value: Boolean): igoMongoFindOptions;
{ showRecordID: Optional. Determines whether to return the record identifier for each document.
If true, adds a field $recordId to the returned documents. }
function showRecordId(Value: Boolean): igoMongoFindOptions;
{ noCursorTimeout: Optional. Prevents the server from timing out idle
cursors after an inactivity period (10 minutes). }
function noCursorTimeout(Value: Boolean): igoMongoFindOptions;
function allowPartialResults(Value: Boolean): igoMongoFindOptions;
{ min:optional. The inclusive lower bound for a specific index. See cursor.min()
for details. Starting in MongoDB 4.2, to use the min field, the command must also use
hint unless the specified filter is an equality condition on the _id field { _id: <value> }
function min(const AValue: TgoBsonDocument): igoMongoFindOptions; overload;
function min(const aJsonDoc: string): igoMongoFindOptions; overload;
{ max: Optional. The exclusive upper bound for a specific index. See
cursor.max() for details. Starting in MongoDB 4.2, to use the max field,
the command must also use hint unless the specified filter is an equality
condition on the _id field { _id: <value> }
function max(const AValue: TgoBsonDocument): igoMongoFindOptions; overload;
function max(const aJsonDoc: string): igoMongoFindOptions; overload;
{ collation: Optional. Specifies the collation to use for the operation. }
function collation(const AValue: TgoBsonDocument): igoMongoFindOptions; overload;
function collation(const aJsonDoc: string): igoMongoFindOptions; overload;
{ allowDiskUse:Optional. Use this option to override allowDiskUseByDefault for a specific query. }
function allowDiskUse(Value: Boolean): igoMongoFindOptions;
procedure WriteOptions(const Writer: IgoBsonWriter);
function asBsonDocument: TgoBsonDocument;
function asJson: string;
procedure fromBson(aBson: TgoBsonDocument);
procedure fromJson(const aJson: string);
end;
{ Represents a collection in a MongoDB database.
Instances of this interface are aquired by calling
IgoMongoDatabase.GetCollection. }
IgoMongoCollection = interface
['{9822579B-1682-4FAC-81CF-A4B239777812}']
{$REGION 'Internal Declarations'}
function _GetDatabase: IgoMongoDatabase;
function _GetName: string;
{$ENDREGION 'Internal Declarations'}
{ Inserts a single document.
Parameters:
ADocument: The document to insert.
Returns:
True if document has been successfully inserted. False if not. }
function InsertOne(const ADocument: TgoBsonDocument): Boolean;
{ Inserts many documents.
Parameters:
ADocuments: The documents to insert.
AOrdered: Optional. If True, perform an ordered insert of the documents
in the array, and if an error occurs with one of documents, MongoDB
will return without processing the remaining documents in the array.
If False, perform an unordered insert, and if an error occurs with one
of documents, continue processing the remaining documents in the
array.
Defaults to true.
Returns:
The number of inserted documents. }
function InsertMany(const ADocuments: array of TgoBsonDocument; const AOrdered: Boolean = True): Integer; overload;
function InsertMany(const ADocuments: TArray<TgoBsonDocument>; const AOrdered: Boolean = True): Integer; overload;
function InsertMany(const ADocuments: TEnumerable<TgoBsonDocument>; const AOrdered: Boolean = True): Integer; overload;
{ Deletes a single document.
Parameters:
AFilter: filter containing query operators to search for the document
to delete.
Returns:
True if a document matching the filter has been found and it has
been successfully deleted. }
function DeleteOne(const AFilter: tgoMongoFilter): Boolean;
{ Deletes all documents that match a filter.
Parameters:
AFilter: filter containing query operators to search for the documents
to delete.
AOrdered: Optional. If True, then when a delete statement fails, return
without performing the remaining delete statements. If False, then
when a delete statement fails, continue with the remaining delete
statements, if any.
Defaults to true.
Returns:
The number of documents deleted. }
function DeleteMany(const AFilter: tgoMongoFilter; const AOrdered: Boolean = True): Integer;
{ Updates a single document.
Parameters:
AFilter: filter containing query operators to search for the document
to update.
AUpdate: the update definition that specifies how the document should
be updated.
AUpsert: (optional) upsert flag. If True, perform an insert if no
documents match the query. Defaults to False.
Returns:
True if a document matching the filter has been found and it has
been successfully updated. }
function UpdateOne(const AFilter: tgoMongoFilter; const AUpdate: TgoMongoUpdate; const AUpsert: Boolean = false): Boolean;
{ Updates all documents that match a filter.
Parameters:
AFilter: filter containing query operators to search for the documents
to update.
AUpdate: the update definition that specifies how the documents should
be updated.
AUpsert: (optional) upsert flag. If True, perform an insert if no
documents match the query. Defaults to False.
AOrdered: Optional. If True, then when an update statement fails, return
without performing the remaining update statements. If False, then
when an update statement fails, continue with the remaining update
statements, if any.
Defaults to true.
Returns:
The number of documents that match the filter. The number of documents
that is actually updated may be less than this in case an update did
not result in the change of one or more documents. }
function UpdateMany(const AFilter: tgoMongoFilter; const AUpdate: TgoMongoUpdate; const AUpsert: Boolean = false;
const AOrdered: Boolean = True): Integer;
{ Finds the documents matching the filter.
Parameters:
AOptions: a fluent interface that will let you specify all options such
as the filter, projection, sorting.
Legacy parameters:
AFilter: (optional) filter containing query operators to search for
documents that match the filter. If not specified, then all documents
in the collection are returned.
AProjection: (optional) projection that specifies the fields to return
in the documents that match the query filter. If not specified, then
all fields are returned.
ASort: (optional) sort modifier, used to sort the results. Note: an
exception is raised when the result set is very large (32MB or larger)
and cannot be sorted.
Returns:
An enumerable of documents that match the filter. The enumerable will
be empty if there are no documents that match the filter.
Enumerating over the result may trigger additional calls to the MongoDB
server. }
function EmptyCursor: igoMongoCursor;
function Find(AOptions: igoMongoFindOptions): igoMongoCursor; overload;
function Find: igoMongoCursor; overload;
function Find(const AFilter: tgoMongoFilter): igoMongoCursor; overload;
function Find(const AProjection: TgoMongoProjection): igoMongoCursor; overload;
function Find(const AFilter: tgoMongoFilter; const AProjection: TgoMongoProjection): igoMongoCursor; overload;
function Find(const AFilter: tgoMongoFilter; const ASort: TgoMongoSort): igoMongoCursor; overload;
function Find(const AFilter: tgoMongoFilter; const AProjection: TgoMongoProjection; const ASort: TgoMongoSort; aSkip: Integer = 0)
: igoMongoCursor; overload;
{ Finds the first document matching the filter.
Parameters:
AOptions: a fluent interface that will let you specify all options such
as the filter, projection, sorting.
Legacy Parameters:
AFilter: filter containing query operators to search for the document
that matches the filter.
ASort: (optional) use this to find the maximum or minimum value of a field.
An empty filter (tgomongofilter.Empty) with ASort=tgomongosort.Descending('price')
will return the document having the highest 'price'.
For best performance, use indexes in the collection.
AProjection: (optional) projection that specifies the fields to return
in the document that matches the query filter. If not specified, then
all fields are returned.
Returns:
The first document that matches the filter. If no documents match the
filter, then a null-documents is returned (call its IsNil method to
check for this). }
function FindOne(AOptions: igoMongoFindOptions): TgoBsonDocument; overload;
function FindOne(const AFilter: tgoMongoFilter; const AProjection: TgoMongoProjection): TgoBsonDocument; overload;
function FindOne(const AFilter: tgoMongoFilter): TgoBsonDocument; overload;
function FindOne(const AFilter: tgoMongoFilter; const ASort: TgoMongoSort): TgoBsonDocument; overload;
function FindOne(const AFilter: tgoMongoFilter; const AProjection: TgoMongoProjection; const ASort: TgoMongoSort)
: TgoBsonDocument; overload;
{ Counts the number of documents matching the filter.
Parameters:
AFilter: (optional) filter containing query operators to search for
documents that match the filter. If not specified, then the total
number of documents in the collection is returned.
Returns:
The number of documents that match the filter. }
function Count: Integer; overload;
function Count(const AFilter: tgoMongoFilter): Integer; overload;
{ Creates an index in the current collection.
Parameters:
AName: Name of the index.
AKeyFields: List of fields to build the index.
AUnique: Defines a unique index.
Returns:
Created or not. }
function CreateIndex(const AName: string; const AKeyFields: array of string; const AUnique: Boolean = false): Boolean;
{ Creates an text index in the current collection.
Parameters:
AName: Name of the index.
AFields: List of fields to build the index.
ALanguageOverwriteField: Defines a field that contains the language to
use for a specific document.
ADefaultLanguage: Defines the default language for internal indexing.
See https://docs.mongodb.com/manual/reference/text-search-languages/#text-search-languages
for language definitions.
Returns:
Created or not. }
function CreateTextIndex(const AName: string; const AFields: array of string; const ALanguageOverwriteField: string = '';
const ADefaultLanguage: string = 'en'): Boolean;
{ Drops an index in the current collection.
Parameters:
AName: Name of the index.
Returns:
Dropped or not. }
function DropIndex(const AName: string): Boolean; overload;
{ List all index names in the current collection.
Returns:
TArray<String> of index names. }
function ListIndexNames: TArray<string>; overload;
function ListIndexes: TArray<TgoBsonDocument>; overload;
{ Return statistics about the collection, see
https://www.mongodb.com/docs/manual/reference/command/collStats }
function Stats: TgoBsonDocument;
function GetReadPreference: tgoMongoReadPreference;
procedure SetReadPreference(const Value: tgoMongoReadPreference);
{ The database that contains this collection. }
property Database: IgoMongoDatabase read _GetDatabase;
{ The name of the collection. }
property name: string read _GetName;
{ setting ReadPreference on the collection will override the global readpreference }
property ReadPreference: tgoMongoReadPreference read GetReadPreference write SetReadPreference;
end;
type
{ Can be passed to the constructor of TgoMongoClient to customize the
client settings. }
TgoMongoClientSettings = record
public
{ Timeout waiting for connection, in milliseconds.
Defaults to 5000 (5 seconds) }
ConnectionTimeout: Integer;
{ Timeout waiting for partial or complete reply events, in milliseconds.
Defaults to 5000 (5 seconds) }
ReplyTimeout: Integer;
{ Default query flags }
QueryFlags: TgoMongoQueryFlags;
{ Tls enabled }
Secure: Boolean;
{ X.509 Certificate in PEM format, if any }
Certificate: TBytes;
{ X.509 Private key in PEM format, if any }
PrivateKey: TBytes;
{ Password for private key, optional }
PrivateKeyPassword: string;
{ Authentication mechanism }
AuthMechanism: TgoMongoAuthMechanism;
{ Authentication database }
AuthDatabase: string;
{ Authentication username }
Username: string;
{ Authentication password }
Password: string;
ApplicationName: string;
UseSnappyCompression: Boolean;
UseZlibCompression: Boolean;
GlobalReadPreference: tgoMongoReadPreference;
public
{ Creates a settings record with the default settings }
class function Create: TgoMongoClientSettings; static;
end;
type
{ Implements IgoMongoClient.
This is the main entry point to the MongoDB API. }
TgoMongoClient = class(TInterfacedObject, IgoMongoClient)
public const
{ Default host address of the MongoDB server. }
DEFAULT_HOST = 'localhost';
{ Default connection port. }
DEFAULT_PORT = 27017;
{$REGION 'Internal Declarations'}
private
FProtocol: TgoMongoProtocol;
function GetGlobalReadPreference: tgoMongoReadPreference;
procedure SetGlobalReadPreference(const Value: tgoMongoReadPreference);
protected
{ IgoMongoClient }
function ListDatabaseNames: TArray<string>;
function ListDatabases: TArray<TgoBsonDocument>;
procedure DropDatabase(const AName: string);
function GetDatabase(const AName: string): IgoMongoDatabase;
function GetInstanceInfo(const ASaslSupportedMechs: string = ''; const AComment: string = ''): TgoMongoInstanceInfo;
function IsMaster: Boolean;
function AdminCommand(CommandToIssue: tWriteCmd): igoMongoCursor;
function LogRotate: Boolean;
function BuildInfo: TgoBsonDocument;
function HostInfo: TgoBsonDocument;
function Features: TgoBsonDocument;
function Hello: TgoBsonDocument;
protected
property Protocol: TgoMongoProtocol read FProtocol;
{$ENDREGION 'Internal Declarations'}
public
{ Creates a client interface to MongoDB.
Parameters:
AHost: (optional) host address of the MongoDB server to connect to.
Defaults to 'localhost'.
APort: (optional) connection port. Defaults to 27017.
ASettings: (optional) client settings.
NOTE: The constructor is light weight and does NOT connect to the server
until the first read, write or query operation. }
constructor Create(const AHost: string = DEFAULT_HOST; const APort: Integer = DEFAULT_PORT); overload;
constructor Create(const AHost: string; const APort: Integer; const ASettings: TgoMongoClientSettings); overload;
constructor Create(const ASettings: TgoMongoClientSettings); overload;
destructor Destroy; override;
{ GlobalReadPreference sets the global ReadPreference for all objects (database, collection etc)
that do not have an individual specific ReadPreference. }
property GlobalReadPreference: tgoMongoReadPreference read GetGlobalReadPreference write SetGlobalReadPreference;
end;
resourcestring
RS_MONGODB_CONNECTION_ERROR = 'Error connecting to the MongoDB database';
RS_MONGODB_GENERIC_ERROR = 'Unspecified error while performing MongoDB operation';
function FindOptions: igoMongoFindOptions; // class factory
implementation
uses
System.Math;
const
NoCursorID = 0;
{$POINTERMATH ON}
{ If no reply was received within timeout seconds, throw an exception }
procedure HandleTimeout(const AReply: IgoMongoReply); inline;
begin
if (AReply = nil) then
raise EgoMongoDBConnectionError.Create(RS_MONGODB_CONNECTION_ERROR);
end;
{ If timeout, or error message, throw exception }
function HandleCommandReply(const AReply: IgoMongoReply; const AErrorToIgnore: TgoMongoErrorCode = TgoMongoErrorCode.OK): Integer;
var
Doc, ErrorDoc: TgoBsonDocument;
Value: TgoBsonValue;
Values: TgoBsonArray;
OK: Boolean;
ErrorCode: TgoMongoErrorCode;
ErrorMsg: string;
begin
HandleTimeout(AReply); { Exception if timeout }
Doc := AReply.FirstDoc;
if Doc.IsNil then
{ Everything OK }
Exit(0);
{ Return number of documents affected }
Result := Doc['n'];
OK := Doc['ok'];
if (not OK) then
begin
{ Check for top-level error }
Word(ErrorCode) := Doc['code'];
{ Check for expected error }
if (AErrorToIgnore <> TgoMongoErrorCode.OK) and (ErrorCode = AErrorToIgnore) then
Exit;
if (ErrorCode <> TgoMongoErrorCode.OK) then
begin
ErrorMsg := Doc['errmsg'];
raise EgoMongoDBWriteError.Create(ErrorCode, ErrorMsg);
end;
{ If there is no top-level error, then check for Write Error(s).
Raise exception for first write error found. }
if (Doc.TryGetValue('writeErrors', Value)) then
begin
Values := Value.AsBsonArray;
if (Values.Count > 0) then
begin
ErrorDoc := Values.Items[0].asBsonDocument;
Word(ErrorCode) := ErrorDoc['code'];
ErrorMsg := ErrorDoc['errmsg'];
raise EgoMongoDBWriteError.Create(ErrorCode, ErrorMsg);
end;
end;
{ If there are no write errors either, then check for write concern error. }
if (Doc.TryGetValue('writeConcernError', Value)) then
begin
ErrorDoc := Value.asBsonDocument;
Word(ErrorCode) := ErrorDoc['code'];
ErrorMsg := ErrorDoc['errmsg'];
raise EgoMongoDBWriteError.Create(ErrorCode, ErrorMsg);
end;
{ Could not detect any errors in reply. Raise generic error. }
raise EgoMongoDBError.Create(RS_MONGODB_GENERIC_ERROR);
end;
end;
type
{ Implements IgoMongoDatabase }
TgoMongoDatabase = class(TInterfacedObject, IgoMongoDatabase)
{$REGION 'Internal Declarations'}
private
FClient: IgoMongoClient;
FProtocol: TgoMongoProtocol; // Reference
FName: string;
FReadPreference: tgoMongoReadPreference;
function GetReadPreference: tgoMongoReadPreference;
procedure SetReadPreference(const Value: tgoMongoReadPreference);
procedure SpecifyDB(const AWriter: IgoBsonWriter);
procedure SpecifyReadPreference(const AWriter: IgoBsonWriter);
protected
{ IgoMongoDatabase }
function _GetClient: IgoMongoClient;
function _GetName: string;
function ListCollectionNames: TArray<string>;
function ListCollections: TArray<TgoBsonDocument>;
procedure DropCollection(const AName: string);
function GetCollection(const AName: string): IgoMongoCollection;
function CreateCollection(const AName: string; const ACapped: Boolean; const AMaxSize: Int64; const AMaxDocuments: Int64;
const AValidationLevel: TgoMongoValidationLevel; const AValidationAction: TgoMongoValidationAction; const AValidator: TgoBsonDocument;
const ACollation: TgoMongoCollation): Boolean;
function RenameCollection(const AFromNamespace, AToNamespace: string; const ADropTarget: Boolean = false): Boolean;
function GetDbStats(const AScale: Integer): TgoMongoStatistics;
function Command(CommandToIssue: tWriteCmd): igoMongoCursor;
function AdminCommand(CommandToIssue: tWriteCmd): igoMongoCursor;
protected
property Protocol: TgoMongoProtocol read FProtocol;
property name: string read FName;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const AClient: TgoMongoClient; const AName: string);
property ReadPreference: tgoMongoReadPreference read GetReadPreference write SetReadPreference;
end;
type
{ Implements IgoMongoCursor }
TgoMongoCursor = class(TInterfacedObject, igoMongoCursor)
{$REGION 'Internal Declarations'}
private type
TEnumerator = class(TEnumerator<TgoBsonDocument>)
private
FProtocol: TgoMongoProtocol; // Reference
FDatabaseName: string;
FCollectionName: string;
FPage: TArray<TBytes>;
FCursorId: Int64;
FIndex: Integer;
FReadPreference: tgoMongoReadPreference;
private
procedure GetMore;
procedure SpecifyDB(const Writer: IgoBsonWriter);
procedure SpecifyReadPreference(const AWriter: IgoBsonWriter);
protected
function DoGetCurrent: TgoBsonDocument; override;
function DoMoveNext: Boolean; override;
public
destructor Destroy; override;
constructor Create(const AProtocol: TgoMongoProtocol; AReadPreference: tgoMongoReadPreference;
const ADatabaseName, ACollectionName: string; const APage: TArray<TBytes>; const ACursorId: Int64);
end;
private
FProtocol: TgoMongoProtocol; // Reference
FDatabaseName: string;
FCollectionName: string;
FInitialPage: TArray<TBytes>;
FInitialCursorId: Int64;
FReadPreference: tgoMongoReadPreference;
public
{ IgoMongoCursor }
function GetEnumerator: TEnumerator<TgoBsonDocument>;
function ToArray: TArray<TgoBsonDocument>;
public
constructor Create(const AProtocol: TgoMongoProtocol; AReadPreference: tgoMongoReadPreference;
const ADatabaseName, ACollectionName: string; const AInitialPage: TArray<TBytes>; const AInitialCursorId: Int64); overload;
constructor Create(const AProtocol: TgoMongoProtocol; AReadPreference: tgoMongoReadPreference; const aNameSpace: string;
const AInitialPage: TArray<TBytes>; const AInitialCursorId: Int64); overload;
{$ENDREGION 'Internal Declarations'}
end;
procedure DoSpecifyReadPreference(AReadPreference: tgoMongoReadPreference; const AWriter: IgoBsonWriter);
begin
if AReadPreference <> tgoMongoReadPreference.Primary then
begin
AWriter.WriteStartDocument('$readPreference');
case AReadPreference of
tgoMongoReadPreference.Primary:
AWriter.WriteString('mode', 'primary');
tgoMongoReadPreference.primaryPreferred:
AWriter.WriteString('mode', 'primaryPreferred');
tgoMongoReadPreference.secondary:
AWriter.WriteString('mode', 'secondary');
tgoMongoReadPreference.secondaryPreferred:
AWriter.WriteString('mode', 'secondaryPreferred');
tgoMongoReadPreference.nearest:
AWriter.WriteString('mode', 'nearest');
end;
AWriter.WriteEndDocument;
end;
end;
function HasCursor(const ADoc: TgoBsonDocument; var Cursor: TgoBsonDocument; var CursorID: Int64; var Namespace: string): Boolean; inline;
var
temp: TgoBsonValue;
begin
Cursor.SetNil;
CursorID := 0;
Namespace := '';
Result := (ADoc.TryGetValue('cursor', temp));
if Result then
begin
Cursor := temp.asBsonDocument;
CursorID := Cursor['id']; // 0=cursor exhausted, else more data can be pulled
Namespace := Cursor.Get('ns', '').ToString(); // databasename.CollectionNameOrCommand
end;
end;
function CreateCursor(const ADoc: TgoBsonDocument; AProtocol: TgoMongoProtocol; AReadPreference: tgoMongoReadPreference): igoMongoCursor;
var