-
Notifications
You must be signed in to change notification settings - Fork 28
/
Grijjy.MongoDB.pas
2081 lines (1796 loc) · 65.8 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
{ 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;
{ 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;
{ 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;
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;
{ The client used for this database. }
property Client: IgoMongoClient read _GetClient;
{ The name of the database. }
property Name: String read _GetName;
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;
{ 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:
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 Find(const AFilter: TgoMongoFilter;
const AProjection: TgoMongoProjection): IgoMongoCursor; overload;
function Find(const AFilter: TgoMongoFilter): IgoMongoCursor; overload;
function Find(const AProjection: TgoMongoProjection): IgoMongoCursor; overload;
function Find: IgoMongoCursor; overload;
function Find(const AFilter: TgoMongoFilter;
const ASort: TgoMongoSort): IgoMongoCursor; overload;
function Find(const AFilter: TgoMongoFilter;
const AProjection: TgoMongoProjection;
const ASort: TgoMongoSort; const ANumberToSkip : Integer = 0): IgoMongoCursor; overload;
{ Finds the first document matching the filter.
Parameters:
AFilter: filter containing query operators to search for the document
that matches the filter.
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(const AFilter: TgoMongoFilter;
const AProjection: TgoMongoProjection): TgoBsonDocument; overload;
function FindOne(const AFilter: TgoMongoFilter): 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;
{ The database that contains this collection. }
property Database: IgoMongoDatabase read _GetDatabase;
{ The name of the collection. }
property Name: String read _GetName;
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;
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;
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;
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;
end;
resourcestring
RS_MONGODB_CONNECTION_ERROR = 'Error connecting to the MongoDB database';
RS_MONGODB_GENERIC_ERROR = 'Unspecified error while performing MongoDB operation';
implementation
uses
System.Math;
{$POINTERMATH ON}
const
{ Virtual collection that is used for query commands }
COLLECTION_COMMAND = '$cmd';
{ System collections }
COLLECTION_ADMIN = 'admin';
COLLECTION_ADMIN_COMMAND = COLLECTION_ADMIN + '.' + COLLECTION_COMMAND;
{ Maximum number of documents that can be written in bulk at once }
MAX_BULK_SIZE = 1000;
procedure HandleTimeout(const AReply: IgoMongoReply); inline;
begin
if (AReply = nil) then
raise EgoMongoDBConnectionError.Create(RS_MONGODB_CONNECTION_ERROR);
end;
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
if (AReply = nil) then
raise EgoMongoDBConnectionError.Create(RS_MONGODB_CONNECTION_ERROR);
if (AReply.Documents = nil) then
{ Everything OK }
Exit(0);
Doc := TgoBsonDocument.Load(AReply.Documents[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;
FFullCommandCollectionName: UTF8String;
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;
protected
property Protocol: TgoMongoProtocol read FProtocol;
property Name: String read FName;
property FullCommandCollectionName: UTF8String read FFullCommandCollectionName;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const AClient: TgoMongoClient; const AName: String);
end;
type
{ Implements IgoMongoCursor }
TgoMongoCursor = class(TInterfacedObject, IgoMongoCursor)
{$REGION 'Internal Declarations'}
private type
TEnumerator = class(TEnumerator<TgoBsonDocument>)
private
FProtocol: TgoMongoProtocol; // Reference
FFullCollectionName: UTF8String;
FPage: TArray<TBytes>;
FCursorId: Int64;
FIndex: Integer;
private
procedure GetMore;
protected
function DoGetCurrent: TgoBsonDocument; override;
function DoMoveNext: Boolean; override;
public
destructor Destroy;Override;
constructor Create(const AProtocol: TgoMongoProtocol;
const AFullCollectionName: UTF8String; const APage: TArray<TBytes>;
const ACursorId: Int64);
end;
private
FProtocol: TgoMongoProtocol; // Reference
FFullCollectionName: UTF8String;
FInitialPage: TArray<TBytes>;
FInitialCursorId: Int64;
public
{ IgoMongoCursor }
function GetEnumerator: TEnumerator<TgoBsonDocument>;
function ToArray: TArray<TgoBsonDocument>;
public
constructor Create(const AProtocol: TgoMongoProtocol;
const AFullCollectionName: UTF8String; const AInitialPage: TArray<TBytes>;
const AInitialCursorId: Int64);
{$ENDREGION 'Internal Declarations'}
end;
type
{ Implements IgoMongoCollection }
TgoMongoCollection = class(TInterfacedObject, IgoMongoCollection)
{$REGION 'Internal Declarations'}
private type
PgoBsonDocument = ^TgoBsonDocument;