go mod vendor

+ move k8s.io/apimachinery fork from go.work to go.mod
(and include it in vendor)
This commit is contained in:
2022-11-07 00:16:27 +02:00
parent d08bbf250a
commit e45bf4739b
1366 changed files with 469062 additions and 45 deletions

View File

@@ -0,0 +1,181 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/bson"
)
// AggregateOptions represents options that can be used to configure an Aggregate operation.
type AggregateOptions struct {
// If true, the operation can write to temporary files in the _tmp subdirectory of the database directory path on
// the server. The default value is false.
AllowDiskUse *bool
// The maximum number of documents to be included in each batch returned by the server.
BatchSize *int32
// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
// false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document
// validation.
BypassDocumentValidation *bool
// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the default collation of the collection will be used.
Collation *Collation
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
// is no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be used
// in its place to control the amount of time that a single operation can run before returning an error. MaxTime
// is ignored if Timeout is set on the client.
MaxTime *time.Duration
// The maximum amount of time that the server should wait for new documents to satisfy a tailable cursor query.
// This option is only valid for MongoDB versions >= 3.2 and is ignored for previous server versions.
MaxAwaitTime *time.Duration
// A string that will be included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default is nil, which means that no comment will be included in the logs.
Comment *string
// The index to use for the aggregation. This should either be the index name as a string or the index specification
// as a document. The hint does not apply to $lookup and $graphLookup aggregation stages. The driver will return an
// error if the hint parameter is a multi-key map. The default value is nil, which means that no hint will be sent.
Hint interface{}
// Specifies parameters for the aggregate expression. This option is only valid for MongoDB versions >= 5.0. Older
// servers will report an error for using this option. This must be a document mapping parameter names to values.
// Values must be constant or closed expressions that do not reference document fields. Parameters can then be
// accessed as variables in an aggregate expression context (e.g. "$$var").
Let interface{}
// Custom options to be added to aggregate expression. Key-value pairs of the BSON map should correlate with desired
// option names and values. Values must be Marshalable. Custom options may conflict with non-custom options, and custom
// options bypass client-side validation. Prefer using non-custom options where possible.
Custom bson.M
}
// Aggregate creates a new AggregateOptions instance.
func Aggregate() *AggregateOptions {
return &AggregateOptions{}
}
// SetAllowDiskUse sets the value for the AllowDiskUse field.
func (ao *AggregateOptions) SetAllowDiskUse(b bool) *AggregateOptions {
ao.AllowDiskUse = &b
return ao
}
// SetBatchSize sets the value for the BatchSize field.
func (ao *AggregateOptions) SetBatchSize(i int32) *AggregateOptions {
ao.BatchSize = &i
return ao
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
func (ao *AggregateOptions) SetBypassDocumentValidation(b bool) *AggregateOptions {
ao.BypassDocumentValidation = &b
return ao
}
// SetCollation sets the value for the Collation field.
func (ao *AggregateOptions) SetCollation(c *Collation) *AggregateOptions {
ao.Collation = c
return ao
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can
// run before returning an error. MaxTime is ignored if Timeout is set on the client.
func (ao *AggregateOptions) SetMaxTime(d time.Duration) *AggregateOptions {
ao.MaxTime = &d
return ao
}
// SetMaxAwaitTime sets the value for the MaxAwaitTime field.
func (ao *AggregateOptions) SetMaxAwaitTime(d time.Duration) *AggregateOptions {
ao.MaxAwaitTime = &d
return ao
}
// SetComment sets the value for the Comment field.
func (ao *AggregateOptions) SetComment(s string) *AggregateOptions {
ao.Comment = &s
return ao
}
// SetHint sets the value for the Hint field.
func (ao *AggregateOptions) SetHint(h interface{}) *AggregateOptions {
ao.Hint = h
return ao
}
// SetLet sets the value for the Let field.
func (ao *AggregateOptions) SetLet(let interface{}) *AggregateOptions {
ao.Let = let
return ao
}
// SetCustom sets the value for the Custom field. Key-value pairs of the BSON map should correlate
// with desired option names and values. Values must be Marshalable. Custom options may conflict
// with non-custom options, and custom options bypass client-side validation. Prefer using non-custom
// options where possible.
func (ao *AggregateOptions) SetCustom(c bson.M) *AggregateOptions {
ao.Custom = c
return ao
}
// MergeAggregateOptions combines the given AggregateOptions instances into a single AggregateOptions in a last-one-wins
// fashion.
func MergeAggregateOptions(opts ...*AggregateOptions) *AggregateOptions {
aggOpts := Aggregate()
for _, ao := range opts {
if ao == nil {
continue
}
if ao.AllowDiskUse != nil {
aggOpts.AllowDiskUse = ao.AllowDiskUse
}
if ao.BatchSize != nil {
aggOpts.BatchSize = ao.BatchSize
}
if ao.BypassDocumentValidation != nil {
aggOpts.BypassDocumentValidation = ao.BypassDocumentValidation
}
if ao.Collation != nil {
aggOpts.Collation = ao.Collation
}
if ao.MaxTime != nil {
aggOpts.MaxTime = ao.MaxTime
}
if ao.MaxAwaitTime != nil {
aggOpts.MaxAwaitTime = ao.MaxAwaitTime
}
if ao.Comment != nil {
aggOpts.Comment = ao.Comment
}
if ao.Hint != nil {
aggOpts.Hint = ao.Hint
}
if ao.Let != nil {
aggOpts.Let = ao.Let
}
if ao.Custom != nil {
aggOpts.Custom = ao.Custom
}
}
return aggOpts
}

View File

@@ -0,0 +1,209 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"crypto/tls"
"net/http"
"go.mongodb.org/mongo-driver/internal"
)
// AutoEncryptionOptions represents options used to configure auto encryption/decryption behavior for a mongo.Client
// instance.
//
// Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic
// encryption is not supported for operations on a database or view, and operations that are not bypassed will result
// in error. Too bypass automatic encryption for all operations, set BypassAutoEncryption=true.
//
// Auto encryption requires the authenticated user to have the listCollections privilege action.
//
// If automatic encryption fails on an operation, use a MongoClient configured with bypassAutoEncryption=true and use
// ClientEncryption.encrypt() to manually encrypt values.
//
// Enabling Client Side Encryption reduces the maximum document and message size (using a maxBsonObjectSize of 2MiB and
// maxMessageSizeBytes of 6MB) and may have a negative performance impact.
type AutoEncryptionOptions struct {
KeyVaultClientOptions *ClientOptions
KeyVaultNamespace string
KmsProviders map[string]map[string]interface{}
SchemaMap map[string]interface{}
BypassAutoEncryption *bool
ExtraOptions map[string]interface{}
TLSConfig map[string]*tls.Config
HTTPClient *http.Client
EncryptedFieldsMap map[string]interface{}
BypassQueryAnalysis *bool
}
// AutoEncryption creates a new AutoEncryptionOptions configured with default values.
func AutoEncryption() *AutoEncryptionOptions {
return &AutoEncryptionOptions{
HTTPClient: internal.DefaultHTTPClient,
}
}
// SetKeyVaultClientOptions specifies options for the client used to communicate with the key vault collection.
//
// If this is set, it is used to create an internal mongo.Client.
// Otherwise, if the target mongo.Client being configured has an unlimited connection pool size (i.e. maxPoolSize=0),
// it is reused to interact with the key vault collection.
// Otherwise, if the target mongo.Client has a limited connection pool size, a separate internal mongo.Client is used
// (and created if necessary). The internal mongo.Client may be shared during automatic encryption (if
// BypassAutomaticEncryption is false). The internal mongo.Client is configured with the same options as the target
// mongo.Client except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
func (a *AutoEncryptionOptions) SetKeyVaultClientOptions(opts *ClientOptions) *AutoEncryptionOptions {
a.KeyVaultClientOptions = opts
return a
}
// SetKeyVaultNamespace specifies the namespace of the key vault collection. This is required.
func (a *AutoEncryptionOptions) SetKeyVaultNamespace(ns string) *AutoEncryptionOptions {
a.KeyVaultNamespace = ns
return a
}
// SetKmsProviders specifies options for KMS providers. This is required.
func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string]interface{}) *AutoEncryptionOptions {
a.KmsProviders = providers
return a
}
// SetSchemaMap specifies a map from namespace to local schema document. Schemas supplied in the schemaMap only apply
// to configuring automatic encryption for client side encryption. Other validation rules in the JSON schema will not
// be enforced by the driver and will result in an error.
//
// Supplying a schemaMap provides more security than relying on JSON Schemas obtained from the server. It protects
// against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted
// data that should be encrypted.
func (a *AutoEncryptionOptions) SetSchemaMap(schemaMap map[string]interface{}) *AutoEncryptionOptions {
a.SchemaMap = schemaMap
return a
}
// SetBypassAutoEncryption specifies whether or not auto encryption should be done.
//
// If this is unset or false and target mongo.Client being configured has an unlimited connection pool size
// (i.e. maxPoolSize=0), it is reused in the process of auto encryption.
// Otherwise, if the target mongo.Client has a limited connection pool size, a separate internal mongo.Client is used
// (and created if necessary). The internal mongo.Client may be shared for key vault operations (if KeyVaultClient is
// unset). The internal mongo.Client is configured with the same options as the target mongo.Client except minPoolSize
// is set to 0 and AutoEncryptionOptions is omitted.
func (a *AutoEncryptionOptions) SetBypassAutoEncryption(bypass bool) *AutoEncryptionOptions {
a.BypassAutoEncryption = &bypass
return a
}
// SetExtraOptions specifies a map of options to configure the mongocryptd process or mongo_crypt shared library.
//
// # Supported Extra Options
//
// "mongocryptdURI" - The mongocryptd URI. Allows setting a custom URI used to communicate with the
// mongocryptd process. The default is "mongodb://localhost:27020", which works with the default
// mongocryptd process spawned by the Client. Must be a string.
//
// "mongocryptdBypassSpawn" - If set to true, the Client will not attempt to spawn a mongocryptd
// process. Must be a bool.
//
// "mongocryptdSpawnPath" - The path used when spawning mongocryptd.
// Defaults to empty string and spawns mongocryptd from system path. Must be a string.
//
// "mongocryptdSpawnArgs" - Command line arguments passed when spawning mongocryptd.
// Defaults to ["--idleShutdownTimeoutSecs=60"]. Must be an array of strings.
//
// "cryptSharedLibRequired" - If set to true, Client creation will return an error if the
// crypt_shared library is not loaded. If unset or set to false, Client creation will not return an
// error if the crypt_shared library is not loaded. The default is unset. Must be a bool.
//
// "cryptSharedLibPath" - The crypt_shared library override path. This must be the path to the
// crypt_shared dynamic library file (for example, a .so, .dll, or .dylib file), not the directory
// that contains it. If the override path is a relative path, it will be resolved relative to the
// working directory of the process. If the override path is a relative path and the first path
// component is the literal string "$ORIGIN", the "$ORIGIN" component will be replaced by the
// absolute path to the directory containing the linked libmongocrypt library. Setting an override
// path disables the default system library search path. If an override path is specified but the
// crypt_shared library cannot be loaded, Client creation will return an error. Must be a string.
func (a *AutoEncryptionOptions) SetExtraOptions(extraOpts map[string]interface{}) *AutoEncryptionOptions {
a.ExtraOptions = extraOpts
return a
}
// SetTLSConfig specifies tls.Config instances for each KMS provider to use to configure TLS on all connections created
// to the KMS provider.
//
// This should only be used to set custom TLS configurations. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12.
func (a *AutoEncryptionOptions) SetTLSConfig(tlsOpts map[string]*tls.Config) *AutoEncryptionOptions {
tlsConfigs := make(map[string]*tls.Config)
for provider, config := range tlsOpts {
// use TLS min version 1.2 to enforce more secure hash algorithms and advanced cipher suites
if config.MinVersion == 0 {
config.MinVersion = tls.VersionTLS12
}
tlsConfigs[provider] = config
}
a.TLSConfig = tlsConfigs
return a
}
// SetEncryptedFieldsMap specifies a map from namespace to local EncryptedFieldsMap document.
// EncryptedFieldsMap is used for Queryable Encryption.
// Queryable Encryption is in Public Technical Preview. Queryable Encryption should not be used in production and is subject to backwards breaking changes.
func (a *AutoEncryptionOptions) SetEncryptedFieldsMap(ef map[string]interface{}) *AutoEncryptionOptions {
a.EncryptedFieldsMap = ef
return a
}
// SetBypassQueryAnalysis specifies whether or not query analysis should be used for automatic encryption.
// Use this option when using explicit encryption with Queryable Encryption.
// Queryable Encryption is in Public Technical Preview. Queryable Encryption should not be used in production and is subject to backwards breaking changes.
func (a *AutoEncryptionOptions) SetBypassQueryAnalysis(bypass bool) *AutoEncryptionOptions {
a.BypassQueryAnalysis = &bypass
return a
}
// MergeAutoEncryptionOptions combines the argued AutoEncryptionOptions in a last-one wins fashion.
func MergeAutoEncryptionOptions(opts ...*AutoEncryptionOptions) *AutoEncryptionOptions {
aeo := AutoEncryption()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.KeyVaultClientOptions != nil {
aeo.KeyVaultClientOptions = opt.KeyVaultClientOptions
}
if opt.KeyVaultNamespace != "" {
aeo.KeyVaultNamespace = opt.KeyVaultNamespace
}
if opt.KmsProviders != nil {
aeo.KmsProviders = opt.KmsProviders
}
if opt.SchemaMap != nil {
aeo.SchemaMap = opt.SchemaMap
}
if opt.BypassAutoEncryption != nil {
aeo.BypassAutoEncryption = opt.BypassAutoEncryption
}
if opt.ExtraOptions != nil {
aeo.ExtraOptions = opt.ExtraOptions
}
if opt.TLSConfig != nil {
aeo.TLSConfig = opt.TLSConfig
}
if opt.EncryptedFieldsMap != nil {
aeo.EncryptedFieldsMap = opt.EncryptedFieldsMap
}
if opt.BypassQueryAnalysis != nil {
aeo.BypassQueryAnalysis = opt.BypassQueryAnalysis
}
if opt.HTTPClient != nil {
aeo.HTTPClient = opt.HTTPClient
}
}
return aeo
}

View File

@@ -0,0 +1,91 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// DefaultOrdered is the default value for the Ordered option in BulkWriteOptions.
var DefaultOrdered = true
// BulkWriteOptions represents options that can be used to configure a BulkWrite operation.
type BulkWriteOptions struct {
// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
// false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document
// validation.
BypassDocumentValidation *bool
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
Comment interface{}
// If true, no writes will be executed after one fails. The default value is true.
Ordered *bool
// Specifies parameters for all update and delete commands in the BulkWrite. This option is only valid for MongoDB
// versions >= 5.0. Older servers will report an error for using this option. This must be a document mapping
// parameter names to values. Values must be constant or closed expressions that do not reference document fields.
// Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var").
Let interface{}
}
// BulkWrite creates a new *BulkWriteOptions instance.
func BulkWrite() *BulkWriteOptions {
return &BulkWriteOptions{
Ordered: &DefaultOrdered,
}
}
// SetComment sets the value for the Comment field.
func (b *BulkWriteOptions) SetComment(comment interface{}) *BulkWriteOptions {
b.Comment = comment
return b
}
// SetOrdered sets the value for the Ordered field.
func (b *BulkWriteOptions) SetOrdered(ordered bool) *BulkWriteOptions {
b.Ordered = &ordered
return b
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
func (b *BulkWriteOptions) SetBypassDocumentValidation(bypass bool) *BulkWriteOptions {
b.BypassDocumentValidation = &bypass
return b
}
// SetLet sets the value for the Let field. Let specifies parameters for all update and delete commands in the BulkWrite.
// This option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using this option.
// This must be a document mapping parameter names to values. Values must be constant or closed expressions that do not
// reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var").
func (b *BulkWriteOptions) SetLet(let interface{}) *BulkWriteOptions {
b.Let = &let
return b
}
// MergeBulkWriteOptions combines the given BulkWriteOptions instances into a single BulkWriteOptions in a last-one-wins
// fashion.
func MergeBulkWriteOptions(opts ...*BulkWriteOptions) *BulkWriteOptions {
b := BulkWrite()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Comment != nil {
b.Comment = opt.Comment
}
if opt.Ordered != nil {
b.Ordered = opt.Ordered
}
if opt.BypassDocumentValidation != nil {
b.BypassDocumentValidation = opt.BypassDocumentValidation
}
if opt.Let != nil {
b.Let = opt.Let
}
}
return b
}

View File

@@ -0,0 +1,205 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// ChangeStreamOptions represents options that can be used to configure a Watch operation.
type ChangeStreamOptions struct {
// The maximum number of documents to be included in each batch returned by the server.
BatchSize *int32
// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the default collation of the collection will be used.
Collation *Collation
// A string that will be included in server logs, profiling logs, and currentOp queries to help trace the operation.
// The default is nil, which means that no comment will be included in the logs.
Comment *string
// Specifies how the updated document should be returned in change notifications for update operations. The default
// is options.Default, which means that only partial update deltas will be included in the change notification.
FullDocument *FullDocument
// Specifies how the pre-update document should be returned in change notifications for update operations. The default
// is options.Off, which means that the pre-update document will not be included in the change notification.
FullDocumentBeforeChange *FullDocument
// The maximum amount of time that the server should wait for new documents to satisfy a tailable cursor query.
MaxAwaitTime *time.Duration
// A document specifying the logical starting point for the change stream. Only changes corresponding to an oplog
// entry immediately after the resume token will be returned. If this is specified, StartAtOperationTime and
// StartAfter must not be set.
ResumeAfter interface{}
// ShowExpandedEvents specifies whether the server will return an expanded list of change stream events. Additional
// events include: createIndexes, dropIndexes, modify, create, shardCollection, reshardCollection and
// refineCollectionShardKey. This option is only valid for MongoDB versions >= 6.0.
ShowExpandedEvents *bool
// If specified, the change stream will only return changes that occurred at or after the given timestamp. This
// option is only valid for MongoDB versions >= 4.0. If this is specified, ResumeAfter and StartAfter must not be
// set.
StartAtOperationTime *primitive.Timestamp
// A document specifying the logical starting point for the change stream. This is similar to the ResumeAfter
// option, but allows a resume token from an "invalidate" notification to be used. This allows a change stream on a
// collection to be resumed after the collection has been dropped and recreated or renamed. Only changes
// corresponding to an oplog entry immediately after the specified token will be returned. If this is specified,
// ResumeAfter and StartAtOperationTime must not be set. This option is only valid for MongoDB versions >= 4.1.1.
StartAfter interface{}
// Custom options to be added to the initial aggregate for the change stream. Key-value pairs of the BSON map should
// correlate with desired option names and values. Values must be Marshalable. Custom options may conflict with
// non-custom options, and custom options bypass client-side validation. Prefer using non-custom options where possible.
Custom bson.M
// Custom options to be added to the $changeStream stage in the initial aggregate. Key-value pairs of the BSON map should
// correlate with desired option names and values. Values must be Marshalable. Custom pipeline options bypass client-side
// validation. Prefer using non-custom options where possible.
CustomPipeline bson.M
}
// ChangeStream creates a new ChangeStreamOptions instance.
func ChangeStream() *ChangeStreamOptions {
cso := &ChangeStreamOptions{}
cso.SetFullDocument(Default)
return cso
}
// SetBatchSize sets the value for the BatchSize field.
func (cso *ChangeStreamOptions) SetBatchSize(i int32) *ChangeStreamOptions {
cso.BatchSize = &i
return cso
}
// SetCollation sets the value for the Collation field.
func (cso *ChangeStreamOptions) SetCollation(c Collation) *ChangeStreamOptions {
cso.Collation = &c
return cso
}
// SetComment sets the value for the Comment field.
func (cso *ChangeStreamOptions) SetComment(comment string) *ChangeStreamOptions {
cso.Comment = &comment
return cso
}
// SetFullDocument sets the value for the FullDocument field.
func (cso *ChangeStreamOptions) SetFullDocument(fd FullDocument) *ChangeStreamOptions {
cso.FullDocument = &fd
return cso
}
// SetFullDocumentBeforeChange sets the value for the FullDocumentBeforeChange field.
func (cso *ChangeStreamOptions) SetFullDocumentBeforeChange(fdbc FullDocument) *ChangeStreamOptions {
cso.FullDocumentBeforeChange = &fdbc
return cso
}
// SetMaxAwaitTime sets the value for the MaxAwaitTime field.
func (cso *ChangeStreamOptions) SetMaxAwaitTime(d time.Duration) *ChangeStreamOptions {
cso.MaxAwaitTime = &d
return cso
}
// SetResumeAfter sets the value for the ResumeAfter field.
func (cso *ChangeStreamOptions) SetResumeAfter(rt interface{}) *ChangeStreamOptions {
cso.ResumeAfter = rt
return cso
}
// SetShowExpandedEvents sets the value for the ShowExpandedEvents field.
func (cso *ChangeStreamOptions) SetShowExpandedEvents(see bool) *ChangeStreamOptions {
cso.ShowExpandedEvents = &see
return cso
}
// SetStartAtOperationTime sets the value for the StartAtOperationTime field.
func (cso *ChangeStreamOptions) SetStartAtOperationTime(t *primitive.Timestamp) *ChangeStreamOptions {
cso.StartAtOperationTime = t
return cso
}
// SetStartAfter sets the value for the StartAfter field.
func (cso *ChangeStreamOptions) SetStartAfter(sa interface{}) *ChangeStreamOptions {
cso.StartAfter = sa
return cso
}
// SetCustom sets the value for the Custom field. Key-value pairs of the BSON map should correlate
// with desired option names and values. Values must be Marshalable. Custom options may conflict
// with non-custom options, and custom options bypass client-side validation. Prefer using non-custom
// options where possible.
func (cso *ChangeStreamOptions) SetCustom(c bson.M) *ChangeStreamOptions {
cso.Custom = c
return cso
}
// SetCustomPipeline sets the value for the CustomPipeline field. Key-value pairs of the BSON map
// should correlate with desired option names and values. Values must be Marshalable. Custom pipeline
// options bypass client-side validation. Prefer using non-custom options where possible.
func (cso *ChangeStreamOptions) SetCustomPipeline(cp bson.M) *ChangeStreamOptions {
cso.CustomPipeline = cp
return cso
}
// MergeChangeStreamOptions combines the given ChangeStreamOptions instances into a single ChangeStreamOptions in a
// last-one-wins fashion.
func MergeChangeStreamOptions(opts ...*ChangeStreamOptions) *ChangeStreamOptions {
csOpts := ChangeStream()
for _, cso := range opts {
if cso == nil {
continue
}
if cso.BatchSize != nil {
csOpts.BatchSize = cso.BatchSize
}
if cso.Collation != nil {
csOpts.Collation = cso.Collation
}
if cso.Comment != nil {
csOpts.Comment = cso.Comment
}
if cso.FullDocument != nil {
csOpts.FullDocument = cso.FullDocument
}
if cso.FullDocumentBeforeChange != nil {
csOpts.FullDocumentBeforeChange = cso.FullDocumentBeforeChange
}
if cso.MaxAwaitTime != nil {
csOpts.MaxAwaitTime = cso.MaxAwaitTime
}
if cso.ResumeAfter != nil {
csOpts.ResumeAfter = cso.ResumeAfter
}
if cso.ShowExpandedEvents != nil {
csOpts.ShowExpandedEvents = cso.ShowExpandedEvents
}
if cso.StartAtOperationTime != nil {
csOpts.StartAtOperationTime = cso.StartAtOperationTime
}
if cso.StartAfter != nil {
csOpts.StartAfter = cso.StartAfter
}
if cso.Custom != nil {
csOpts.Custom = cso.Custom
}
if cso.CustomPipeline != nil {
csOpts.CustomPipeline = cso.CustomPipeline
}
}
return csOpts
}

View File

@@ -0,0 +1,147 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"crypto/tls"
"fmt"
"net/http"
"go.mongodb.org/mongo-driver/internal"
)
// ClientEncryptionOptions represents all possible options used to configure a ClientEncryption instance.
type ClientEncryptionOptions struct {
KeyVaultNamespace string
KmsProviders map[string]map[string]interface{}
TLSConfig map[string]*tls.Config
HTTPClient *http.Client
}
// ClientEncryption creates a new ClientEncryptionOptions instance.
func ClientEncryption() *ClientEncryptionOptions {
return &ClientEncryptionOptions{
HTTPClient: internal.DefaultHTTPClient,
}
}
// SetKeyVaultNamespace specifies the namespace of the key vault collection. This is required.
func (c *ClientEncryptionOptions) SetKeyVaultNamespace(ns string) *ClientEncryptionOptions {
c.KeyVaultNamespace = ns
return c
}
// SetKmsProviders specifies options for KMS providers. This is required.
func (c *ClientEncryptionOptions) SetKmsProviders(providers map[string]map[string]interface{}) *ClientEncryptionOptions {
c.KmsProviders = providers
return c
}
// SetTLSConfig specifies tls.Config instances for each KMS provider to use to configure TLS on all connections created
// to the KMS provider.
//
// This should only be used to set custom TLS configurations. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12.
func (c *ClientEncryptionOptions) SetTLSConfig(tlsOpts map[string]*tls.Config) *ClientEncryptionOptions {
tlsConfigs := make(map[string]*tls.Config)
for provider, config := range tlsOpts {
// use TLS min version 1.2 to enforce more secure hash algorithms and advanced cipher suites
if config.MinVersion == 0 {
config.MinVersion = tls.VersionTLS12
}
tlsConfigs[provider] = config
}
c.TLSConfig = tlsConfigs
return c
}
// BuildTLSConfig specifies tls.Config options for each KMS provider to use to configure TLS on all connections created
// to the KMS provider. The input map should contain a mapping from each KMS provider to a document containing the necessary
// options, as follows:
//
// {
// "kmip": {
// "tlsCertificateKeyFile": "foo.pem",
// "tlsCAFile": "fooCA.pem"
// }
// }
//
// Currently, the following TLS options are supported:
//
// 1. "tlsCertificateKeyFile" (or "sslClientCertificateKeyFile"): The "tlsCertificateKeyFile" option specifies a path to
// the client certificate and private key, which must be concatenated into one file.
//
// 2. "tlsCertificateKeyFilePassword" (or "sslClientCertificateKeyPassword"): Specify the password to decrypt the client
// private key file (e.g. "tlsCertificateKeyFilePassword=password").
//
// 3. "tlsCaFile" (or "sslCertificateAuthorityFile"): Specify the path to a single or bundle of certificate authorities
// to be considered trusted when making a TLS connection (e.g. "tlsCaFile=/path/to/caFile").
//
// This should only be used to set custom TLS options. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12.
func BuildTLSConfig(tlsOpts map[string]interface{}) (*tls.Config, error) {
// use TLS min version 1.2 to enforce more secure hash algorithms and advanced cipher suites
cfg := &tls.Config{MinVersion: tls.VersionTLS12}
for name := range tlsOpts {
var err error
switch name {
case "tlsCertificateKeyFile", "sslClientCertificateKeyFile":
clientCertPath, ok := tlsOpts[name].(string)
if !ok {
return nil, fmt.Errorf("expected %q value to be of type string, got %T", name, tlsOpts[name])
}
// apply custom key file password if found, otherwise use empty string
if keyPwd, found := tlsOpts["tlsCertificateKeyFilePassword"].(string); found {
_, err = addClientCertFromConcatenatedFile(cfg, clientCertPath, keyPwd)
} else if keyPwd, found := tlsOpts["sslClientCertificateKeyPassword"].(string); found {
_, err = addClientCertFromConcatenatedFile(cfg, clientCertPath, keyPwd)
} else {
_, err = addClientCertFromConcatenatedFile(cfg, clientCertPath, "")
}
case "tlsCertificateKeyFilePassword", "sslClientCertificateKeyPassword":
continue
case "tlsCAFile", "sslCertificateAuthorityFile":
caPath, ok := tlsOpts[name].(string)
if !ok {
return nil, fmt.Errorf("expected %q value to be of type string, got %T", name, tlsOpts[name])
}
err = addCACertFromFile(cfg, caPath)
default:
return nil, fmt.Errorf("unrecognized TLS option %v", name)
}
if err != nil {
return nil, err
}
}
return cfg, nil
}
// MergeClientEncryptionOptions combines the argued ClientEncryptionOptions in a last-one wins fashion.
func MergeClientEncryptionOptions(opts ...*ClientEncryptionOptions) *ClientEncryptionOptions {
ceo := ClientEncryption()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.KeyVaultNamespace != "" {
ceo.KeyVaultNamespace = opt.KeyVaultNamespace
}
if opt.KmsProviders != nil {
ceo.KmsProviders = opt.KmsProviders
}
if opt.TLSConfig != nil {
ceo.TLSConfig = opt.TLSConfig
}
if opt.HTTPClient != nil {
ceo.HTTPClient = opt.HTTPClient
}
}
return ceo
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
// CollectionOptions represents options that can be used to configure a Collection.
type CollectionOptions struct {
// ReadConcern is the read concern to use for operations executed on the Collection. The default value is nil, which means that
// the read concern of the Database used to configure the Collection will be used.
ReadConcern *readconcern.ReadConcern
// WriteConcern is the write concern to use for operations executed on the Collection. The default value is nil, which means that
// the write concern of the Database used to configure the Collection will be used.
WriteConcern *writeconcern.WriteConcern
// ReadPreference is the read preference to use for operations executed on the Collection. The default value is nil, which means that
// the read preference of the Database used to configure the Collection will be used.
ReadPreference *readpref.ReadPref
// Registry is the BSON registry to marshal and unmarshal documents for operations executed on the Collection. The default value
// is nil, which means that the registry of the Database used to configure the Collection will be used.
Registry *bsoncodec.Registry
}
// Collection creates a new CollectionOptions instance.
func Collection() *CollectionOptions {
return &CollectionOptions{}
}
// SetReadConcern sets the value for the ReadConcern field.
func (c *CollectionOptions) SetReadConcern(rc *readconcern.ReadConcern) *CollectionOptions {
c.ReadConcern = rc
return c
}
// SetWriteConcern sets the value for the WriteConcern field.
func (c *CollectionOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *CollectionOptions {
c.WriteConcern = wc
return c
}
// SetReadPreference sets the value for the ReadPreference field.
func (c *CollectionOptions) SetReadPreference(rp *readpref.ReadPref) *CollectionOptions {
c.ReadPreference = rp
return c
}
// SetRegistry sets the value for the Registry field.
func (c *CollectionOptions) SetRegistry(r *bsoncodec.Registry) *CollectionOptions {
c.Registry = r
return c
}
// MergeCollectionOptions combines the given CollectionOptions instances into a single *CollectionOptions in a
// last-one-wins fashion.
func MergeCollectionOptions(opts ...*CollectionOptions) *CollectionOptions {
c := Collection()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.ReadConcern != nil {
c.ReadConcern = opt.ReadConcern
}
if opt.WriteConcern != nil {
c.WriteConcern = opt.WriteConcern
}
if opt.ReadPreference != nil {
c.ReadPreference = opt.ReadPreference
}
if opt.Registry != nil {
c.Registry = opt.Registry
}
}
return c
}

View File

@@ -0,0 +1,119 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "time"
// CountOptions represents options that can be used to configure a CountDocuments operation.
type CountOptions struct {
// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the default collation of the collection will be used.
Collation *Collation
// TODO(GODRIVER-2386): CountOptions executor uses aggregation under the hood, which means this type has to be
// TODO a string for now. This can be replaced with `Comment interface{}` once 2386 is implemented.
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default is nil, which means that no comment will be included in the logs.
Comment *string
// The index to use for the aggregation. This should either be the index name as a string or the index specification
// as a document. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
// which means that no hint will be sent.
Hint interface{}
// The maximum number of documents to count. The default value is 0, which means that there is no limit and all
// documents matching the filter will be counted.
Limit *int64
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there is
// no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be used in
// its place to control the amount of time that a single operation can run before returning an error. MaxTime is
// ignored if Timeout is set on the client.
MaxTime *time.Duration
// The number of documents to skip before counting. The default value is 0.
Skip *int64
}
// Count creates a new CountOptions instance.
func Count() *CountOptions {
return &CountOptions{}
}
// SetCollation sets the value for the Collation field.
func (co *CountOptions) SetCollation(c *Collation) *CountOptions {
co.Collation = c
return co
}
// SetComment sets the value for the Comment field.
func (co *CountOptions) SetComment(c string) *CountOptions {
co.Comment = &c
return co
}
// SetHint sets the value for the Hint field.
func (co *CountOptions) SetHint(h interface{}) *CountOptions {
co.Hint = h
return co
}
// SetLimit sets the value for the Limit field.
func (co *CountOptions) SetLimit(i int64) *CountOptions {
co.Limit = &i
return co
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can
// run before returning an error. MaxTime is ignored if Timeout is set on the client.
func (co *CountOptions) SetMaxTime(d time.Duration) *CountOptions {
co.MaxTime = &d
return co
}
// SetSkip sets the value for the Skip field.
func (co *CountOptions) SetSkip(i int64) *CountOptions {
co.Skip = &i
return co
}
// MergeCountOptions combines the given CountOptions instances into a single CountOptions in a last-one-wins fashion.
func MergeCountOptions(opts ...*CountOptions) *CountOptions {
countOpts := Count()
for _, co := range opts {
if co == nil {
continue
}
if co.Collation != nil {
countOpts.Collation = co.Collation
}
if co.Comment != nil {
countOpts.Comment = co.Comment
}
if co.Hint != nil {
countOpts.Hint = co.Hint
}
if co.Limit != nil {
countOpts.Limit = co.Limit
}
if co.MaxTime != nil {
countOpts.MaxTime = co.MaxTime
}
if co.Skip != nil {
countOpts.Skip = co.Skip
}
}
return countOpts
}

View File

@@ -0,0 +1,326 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// DefaultIndexOptions represents the default options for a collection to apply on new indexes. This type can be used
// when creating a new collection through the CreateCollectionOptions.SetDefaultIndexOptions method.
type DefaultIndexOptions struct {
// Specifies the storage engine to use for the index. The value must be a document in the form
// {<storage engine name>: <options>}. The default value is nil, which means that the default storage engine
// will be used.
StorageEngine interface{}
}
// DefaultIndex creates a new DefaultIndexOptions instance.
func DefaultIndex() *DefaultIndexOptions {
return &DefaultIndexOptions{}
}
// SetStorageEngine sets the value for the StorageEngine field.
func (d *DefaultIndexOptions) SetStorageEngine(storageEngine interface{}) *DefaultIndexOptions {
d.StorageEngine = storageEngine
return d
}
// TimeSeriesOptions specifies options on a time-series collection.
type TimeSeriesOptions struct {
// Name of the top-level field to be used for time. Inserted documents must have this field,
// and the field must be of the BSON UTC datetime type (0x9).
TimeField string
// Optional name of the top-level field describing the series. This field is used to group
// related data and may be of any BSON type, except for array. This name may not be the same
// as the TimeField or _id.
MetaField *string
// Optional string specifying granularity of time-series data. Allowed granularity options are
// "seconds", "minutes" and "hours".
Granularity *string
}
// TimeSeries creates a new TimeSeriesOptions instance.
func TimeSeries() *TimeSeriesOptions {
return &TimeSeriesOptions{}
}
// SetTimeField sets the value for the TimeField.
func (tso *TimeSeriesOptions) SetTimeField(timeField string) *TimeSeriesOptions {
tso.TimeField = timeField
return tso
}
// SetMetaField sets the value for the MetaField.
func (tso *TimeSeriesOptions) SetMetaField(metaField string) *TimeSeriesOptions {
tso.MetaField = &metaField
return tso
}
// SetGranularity sets the value for Granularity.
func (tso *TimeSeriesOptions) SetGranularity(granularity string) *TimeSeriesOptions {
tso.Granularity = &granularity
return tso
}
// CreateCollectionOptions represents options that can be used to configure a CreateCollection operation.
type CreateCollectionOptions struct {
// Specifies if the collection is capped (see https://www.mongodb.com/docs/manual/core/capped-collections/). If true,
// the SizeInBytes option must also be specified. The default value is false.
Capped *bool
// Specifies the default collation for the new collection. This option is only valid for MongoDB versions >= 3.4.
// For previous server versions, the driver will return an error if this option is used. The default value is nil.
Collation *Collation
// Specifies how change streams opened against the collection can return pre- and post-images of updated
// documents. The value must be a document in the form {<option name>: <options>}. This option is only valid for
// MongoDB versions >= 6.0. The default value is nil, which means that change streams opened against the collection
// will not return pre- and post-images of updated documents in any way.
ChangeStreamPreAndPostImages interface{}
// Specifies a default configuration for indexes on the collection. This option is only valid for MongoDB versions
// >= 3.4. The default value is nil, meaning indexes will be configured using server defaults.
DefaultIndexOptions *DefaultIndexOptions
// Specifies the maximum number of documents allowed in a capped collection. The limit specified by the SizeInBytes
// option takes precedence over this option. If a capped collection reaches its size limit, old documents will be
// removed, regardless of the number of documents in the collection. The default value is 0, meaning the maximum
// number of documents is unbounded.
MaxDocuments *int64
// Specifies the maximum size in bytes for a capped collection. The default value is 0.
SizeInBytes *int64
// Specifies the storage engine to use for the index. The value must be a document in the form
// {<storage engine name>: <options>}. The default value is nil, which means that the default storage engine
// will be used.
StorageEngine interface{}
// Specifies what should happen if a document being inserted does not pass validation. Valid values are "error" and
// "warn". See https://www.mongodb.com/docs/manual/core/schema-validation/#accept-or-reject-invalid-documents for more
// information. This option is only valid for MongoDB versions >= 3.2. The default value is "error".
ValidationAction *string
// Specifies how strictly the server applies validation rules to existing documents in the collection during update
// operations. Valid values are "off", "strict", and "moderate". See
// https://www.mongodb.com/docs/manual/core/schema-validation/#existing-documents for more information. This option is
// only valid for MongoDB versions >= 3.2. The default value is "strict".
ValidationLevel *string
// A document specifying validation rules for the collection. See
// https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about schema validation. This option
// is only valid for MongoDB versions >= 3.2. The default value is nil, meaning no validator will be used for the
// collection.
Validator interface{}
// Value indicating after how many seconds old time-series data should be deleted. See
// https://www.mongodb.com/docs/manual/reference/command/create/ for supported options, and
// https://www.mongodb.com/docs/manual/core/timeseries-collections/ for more information on time-series
// collections.
//
// This option is only valid for MongoDB versions >= 5.0
ExpireAfterSeconds *int64
// Options for specifying a time-series collection. See
// https://www.mongodb.com/docs/manual/reference/command/create/ for supported options, and
// https://www.mongodb.com/docs/manual/core/timeseries-collections/ for more information on time-series
// collections.
//
// This option is only valid for MongoDB versions >= 5.0
TimeSeriesOptions *TimeSeriesOptions
// EncryptedFields configures encrypted fields.
//
// This option is only valid for MongoDB versions >= 6.0
EncryptedFields interface{}
// ClusteredIndex is used to create a collection with a clustered index.
//
// This option is only valid for MongoDB versions >= 5.3
ClusteredIndex interface{}
}
// CreateCollection creates a new CreateCollectionOptions instance.
func CreateCollection() *CreateCollectionOptions {
return &CreateCollectionOptions{}
}
// SetCapped sets the value for the Capped field.
func (c *CreateCollectionOptions) SetCapped(capped bool) *CreateCollectionOptions {
c.Capped = &capped
return c
}
// SetCollation sets the value for the Collation field.
func (c *CreateCollectionOptions) SetCollation(collation *Collation) *CreateCollectionOptions {
c.Collation = collation
return c
}
// SetChangeStreamPreAndPostImages sets the value for the ChangeStreamPreAndPostImages field.
func (c *CreateCollectionOptions) SetChangeStreamPreAndPostImages(csppi interface{}) *CreateCollectionOptions {
c.ChangeStreamPreAndPostImages = &csppi
return c
}
// SetDefaultIndexOptions sets the value for the DefaultIndexOptions field.
func (c *CreateCollectionOptions) SetDefaultIndexOptions(opts *DefaultIndexOptions) *CreateCollectionOptions {
c.DefaultIndexOptions = opts
return c
}
// SetMaxDocuments sets the value for the MaxDocuments field.
func (c *CreateCollectionOptions) SetMaxDocuments(max int64) *CreateCollectionOptions {
c.MaxDocuments = &max
return c
}
// SetSizeInBytes sets the value for the SizeInBytes field.
func (c *CreateCollectionOptions) SetSizeInBytes(size int64) *CreateCollectionOptions {
c.SizeInBytes = &size
return c
}
// SetStorageEngine sets the value for the StorageEngine field.
func (c *CreateCollectionOptions) SetStorageEngine(storageEngine interface{}) *CreateCollectionOptions {
c.StorageEngine = &storageEngine
return c
}
// SetValidationAction sets the value for the ValidationAction field.
func (c *CreateCollectionOptions) SetValidationAction(action string) *CreateCollectionOptions {
c.ValidationAction = &action
return c
}
// SetValidationLevel sets the value for the ValidationLevel field.
func (c *CreateCollectionOptions) SetValidationLevel(level string) *CreateCollectionOptions {
c.ValidationLevel = &level
return c
}
// SetValidator sets the value for the Validator field.
func (c *CreateCollectionOptions) SetValidator(validator interface{}) *CreateCollectionOptions {
c.Validator = validator
return c
}
// SetExpireAfterSeconds sets the value for the ExpireAfterSeconds field.
func (c *CreateCollectionOptions) SetExpireAfterSeconds(eas int64) *CreateCollectionOptions {
c.ExpireAfterSeconds = &eas
return c
}
// SetTimeSeriesOptions sets the options for time-series collections.
func (c *CreateCollectionOptions) SetTimeSeriesOptions(timeSeriesOpts *TimeSeriesOptions) *CreateCollectionOptions {
c.TimeSeriesOptions = timeSeriesOpts
return c
}
// SetEncryptedFields sets the encrypted fields for encrypted collections.
func (c *CreateCollectionOptions) SetEncryptedFields(encryptedFields interface{}) *CreateCollectionOptions {
c.EncryptedFields = encryptedFields
return c
}
// SetClusteredIndex sets the value for the ClusteredIndex field.
func (c *CreateCollectionOptions) SetClusteredIndex(clusteredIndex interface{}) *CreateCollectionOptions {
c.ClusteredIndex = clusteredIndex
return c
}
// MergeCreateCollectionOptions combines the given CreateCollectionOptions instances into a single
// CreateCollectionOptions in a last-one-wins fashion.
func MergeCreateCollectionOptions(opts ...*CreateCollectionOptions) *CreateCollectionOptions {
cc := CreateCollection()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Capped != nil {
cc.Capped = opt.Capped
}
if opt.Collation != nil {
cc.Collation = opt.Collation
}
if opt.ChangeStreamPreAndPostImages != nil {
cc.ChangeStreamPreAndPostImages = opt.ChangeStreamPreAndPostImages
}
if opt.DefaultIndexOptions != nil {
cc.DefaultIndexOptions = opt.DefaultIndexOptions
}
if opt.MaxDocuments != nil {
cc.MaxDocuments = opt.MaxDocuments
}
if opt.SizeInBytes != nil {
cc.SizeInBytes = opt.SizeInBytes
}
if opt.StorageEngine != nil {
cc.StorageEngine = opt.StorageEngine
}
if opt.ValidationAction != nil {
cc.ValidationAction = opt.ValidationAction
}
if opt.ValidationLevel != nil {
cc.ValidationLevel = opt.ValidationLevel
}
if opt.Validator != nil {
cc.Validator = opt.Validator
}
if opt.ExpireAfterSeconds != nil {
cc.ExpireAfterSeconds = opt.ExpireAfterSeconds
}
if opt.TimeSeriesOptions != nil {
cc.TimeSeriesOptions = opt.TimeSeriesOptions
}
if opt.EncryptedFields != nil {
cc.EncryptedFields = opt.EncryptedFields
}
if opt.ClusteredIndex != nil {
cc.ClusteredIndex = opt.ClusteredIndex
}
}
return cc
}
// CreateViewOptions represents options that can be used to configure a CreateView operation.
type CreateViewOptions struct {
// Specifies the default collation for the new collection. This option is only valid for MongoDB versions >= 3.4.
// For previous server versions, the driver will return an error if this option is used. The default value is nil.
Collation *Collation
}
// CreateView creates an new CreateViewOptions instance.
func CreateView() *CreateViewOptions {
return &CreateViewOptions{}
}
// SetCollation sets the value for the Collation field.
func (c *CreateViewOptions) SetCollation(collation *Collation) *CreateViewOptions {
c.Collation = collation
return c
}
// MergeCreateViewOptions combines the given CreateViewOptions instances into a single CreateViewOptions in a
// last-one-wins fashion.
func MergeCreateViewOptions(opts ...*CreateViewOptions) *CreateViewOptions {
cv := CreateView()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Collation != nil {
cv.Collation = opt.Collation
}
}
return cv
}

View File

@@ -0,0 +1,101 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// DataKeyOptions represents all possible options used to create a new data key.
type DataKeyOptions struct {
MasterKey interface{}
KeyAltNames []string
// KeyMaterial is used to encrypt data. If omitted, keyMaterial is generated form a cryptographically secure random
// source. "Key Material" is used interchangeably with "dataKey" and "Data Encryption Key" (DEK).
KeyMaterial []byte
}
// DataKey creates a new DataKeyOptions instance.
func DataKey() *DataKeyOptions {
return &DataKeyOptions{}
}
// SetMasterKey specifies a KMS-specific key used to encrypt the new data key.
//
// If being used with a local KMS provider, this option is not applicable and should not be specified.
//
// For the AWS, Azure, and GCP KMS providers, this option is required and must be a document. For each, the value of the
// "endpoint" or "keyVaultEndpoint" must be a host name with an optional port number (e.g. "foo.com" or "foo.com:443").
//
// When using AWS, the document must have the format:
//
// {
// region: <string>,
// key: <string>, // The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
// endpoint: Optional<string> // An alternate host identifier to send KMS requests to.
// }
//
// If unset, the "endpoint" defaults to "kms.<region>.amazonaws.com".
//
// When using Azure, the document must have the format:
//
// {
// keyVaultEndpoint: <string>, // A host identifier to send KMS requests to.
// keyName: <string>,
// keyVersion: Optional<string> // A specific version of the named key.
// }
//
// If unset, "keyVersion" defaults to the key's primary version.
//
// When using GCP, the document must have the format:
//
// {
// projectId: <string>,
// location: <string>,
// keyRing: <string>,
// keyName: <string>,
// keyVersion: Optional<string>, // A specific version of the named key.
// endpoint: Optional<string> // An alternate host identifier to send KMS requests to.
// }
//
// If unset, "keyVersion" defaults to the key's primary version and "endpoint" defaults to "cloudkms.googleapis.com".
func (dk *DataKeyOptions) SetMasterKey(masterKey interface{}) *DataKeyOptions {
dk.MasterKey = masterKey
return dk
}
// SetKeyAltNames specifies an optional list of string alternate names used to reference a key. If a key is created'
// with alternate names, encryption may refer to the key by a unique alternate name instead of by _id.
func (dk *DataKeyOptions) SetKeyAltNames(keyAltNames []string) *DataKeyOptions {
dk.KeyAltNames = keyAltNames
return dk
}
// SetKeyMaterial will set a custom keyMaterial to DataKeyOptions which can be used to encrypt data.
func (dk *DataKeyOptions) SetKeyMaterial(keyMaterial []byte) *DataKeyOptions {
dk.KeyMaterial = keyMaterial
return dk
}
// MergeDataKeyOptions combines the argued DataKeyOptions in a last-one wins fashion.
func MergeDataKeyOptions(opts ...*DataKeyOptions) *DataKeyOptions {
dko := DataKey()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.MasterKey != nil {
dko.MasterKey = opt.MasterKey
}
if opt.KeyAltNames != nil {
dko.KeyAltNames = opt.KeyAltNames
}
if opt.KeyMaterial != nil {
dko.KeyMaterial = opt.KeyMaterial
}
}
return dko
}

View File

@@ -0,0 +1,88 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
// DatabaseOptions represents options that can be used to configure a Database.
type DatabaseOptions struct {
// ReadConcern is the read concern to use for operations executed on the Database. The default value is nil, which means that
// the read concern of the Client used to configure the Database will be used.
ReadConcern *readconcern.ReadConcern
// WriteConcern is the write concern to use for operations executed on the Database. The default value is nil, which means that the
// write concern of the Client used to configure the Database will be used.
WriteConcern *writeconcern.WriteConcern
// ReadPreference is the read preference to use for operations executed on the Database. The default value is nil, which means that
// the read preference of the Client used to configure the Database will be used.
ReadPreference *readpref.ReadPref
// Registry is the BSON registry to marshal and unmarshal documents for operations executed on the Database. The default value
// is nil, which means that the registry of the Client used to configure the Database will be used.
Registry *bsoncodec.Registry
}
// Database creates a new DatabaseOptions instance.
func Database() *DatabaseOptions {
return &DatabaseOptions{}
}
// SetReadConcern sets the value for the ReadConcern field.
func (d *DatabaseOptions) SetReadConcern(rc *readconcern.ReadConcern) *DatabaseOptions {
d.ReadConcern = rc
return d
}
// SetWriteConcern sets the value for the WriteConcern field.
func (d *DatabaseOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *DatabaseOptions {
d.WriteConcern = wc
return d
}
// SetReadPreference sets the value for the ReadPreference field.
func (d *DatabaseOptions) SetReadPreference(rp *readpref.ReadPref) *DatabaseOptions {
d.ReadPreference = rp
return d
}
// SetRegistry sets the value for the Registry field.
func (d *DatabaseOptions) SetRegistry(r *bsoncodec.Registry) *DatabaseOptions {
d.Registry = r
return d
}
// MergeDatabaseOptions combines the given DatabaseOptions instances into a single DatabaseOptions in a last-one-wins
// fashion.
func MergeDatabaseOptions(opts ...*DatabaseOptions) *DatabaseOptions {
d := Database()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.ReadConcern != nil {
d.ReadConcern = opt.ReadConcern
}
if opt.WriteConcern != nil {
d.WriteConcern = opt.WriteConcern
}
if opt.ReadPreference != nil {
d.ReadPreference = opt.ReadPreference
}
if opt.Registry != nil {
d.Registry = opt.Registry
}
}
return d
}

View File

@@ -0,0 +1,86 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// DeleteOptions represents options that can be used to configure DeleteOne and DeleteMany operations.
type DeleteOptions struct {
// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the default collation of the collection will be used.
Collation *Collation
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
Comment interface{}
// The index to use for the operation. This should either be the index name as a string or the index specification
// as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an error
// if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option
// is specified. The driver will return an error if this option is specified during an unacknowledged write
// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
// which means that no hint will be sent.
Hint interface{}
// Specifies parameters for the delete expression. This option is only valid for MongoDB versions >= 5.0. Older
// servers will report an error for using this option. This must be a document mapping parameter names to values.
// Values must be constant or closed expressions that do not reference document fields. Parameters can then be
// accessed as variables in an aggregate expression context (e.g. "$$var").
Let interface{}
}
// Delete creates a new DeleteOptions instance.
func Delete() *DeleteOptions {
return &DeleteOptions{}
}
// SetCollation sets the value for the Collation field.
func (do *DeleteOptions) SetCollation(c *Collation) *DeleteOptions {
do.Collation = c
return do
}
// SetComment sets the value for the Comment field.
func (do *DeleteOptions) SetComment(comment interface{}) *DeleteOptions {
do.Comment = comment
return do
}
// SetHint sets the value for the Hint field.
func (do *DeleteOptions) SetHint(hint interface{}) *DeleteOptions {
do.Hint = hint
return do
}
// SetLet sets the value for the Let field.
func (do *DeleteOptions) SetLet(let interface{}) *DeleteOptions {
do.Let = let
return do
}
// MergeDeleteOptions combines the given DeleteOptions instances into a single DeleteOptions in a last-one-wins fashion.
func MergeDeleteOptions(opts ...*DeleteOptions) *DeleteOptions {
dOpts := Delete()
for _, do := range opts {
if do == nil {
continue
}
if do.Collation != nil {
dOpts.Collation = do.Collation
}
if do.Comment != nil {
dOpts.Comment = do.Comment
}
if do.Hint != nil {
dOpts.Hint = do.Hint
}
if do.Let != nil {
dOpts.Let = do.Let
}
}
return dOpts
}

View File

@@ -0,0 +1,78 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "time"
// DistinctOptions represents options that can be used to configure a Distinct operation.
type DistinctOptions struct {
// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the default collation of the collection will be used.
Collation *Collation
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
Comment interface{}
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
// is no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be
// used in its place to control the amount of time that a single operation can run before returning an error.
// MaxTime is ignored if Timeout is set on the client.
MaxTime *time.Duration
}
// Distinct creates a new DistinctOptions instance.
func Distinct() *DistinctOptions {
return &DistinctOptions{}
}
// SetCollation sets the value for the Collation field.
func (do *DistinctOptions) SetCollation(c *Collation) *DistinctOptions {
do.Collation = c
return do
}
// SetComment sets the value for the Comment field.
func (do *DistinctOptions) SetComment(comment interface{}) *DistinctOptions {
do.Comment = comment
return do
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can
// run before returning an error. MaxTime is ignored if Timeout is set on the client.
func (do *DistinctOptions) SetMaxTime(d time.Duration) *DistinctOptions {
do.MaxTime = &d
return do
}
// MergeDistinctOptions combines the given DistinctOptions instances into a single DistinctOptions in a last-one-wins
// fashion.
func MergeDistinctOptions(opts ...*DistinctOptions) *DistinctOptions {
distinctOpts := Distinct()
for _, do := range opts {
if do == nil {
continue
}
if do.Collation != nil {
distinctOpts.Collation = do.Collation
}
if do.Comment != nil {
distinctOpts.Comment = do.Comment
}
if do.MaxTime != nil {
distinctOpts.MaxTime = do.MaxTime
}
}
return distinctOpts
}

View File

@@ -0,0 +1,8 @@
// Copyright (C) MongoDB, Inc. 2022-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Package options defines the optional configurations for the MongoDB Go Driver.
package options

View File

@@ -0,0 +1,103 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"go.mongodb.org/mongo-driver/bson/primitive"
)
// These constants specify valid values for QueryType
// QueryType is used for Queryable Encryption.
// Queryable Encryption is in Public Technical Preview. Queryable Encryption should not be used in production and is subject to backwards breaking changes.
const (
QueryTypeEquality string = "equality"
)
// EncryptOptions represents options to explicitly encrypt a value.
type EncryptOptions struct {
KeyID *primitive.Binary
KeyAltName *string
Algorithm string
QueryType string
ContentionFactor *int64
}
// Encrypt creates a new EncryptOptions instance.
func Encrypt() *EncryptOptions {
return &EncryptOptions{}
}
// SetKeyID specifies an _id of a data key. This should be a UUID (a primitive.Binary with subtype 4).
func (e *EncryptOptions) SetKeyID(keyID primitive.Binary) *EncryptOptions {
e.KeyID = &keyID
return e
}
// SetKeyAltName identifies a key vault document by 'keyAltName'.
func (e *EncryptOptions) SetKeyAltName(keyAltName string) *EncryptOptions {
e.KeyAltName = &keyAltName
return e
}
// SetAlgorithm specifies an algorithm to use for encryption. This should be one of the following:
// - AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic
// - AEAD_AES_256_CBC_HMAC_SHA_512-Random
// - Indexed
// - Unindexed
// This is required.
// Indexed and Unindexed are used for Queryable Encryption.
// Queryable Encryption is in Public Technical Preview. Queryable Encryption should not be used in production and is subject to backwards breaking changes.
func (e *EncryptOptions) SetAlgorithm(algorithm string) *EncryptOptions {
e.Algorithm = algorithm
return e
}
// SetQueryType specifies the intended query type. It is only valid to set if algorithm is "Indexed".
// This should be one of the following:
// - equality
// QueryType is used for Queryable Encryption.
// Queryable Encryption is in Public Technical Preview. Queryable Encryption should not be used in production and is subject to backwards breaking changes.
func (e *EncryptOptions) SetQueryType(queryType string) *EncryptOptions {
e.QueryType = queryType
return e
}
// SetContentionFactor specifies the contention factor. It is only valid to set if algorithm is "Indexed".
// ContentionFactor is used for Queryable Encryption.
// Queryable Encryption is in Public Technical Preview. Queryable Encryption should not be used in production and is subject to backwards breaking changes.
func (e *EncryptOptions) SetContentionFactor(contentionFactor int64) *EncryptOptions {
e.ContentionFactor = &contentionFactor
return e
}
// MergeEncryptOptions combines the argued EncryptOptions in a last-one wins fashion.
func MergeEncryptOptions(opts ...*EncryptOptions) *EncryptOptions {
eo := Encrypt()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.KeyID != nil {
eo.KeyID = opt.KeyID
}
if opt.KeyAltName != nil {
eo.KeyAltName = opt.KeyAltName
}
if opt.Algorithm != "" {
eo.Algorithm = opt.Algorithm
}
if opt.QueryType != "" {
eo.QueryType = opt.QueryType
}
if opt.ContentionFactor != nil {
eo.ContentionFactor = opt.ContentionFactor
}
}
return eo
}

View File

@@ -0,0 +1,64 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "time"
// EstimatedDocumentCountOptions represents options that can be used to configure an EstimatedDocumentCount operation.
type EstimatedDocumentCountOptions struct {
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default is nil, which means that no comment will be included in the logs.
Comment interface{}
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
// is no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be used
// in its place to control the amount of time that a single operation can run before returning an error. MaxTime
// is ignored if Timeout is set on the client.
MaxTime *time.Duration
}
// EstimatedDocumentCount creates a new EstimatedDocumentCountOptions instance.
func EstimatedDocumentCount() *EstimatedDocumentCountOptions {
return &EstimatedDocumentCountOptions{}
}
// SetComment sets the value for the Comment field.
func (eco *EstimatedDocumentCountOptions) SetComment(comment interface{}) *EstimatedDocumentCountOptions {
eco.Comment = comment
return eco
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option
// may be used in its place to control the amount of time that a single operation can run before
// returning an error. MaxTime is ignored if Timeout is set on the client.
func (eco *EstimatedDocumentCountOptions) SetMaxTime(d time.Duration) *EstimatedDocumentCountOptions {
eco.MaxTime = &d
return eco
}
// MergeEstimatedDocumentCountOptions combines the given EstimatedDocumentCountOptions instances into a single
// EstimatedDocumentCountOptions in a last-one-wins fashion.
func MergeEstimatedDocumentCountOptions(opts ...*EstimatedDocumentCountOptions) *EstimatedDocumentCountOptions {
e := EstimatedDocumentCount()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Comment != nil {
e.Comment = opt.Comment
}
if opt.MaxTime != nil {
e.MaxTime = opt.MaxTime
}
}
return e
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,329 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
// DefaultName is the default name for a GridFS bucket.
var DefaultName = "fs"
// DefaultChunkSize is the default size of each file chunk in bytes (255 KiB).
var DefaultChunkSize int32 = 255 * 1024
// DefaultRevision is the default revision number for a download by name operation.
var DefaultRevision int32 = -1
// BucketOptions represents options that can be used to configure GridFS bucket.
type BucketOptions struct {
// The name of the bucket. The default value is "fs".
Name *string
// The number of bytes in each chunk in the bucket. The default value is 255 KiB.
ChunkSizeBytes *int32
// The write concern for the bucket. The default value is the write concern of the database from which the bucket
// is created.
WriteConcern *writeconcern.WriteConcern
// The read concern for the bucket. The default value is the read concern of the database from which the bucket
// is created.
ReadConcern *readconcern.ReadConcern
// The read preference for the bucket. The default value is the read preference of the database from which the
// bucket is created.
ReadPreference *readpref.ReadPref
}
// GridFSBucket creates a new BucketOptions instance.
func GridFSBucket() *BucketOptions {
return &BucketOptions{
Name: &DefaultName,
ChunkSizeBytes: &DefaultChunkSize,
}
}
// SetName sets the value for the Name field.
func (b *BucketOptions) SetName(name string) *BucketOptions {
b.Name = &name
return b
}
// SetChunkSizeBytes sets the value for the ChunkSize field.
func (b *BucketOptions) SetChunkSizeBytes(i int32) *BucketOptions {
b.ChunkSizeBytes = &i
return b
}
// SetWriteConcern sets the value for the WriteConcern field.
func (b *BucketOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *BucketOptions {
b.WriteConcern = wc
return b
}
// SetReadConcern sets the value for the ReadConcern field.
func (b *BucketOptions) SetReadConcern(rc *readconcern.ReadConcern) *BucketOptions {
b.ReadConcern = rc
return b
}
// SetReadPreference sets the value for the ReadPreference field.
func (b *BucketOptions) SetReadPreference(rp *readpref.ReadPref) *BucketOptions {
b.ReadPreference = rp
return b
}
// MergeBucketOptions combines the given BucketOptions instances into a single BucketOptions in a last-one-wins fashion.
func MergeBucketOptions(opts ...*BucketOptions) *BucketOptions {
b := GridFSBucket()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Name != nil {
b.Name = opt.Name
}
if opt.ChunkSizeBytes != nil {
b.ChunkSizeBytes = opt.ChunkSizeBytes
}
if opt.WriteConcern != nil {
b.WriteConcern = opt.WriteConcern
}
if opt.ReadConcern != nil {
b.ReadConcern = opt.ReadConcern
}
if opt.ReadPreference != nil {
b.ReadPreference = opt.ReadPreference
}
}
return b
}
// UploadOptions represents options that can be used to configure a GridFS upload operation.
type UploadOptions struct {
// The number of bytes in each chunk in the bucket. The default value is DefaultChunkSize (255 KiB).
ChunkSizeBytes *int32
// Additional application data that will be stored in the "metadata" field of the document in the files collection.
// The default value is nil, which means that the document in the files collection will not contain a "metadata"
// field.
Metadata interface{}
// The BSON registry to use for converting filters to BSON documents. The default value is bson.DefaultRegistry.
Registry *bsoncodec.Registry
}
// GridFSUpload creates a new UploadOptions instance.
func GridFSUpload() *UploadOptions {
return &UploadOptions{Registry: bson.DefaultRegistry}
}
// SetChunkSizeBytes sets the value for the ChunkSize field.
func (u *UploadOptions) SetChunkSizeBytes(i int32) *UploadOptions {
u.ChunkSizeBytes = &i
return u
}
// SetMetadata sets the value for the Metadata field.
func (u *UploadOptions) SetMetadata(doc interface{}) *UploadOptions {
u.Metadata = doc
return u
}
// MergeUploadOptions combines the given UploadOptions instances into a single UploadOptions in a last-one-wins fashion.
func MergeUploadOptions(opts ...*UploadOptions) *UploadOptions {
u := GridFSUpload()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.ChunkSizeBytes != nil {
u.ChunkSizeBytes = opt.ChunkSizeBytes
}
if opt.Metadata != nil {
u.Metadata = opt.Metadata
}
if opt.Registry != nil {
u.Registry = opt.Registry
}
}
return u
}
// NameOptions represents options that can be used to configure a GridFS DownloadByName operation.
type NameOptions struct {
// Specifies the revision of the file to retrieve. Revision numbers are defined as follows:
//
// * 0 = the original stored file
// * 1 = the first revision
// * 2 = the second revision
// * etc..
// * -2 = the second most recent revision
// * -1 = the most recent revision.
//
// The default value is -1
Revision *int32
}
// GridFSName creates a new NameOptions instance.
func GridFSName() *NameOptions {
return &NameOptions{}
}
// SetRevision sets the value for the Revision field.
func (n *NameOptions) SetRevision(r int32) *NameOptions {
n.Revision = &r
return n
}
// MergeNameOptions combines the given NameOptions instances into a single *NameOptions in a last-one-wins fashion.
func MergeNameOptions(opts ...*NameOptions) *NameOptions {
n := GridFSName()
n.Revision = &DefaultRevision
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Revision != nil {
n.Revision = opt.Revision
}
}
return n
}
// GridFSFindOptions represents options that can be used to configure a GridFS Find operation.
type GridFSFindOptions struct {
// If true, the server can write temporary data to disk while executing the find operation. The default value
// is false. This option is only valid for MongoDB versions >= 4.4. For previous server versions, the server will
// return an error if this option is used.
AllowDiskUse *bool
// The maximum number of documents to be included in each batch returned by the server.
BatchSize *int32
// The maximum number of documents to return. The default value is 0, which means that all documents matching the
// filter will be returned. A negative limit specifies that the resulting documents should be returned in a single
// batch. The default value is 0.
Limit *int32
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
// is no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be used
// in its place to control the amount of time that a single operation can run before returning an error. MaxTime
// is ignored if Timeout is set on the client.
MaxTime *time.Duration
// If true, the cursor created by the operation will not timeout after a period of inactivity. The default value
// is false.
NoCursorTimeout *bool
// The number of documents to skip before adding documents to the result. The default value is 0.
Skip *int32
// A document specifying the order in which documents should be returned. The driver will return an error if the
// sort parameter is a multi-key map.
Sort interface{}
}
// GridFSFind creates a new GridFSFindOptions instance.
func GridFSFind() *GridFSFindOptions {
return &GridFSFindOptions{}
}
// SetAllowDiskUse sets the value for the AllowDiskUse field.
func (f *GridFSFindOptions) SetAllowDiskUse(b bool) *GridFSFindOptions {
f.AllowDiskUse = &b
return f
}
// SetBatchSize sets the value for the BatchSize field.
func (f *GridFSFindOptions) SetBatchSize(i int32) *GridFSFindOptions {
f.BatchSize = &i
return f
}
// SetLimit sets the value for the Limit field.
func (f *GridFSFindOptions) SetLimit(i int32) *GridFSFindOptions {
f.Limit = &i
return f
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can
// run before returning an error. MaxTime is ignored if Timeout is set on the client.
func (f *GridFSFindOptions) SetMaxTime(d time.Duration) *GridFSFindOptions {
f.MaxTime = &d
return f
}
// SetNoCursorTimeout sets the value for the NoCursorTimeout field.
func (f *GridFSFindOptions) SetNoCursorTimeout(b bool) *GridFSFindOptions {
f.NoCursorTimeout = &b
return f
}
// SetSkip sets the value for the Skip field.
func (f *GridFSFindOptions) SetSkip(i int32) *GridFSFindOptions {
f.Skip = &i
return f
}
// SetSort sets the value for the Sort field.
func (f *GridFSFindOptions) SetSort(sort interface{}) *GridFSFindOptions {
f.Sort = sort
return f
}
// MergeGridFSFindOptions combines the given GridFSFindOptions instances into a single GridFSFindOptions in a
// last-one-wins fashion.
func MergeGridFSFindOptions(opts ...*GridFSFindOptions) *GridFSFindOptions {
fo := GridFSFind()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.AllowDiskUse != nil {
fo.AllowDiskUse = opt.AllowDiskUse
}
if opt.BatchSize != nil {
fo.BatchSize = opt.BatchSize
}
if opt.Limit != nil {
fo.Limit = opt.Limit
}
if opt.MaxTime != nil {
fo.MaxTime = opt.MaxTime
}
if opt.NoCursorTimeout != nil {
fo.NoCursorTimeout = opt.NoCursorTimeout
}
if opt.Skip != nil {
fo.Skip = opt.Skip
}
if opt.Sort != nil {
fo.Sort = opt.Sort
}
}
return fo
}

View File

@@ -0,0 +1,482 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
)
// CreateIndexesOptions represents options that can be used to configure IndexView.CreateOne and IndexView.CreateMany
// operations.
type CreateIndexesOptions struct {
// The number of data-bearing members of a replica set, including the primary, that must complete the index builds
// successfully before the primary marks the indexes as ready. This should either be a string or int32 value. The
// semantics of the values are as follows:
//
// 1. String: specifies a tag. All members with that tag must complete the build.
// 2. int: the number of members that must complete the build.
// 3. "majority": A special value to indicate that more than half the nodes must complete the build.
// 4. "votingMembers": A special value to indicate that all voting data-bearing nodes must complete.
//
// This option is only available on MongoDB versions >= 4.4. A client-side error will be returned if the option
// is specified for MongoDB versions <= 4.2. The default value is nil, meaning that the server-side default will be
// used. See dochub.mongodb.org/core/index-commit-quorum for more information.
CommitQuorum interface{}
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
// is no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be used
// in its place to control the amount of time that a single operation can run before returning an error. MaxTime
// is ignored if Timeout is set on the client.
MaxTime *time.Duration
}
// CreateIndexes creates a new CreateIndexesOptions instance.
func CreateIndexes() *CreateIndexesOptions {
return &CreateIndexesOptions{}
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can
// run before returning an error. MaxTime is ignored if Timeout is set on the client.
func (c *CreateIndexesOptions) SetMaxTime(d time.Duration) *CreateIndexesOptions {
c.MaxTime = &d
return c
}
// SetCommitQuorumInt sets the value for the CommitQuorum field as an int32.
func (c *CreateIndexesOptions) SetCommitQuorumInt(quorum int32) *CreateIndexesOptions {
c.CommitQuorum = quorum
return c
}
// SetCommitQuorumString sets the value for the CommitQuorum field as a string.
func (c *CreateIndexesOptions) SetCommitQuorumString(quorum string) *CreateIndexesOptions {
c.CommitQuorum = quorum
return c
}
// SetCommitQuorumMajority sets the value for the CommitQuorum to special "majority" value.
func (c *CreateIndexesOptions) SetCommitQuorumMajority() *CreateIndexesOptions {
c.CommitQuorum = "majority"
return c
}
// SetCommitQuorumVotingMembers sets the value for the CommitQuorum to special "votingMembers" value.
func (c *CreateIndexesOptions) SetCommitQuorumVotingMembers() *CreateIndexesOptions {
c.CommitQuorum = "votingMembers"
return c
}
// MergeCreateIndexesOptions combines the given CreateIndexesOptions into a single CreateIndexesOptions in a last one
// wins fashion.
func MergeCreateIndexesOptions(opts ...*CreateIndexesOptions) *CreateIndexesOptions {
c := CreateIndexes()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.MaxTime != nil {
c.MaxTime = opt.MaxTime
}
if opt.CommitQuorum != nil {
c.CommitQuorum = opt.CommitQuorum
}
}
return c
}
// DropIndexesOptions represents options that can be used to configure IndexView.DropOne and IndexView.DropAll
// operations.
type DropIndexesOptions struct {
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
// is no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be used
// in its place to control the amount of time that a single operation can run before returning an error. MaxTime
// is ignored if Timeout is set on the client.
MaxTime *time.Duration
}
// DropIndexes creates a new DropIndexesOptions instance.
func DropIndexes() *DropIndexesOptions {
return &DropIndexesOptions{}
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can
// run before returning an error. MaxTime is ignored if Timeout is set on the client.
func (d *DropIndexesOptions) SetMaxTime(duration time.Duration) *DropIndexesOptions {
d.MaxTime = &duration
return d
}
// MergeDropIndexesOptions combines the given DropIndexesOptions into a single DropIndexesOptions in a last-one-wins
// fashion.
func MergeDropIndexesOptions(opts ...*DropIndexesOptions) *DropIndexesOptions {
c := DropIndexes()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.MaxTime != nil {
c.MaxTime = opt.MaxTime
}
}
return c
}
// ListIndexesOptions represents options that can be used to configure an IndexView.List operation.
type ListIndexesOptions struct {
// The maximum number of documents to be included in each batch returned by the server.
BatchSize *int32
// The maximum amount of time that the query can run on the server. The default value is nil, meaning that there
// is no time limit for query execution.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout option may be used
// in its place to control the amount of time that a single operation can run before returning an error. MaxTime
// is ignored if Timeout is set on the client.
MaxTime *time.Duration
}
// ListIndexes creates a new ListIndexesOptions instance.
func ListIndexes() *ListIndexesOptions {
return &ListIndexesOptions{}
}
// SetBatchSize sets the value for the BatchSize field.
func (l *ListIndexesOptions) SetBatchSize(i int32) *ListIndexesOptions {
l.BatchSize = &i
return l
}
// SetMaxTime sets the value for the MaxTime field.
//
// NOTE(benjirewis): MaxTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can
// run before returning an error. MaxTime is ignored if Timeout is set on the client.
func (l *ListIndexesOptions) SetMaxTime(d time.Duration) *ListIndexesOptions {
l.MaxTime = &d
return l
}
// MergeListIndexesOptions combines the given ListIndexesOptions instances into a single *ListIndexesOptions in a
// last-one-wins fashion.
func MergeListIndexesOptions(opts ...*ListIndexesOptions) *ListIndexesOptions {
c := ListIndexes()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.BatchSize != nil {
c.BatchSize = opt.BatchSize
}
if opt.MaxTime != nil {
c.MaxTime = opt.MaxTime
}
}
return c
}
// IndexOptions represents options that can be used to configure a new index created through the IndexView.CreateOne
// or IndexView.CreateMany operations.
type IndexOptions struct {
// If true, the index will be built in the background on the server and will not block other tasks. The default
// value is false.
//
// Deprecated: This option has been deprecated in MongoDB version 4.2.
Background *bool
// The length of time, in seconds, for documents to remain in the collection. The default value is 0, which means
// that documents will remain in the collection until they're explicitly deleted or the collection is dropped.
ExpireAfterSeconds *int32
// The name of the index. The default value is "[field1]_[direction1]_[field2]_[direction2]...". For example, an
// index with the specification {name: 1, age: -1} will be named "name_1_age_-1".
Name *string
// If true, the index will only reference documents that contain the fields specified in the index. The default is
// false.
Sparse *bool
// Specifies the storage engine to use for the index. The value must be a document in the form
// {<storage engine name>: <options>}. The default value is nil, which means that the default storage engine
// will be used. This option is only applicable for MongoDB versions >= 3.0 and is ignored for previous server
// versions.
StorageEngine interface{}
// If true, the collection will not accept insertion or update of documents where the index key value matches an
// existing value in the index. The default is false.
Unique *bool
// The index version number, either 0 or 1.
Version *int32
// The language that determines the list of stop words and the rules for the stemmer and tokenizer. This option
// is only applicable for text indexes and is ignored for other index types. The default value is "english".
DefaultLanguage *string
// The name of the field in the collection's documents that contains the override language for the document. This
// option is only applicable for text indexes and is ignored for other index types. The default value is the value
// of the DefaultLanguage option.
LanguageOverride *string
// The index version number for a text index. See https://www.mongodb.com/docs/manual/core/index-text/#text-versions for
// information about different version numbers.
TextVersion *int32
// A document that contains field and weight pairs. The weight is an integer ranging from 1 to 99,999, inclusive,
// indicating the significance of the field relative to the other indexed fields in terms of the score. This option
// is only applicable for text indexes and is ignored for other index types. The default value is nil, which means
// that every field will have a weight of 1.
Weights interface{}
// The index version number for a 2D sphere index. See https://www.mongodb.com/docs/manual/core/2dsphere/#dsphere-v2 for
// information about different version numbers.
SphereVersion *int32
// The precision of the stored geohash value of the location data. This option only applies to 2D indexes and is
// ignored for other index types. The value must be between 1 and 32, inclusive. The default value is 26.
Bits *int32
// The upper inclusive boundary for longitude and latitude values. This option is only applicable to 2D indexes and
// is ignored for other index types. The default value is 180.0.
Max *float64
// The lower inclusive boundary for longitude and latitude values. This option is only applicable to 2D indexes and
// is ignored for other index types. The default value is -180.0.
Min *float64
// The number of units within which to group location values. Location values that are within BucketSize units of
// each other will be grouped in the same bucket. This option is only applicable to geoHaystack indexes and is
// ignored for other index types. The value must be greater than 0.
BucketSize *int32
// A document that defines which collection documents the index should reference. This option is only valid for
// MongoDB versions >= 3.2 and is ignored for previous server versions.
PartialFilterExpression interface{}
// The collation to use for string comparisons for the index. This option is only valid for MongoDB versions >= 3.4.
// For previous server versions, the driver will return an error if this option is used.
Collation *Collation
// A document that defines the wildcard projection for the index.
WildcardProjection interface{}
// If true, the index will exist on the target collection but will not be used by the query planner when executing
// operations. This option is only valid for MongoDB versions >= 4.4. The default value is false.
Hidden *bool
}
// Index creates a new IndexOptions instance.
func Index() *IndexOptions {
return &IndexOptions{}
}
// SetBackground sets value for the Background field.
//
// Deprecated: This option has been deprecated in MongoDB version 4.2.
func (i *IndexOptions) SetBackground(background bool) *IndexOptions {
i.Background = &background
return i
}
// SetExpireAfterSeconds sets value for the ExpireAfterSeconds field.
func (i *IndexOptions) SetExpireAfterSeconds(seconds int32) *IndexOptions {
i.ExpireAfterSeconds = &seconds
return i
}
// SetName sets the value for the Name field.
func (i *IndexOptions) SetName(name string) *IndexOptions {
i.Name = &name
return i
}
// SetSparse sets the value of the Sparse field.
func (i *IndexOptions) SetSparse(sparse bool) *IndexOptions {
i.Sparse = &sparse
return i
}
// SetStorageEngine sets the value for the StorageEngine field.
func (i *IndexOptions) SetStorageEngine(engine interface{}) *IndexOptions {
i.StorageEngine = engine
return i
}
// SetUnique sets the value for the Unique field.
func (i *IndexOptions) SetUnique(unique bool) *IndexOptions {
i.Unique = &unique
return i
}
// SetVersion sets the value for the Version field.
func (i *IndexOptions) SetVersion(version int32) *IndexOptions {
i.Version = &version
return i
}
// SetDefaultLanguage sets the value for the DefaultLanguage field.
func (i *IndexOptions) SetDefaultLanguage(language string) *IndexOptions {
i.DefaultLanguage = &language
return i
}
// SetLanguageOverride sets the value of the LanguageOverride field.
func (i *IndexOptions) SetLanguageOverride(override string) *IndexOptions {
i.LanguageOverride = &override
return i
}
// SetTextVersion sets the value for the TextVersion field.
func (i *IndexOptions) SetTextVersion(version int32) *IndexOptions {
i.TextVersion = &version
return i
}
// SetWeights sets the value for the Weights field.
func (i *IndexOptions) SetWeights(weights interface{}) *IndexOptions {
i.Weights = weights
return i
}
// SetSphereVersion sets the value for the SphereVersion field.
func (i *IndexOptions) SetSphereVersion(version int32) *IndexOptions {
i.SphereVersion = &version
return i
}
// SetBits sets the value for the Bits field.
func (i *IndexOptions) SetBits(bits int32) *IndexOptions {
i.Bits = &bits
return i
}
// SetMax sets the value for the Max field.
func (i *IndexOptions) SetMax(max float64) *IndexOptions {
i.Max = &max
return i
}
// SetMin sets the value for the Min field.
func (i *IndexOptions) SetMin(min float64) *IndexOptions {
i.Min = &min
return i
}
// SetBucketSize sets the value for the BucketSize field
func (i *IndexOptions) SetBucketSize(bucketSize int32) *IndexOptions {
i.BucketSize = &bucketSize
return i
}
// SetPartialFilterExpression sets the value for the PartialFilterExpression field.
func (i *IndexOptions) SetPartialFilterExpression(expression interface{}) *IndexOptions {
i.PartialFilterExpression = expression
return i
}
// SetCollation sets the value for the Collation field.
func (i *IndexOptions) SetCollation(collation *Collation) *IndexOptions {
i.Collation = collation
return i
}
// SetWildcardProjection sets the value for the WildcardProjection field.
func (i *IndexOptions) SetWildcardProjection(wildcardProjection interface{}) *IndexOptions {
i.WildcardProjection = wildcardProjection
return i
}
// SetHidden sets the value for the Hidden field.
func (i *IndexOptions) SetHidden(hidden bool) *IndexOptions {
i.Hidden = &hidden
return i
}
// MergeIndexOptions combines the given IndexOptions into a single IndexOptions in a last-one-wins fashion.
func MergeIndexOptions(opts ...*IndexOptions) *IndexOptions {
i := Index()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Background != nil {
i.Background = opt.Background
}
if opt.ExpireAfterSeconds != nil {
i.ExpireAfterSeconds = opt.ExpireAfterSeconds
}
if opt.Name != nil {
i.Name = opt.Name
}
if opt.Sparse != nil {
i.Sparse = opt.Sparse
}
if opt.StorageEngine != nil {
i.StorageEngine = opt.StorageEngine
}
if opt.Unique != nil {
i.Unique = opt.Unique
}
if opt.Version != nil {
i.Version = opt.Version
}
if opt.DefaultLanguage != nil {
i.DefaultLanguage = opt.DefaultLanguage
}
if opt.LanguageOverride != nil {
i.LanguageOverride = opt.LanguageOverride
}
if opt.TextVersion != nil {
i.TextVersion = opt.TextVersion
}
if opt.Weights != nil {
i.Weights = opt.Weights
}
if opt.SphereVersion != nil {
i.SphereVersion = opt.SphereVersion
}
if opt.Bits != nil {
i.Bits = opt.Bits
}
if opt.Max != nil {
i.Max = opt.Max
}
if opt.Min != nil {
i.Min = opt.Min
}
if opt.BucketSize != nil {
i.BucketSize = opt.BucketSize
}
if opt.PartialFilterExpression != nil {
i.PartialFilterExpression = opt.PartialFilterExpression
}
if opt.Collation != nil {
i.Collation = opt.Collation
}
if opt.WildcardProjection != nil {
i.WildcardProjection = opt.WildcardProjection
}
if opt.Hidden != nil {
i.Hidden = opt.Hidden
}
}
return i
}

View File

@@ -0,0 +1,119 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// InsertOneOptions represents options that can be used to configure an InsertOne operation.
type InsertOneOptions struct {
// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
// false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document
// validation.
BypassDocumentValidation *bool
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
Comment interface{}
}
// InsertOne creates a new InsertOneOptions instance.
func InsertOne() *InsertOneOptions {
return &InsertOneOptions{}
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
func (ioo *InsertOneOptions) SetBypassDocumentValidation(b bool) *InsertOneOptions {
ioo.BypassDocumentValidation = &b
return ioo
}
// SetComment sets the value for the Comment field.
func (ioo *InsertOneOptions) SetComment(comment interface{}) *InsertOneOptions {
ioo.Comment = comment
return ioo
}
// MergeInsertOneOptions combines the given InsertOneOptions instances into a single InsertOneOptions in a last-one-wins
// fashion.
func MergeInsertOneOptions(opts ...*InsertOneOptions) *InsertOneOptions {
ioOpts := InsertOne()
for _, ioo := range opts {
if ioo == nil {
continue
}
if ioo.BypassDocumentValidation != nil {
ioOpts.BypassDocumentValidation = ioo.BypassDocumentValidation
}
if ioo.Comment != nil {
ioOpts.Comment = ioo.Comment
}
}
return ioOpts
}
// InsertManyOptions represents options that can be used to configure an InsertMany operation.
type InsertManyOptions struct {
// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
// false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document
// validation.
BypassDocumentValidation *bool
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
Comment interface{}
// If true, no writes will be executed after one fails. The default value is true.
Ordered *bool
}
// InsertMany creates a new InsertManyOptions instance.
func InsertMany() *InsertManyOptions {
return &InsertManyOptions{
Ordered: &DefaultOrdered,
}
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
func (imo *InsertManyOptions) SetBypassDocumentValidation(b bool) *InsertManyOptions {
imo.BypassDocumentValidation = &b
return imo
}
// SetComment sets the value for the Comment field.
func (imo *InsertManyOptions) SetComment(comment interface{}) *InsertManyOptions {
imo.Comment = comment
return imo
}
// SetOrdered sets the value for the Ordered field.
func (imo *InsertManyOptions) SetOrdered(b bool) *InsertManyOptions {
imo.Ordered = &b
return imo
}
// MergeInsertManyOptions combines the given InsertManyOptions instances into a single InsertManyOptions in a last one
// wins fashion.
func MergeInsertManyOptions(opts ...*InsertManyOptions) *InsertManyOptions {
imOpts := InsertMany()
for _, imo := range opts {
if imo == nil {
continue
}
if imo.BypassDocumentValidation != nil {
imOpts.BypassDocumentValidation = imo.BypassDocumentValidation
}
if imo.Comment != nil {
imOpts.Comment = imo.Comment
}
if imo.Ordered != nil {
imOpts.Ordered = imo.Ordered
}
}
return imOpts
}

View File

@@ -0,0 +1,66 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// ListCollectionsOptions represents options that can be used to configure a ListCollections operation.
type ListCollectionsOptions struct {
// If true, each collection document will only contain a field for the collection name. The default value is false.
NameOnly *bool
// The maximum number of documents to be included in each batch returned by the server.
BatchSize *int32
// If true, and NameOnly is true, limits the documents returned to only contain collections the user is authorized to use. The default value
// is false. This option is only valid for MongoDB server versions >= 4.0. Server versions < 4.0 ignore this option.
AuthorizedCollections *bool
}
// ListCollections creates a new ListCollectionsOptions instance.
func ListCollections() *ListCollectionsOptions {
return &ListCollectionsOptions{}
}
// SetNameOnly sets the value for the NameOnly field.
func (lc *ListCollectionsOptions) SetNameOnly(b bool) *ListCollectionsOptions {
lc.NameOnly = &b
return lc
}
// SetBatchSize sets the value for the BatchSize field.
func (lc *ListCollectionsOptions) SetBatchSize(size int32) *ListCollectionsOptions {
lc.BatchSize = &size
return lc
}
// SetAuthorizedCollections sets the value for the AuthorizedCollections field. This option is only valid for MongoDB server versions >= 4.0. Server
// versions < 4.0 ignore this option.
func (lc *ListCollectionsOptions) SetAuthorizedCollections(b bool) *ListCollectionsOptions {
lc.AuthorizedCollections = &b
return lc
}
// MergeListCollectionsOptions combines the given ListCollectionsOptions instances into a single *ListCollectionsOptions
// in a last-one-wins fashion.
func MergeListCollectionsOptions(opts ...*ListCollectionsOptions) *ListCollectionsOptions {
lc := ListCollections()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.NameOnly != nil {
lc.NameOnly = opt.NameOnly
}
if opt.BatchSize != nil {
lc.BatchSize = opt.BatchSize
}
if opt.AuthorizedCollections != nil {
lc.AuthorizedCollections = opt.AuthorizedCollections
}
}
return lc
}

View File

@@ -0,0 +1,55 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// ListDatabasesOptions represents options that can be used to configure a ListDatabases operation.
type ListDatabasesOptions struct {
// If true, only the Name field of the returned DatabaseSpecification objects will be populated. The default value
// is false.
NameOnly *bool
// If true, only the databases which the user is authorized to see will be returned. For more information about
// the behavior of this option, see https://www.mongodb.com/docs/manual/reference/privilege-actions/#find. The default
// value is true.
AuthorizedDatabases *bool
}
// ListDatabases creates a new ListDatabasesOptions instance.
func ListDatabases() *ListDatabasesOptions {
return &ListDatabasesOptions{}
}
// SetNameOnly sets the value for the NameOnly field.
func (ld *ListDatabasesOptions) SetNameOnly(b bool) *ListDatabasesOptions {
ld.NameOnly = &b
return ld
}
// SetAuthorizedDatabases sets the value for the AuthorizedDatabases field.
func (ld *ListDatabasesOptions) SetAuthorizedDatabases(b bool) *ListDatabasesOptions {
ld.AuthorizedDatabases = &b
return ld
}
// MergeListDatabasesOptions combines the given ListDatabasesOptions instances into a single *ListDatabasesOptions in a
// last-one-wins fashion.
func MergeListDatabasesOptions(opts ...*ListDatabasesOptions) *ListDatabasesOptions {
ld := ListDatabases()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.NameOnly != nil {
ld.NameOnly = opt.NameOnly
}
if opt.AuthorizedDatabases != nil {
ld.AuthorizedDatabases = opt.AuthorizedDatabases
}
}
return ld
}

View File

@@ -0,0 +1,165 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"fmt"
"reflect"
"strconv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
// Collation allows users to specify language-specific rules for string comparison, such as
// rules for lettercase and accent marks.
type Collation struct {
Locale string `bson:",omitempty"` // The locale
CaseLevel bool `bson:",omitempty"` // The case level
CaseFirst string `bson:",omitempty"` // The case ordering
Strength int `bson:",omitempty"` // The number of comparison levels to use
NumericOrdering bool `bson:",omitempty"` // Whether to order numbers based on numerical order and not collation order
Alternate string `bson:",omitempty"` // Whether spaces and punctuation are considered base characters
MaxVariable string `bson:",omitempty"` // Which characters are affected by alternate: "shifted"
Normalization bool `bson:",omitempty"` // Causes text to be normalized into Unicode NFD
Backwards bool `bson:",omitempty"` // Causes secondary differences to be considered in reverse order, as it is done in the French language
}
// ToDocument converts the Collation to a bson.Raw.
func (co *Collation) ToDocument() bson.Raw {
idx, doc := bsoncore.AppendDocumentStart(nil)
if co.Locale != "" {
doc = bsoncore.AppendStringElement(doc, "locale", co.Locale)
}
if co.CaseLevel {
doc = bsoncore.AppendBooleanElement(doc, "caseLevel", true)
}
if co.CaseFirst != "" {
doc = bsoncore.AppendStringElement(doc, "caseFirst", co.CaseFirst)
}
if co.Strength != 0 {
doc = bsoncore.AppendInt32Element(doc, "strength", int32(co.Strength))
}
if co.NumericOrdering {
doc = bsoncore.AppendBooleanElement(doc, "numericOrdering", true)
}
if co.Alternate != "" {
doc = bsoncore.AppendStringElement(doc, "alternate", co.Alternate)
}
if co.MaxVariable != "" {
doc = bsoncore.AppendStringElement(doc, "maxVariable", co.MaxVariable)
}
if co.Normalization {
doc = bsoncore.AppendBooleanElement(doc, "normalization", true)
}
if co.Backwards {
doc = bsoncore.AppendBooleanElement(doc, "backwards", true)
}
doc, _ = bsoncore.AppendDocumentEnd(doc, idx)
return doc
}
// CursorType specifies whether a cursor should close when the last data is retrieved. See
// NonTailable, Tailable, and TailableAwait.
type CursorType int8
const (
// NonTailable specifies that a cursor should close after retrieving the last data.
NonTailable CursorType = iota
// Tailable specifies that a cursor should not close when the last data is retrieved and can be resumed later.
Tailable
// TailableAwait specifies that a cursor should not close when the last data is retrieved and
// that it should block for a certain amount of time for new data before returning no data.
TailableAwait
)
// ReturnDocument specifies whether a findAndUpdate operation should return the document as it was
// before the update or as it is after the update.
type ReturnDocument int8
const (
// Before specifies that findAndUpdate should return the document as it was before the update.
Before ReturnDocument = iota
// After specifies that findAndUpdate should return the document as it is after the update.
After
)
// FullDocument specifies how a change stream should return the modified document.
type FullDocument string
const (
// Default does not include a document copy.
Default FullDocument = "default"
// Off is the same as sending no value for fullDocumentBeforeChange.
Off FullDocument = "off"
// Required is the same as WhenAvailable but raises a server-side error if the post-image is not available.
Required FullDocument = "required"
// UpdateLookup includes a delta describing the changes to the document and a copy of the entire document that
// was changed.
UpdateLookup FullDocument = "updateLookup"
// WhenAvailable includes a post-image of the the modified document for replace and update change events
// if the post-image for this event is available.
WhenAvailable FullDocument = "whenAvailable"
)
// ArrayFilters is used to hold filters for the array filters CRUD option. If a registry is nil, bson.DefaultRegistry
// will be used when converting the filter interfaces to BSON.
type ArrayFilters struct {
Registry *bsoncodec.Registry // The registry to use for converting filters. Defaults to bson.DefaultRegistry.
Filters []interface{} // The filters to apply
}
// ToArray builds a []bson.Raw from the provided ArrayFilters.
func (af *ArrayFilters) ToArray() ([]bson.Raw, error) {
registry := af.Registry
if registry == nil {
registry = bson.DefaultRegistry
}
filters := make([]bson.Raw, 0, len(af.Filters))
for _, f := range af.Filters {
filter, err := bson.MarshalWithRegistry(registry, f)
if err != nil {
return nil, err
}
filters = append(filters, filter)
}
return filters, nil
}
// ToArrayDocument builds a BSON array for the array filters CRUD option. If the registry for af is nil,
// bson.DefaultRegistry will be used when converting the filter interfaces to BSON.
func (af *ArrayFilters) ToArrayDocument() (bson.Raw, error) {
registry := af.Registry
if registry == nil {
registry = bson.DefaultRegistry
}
idx, arr := bsoncore.AppendArrayStart(nil)
for i, f := range af.Filters {
filter, err := bson.MarshalWithRegistry(registry, f)
if err != nil {
return nil, err
}
arr = bsoncore.AppendDocumentElement(arr, strconv.Itoa(i), filter)
}
arr, _ = bsoncore.AppendArrayEnd(arr, idx)
return arr, nil
}
// MarshalError is returned when attempting to transform a value into a document
// results in an error.
type MarshalError struct {
Value interface{}
Err error
}
// Error implements the error interface.
func (me MarshalError) Error() string {
return fmt.Sprintf("cannot transform type %s to a bson.Raw", reflect.TypeOf(me.Value))
}

View File

@@ -0,0 +1,115 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// ReplaceOptions represents options that can be used to configure a ReplaceOne operation.
type ReplaceOptions struct {
// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
// false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document
// validation.
BypassDocumentValidation *bool
// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the default collation of the collection will be used.
Collation *Collation
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
Comment interface{}
// The index to use for the operation. This should either be the index name as a string or the index specification
// as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error
// if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option
// is specified. The driver will return an error if this option is specified during an unacknowledged write
// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
// which means that no hint will be sent.
Hint interface{}
// If true, a new document will be inserted if the filter does not match any documents in the collection. The
// default value is false.
Upsert *bool
// Specifies parameters for the aggregate expression. This option is only valid for MongoDB versions >= 5.0. Older
// servers will report an error for using this option. This must be a document mapping parameter names to values.
// Values must be constant or closed expressions that do not reference document fields. Parameters can then be
// accessed as variables in an aggregate expression context (e.g. "$$var").
Let interface{}
}
// Replace creates a new ReplaceOptions instance.
func Replace() *ReplaceOptions {
return &ReplaceOptions{}
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
func (ro *ReplaceOptions) SetBypassDocumentValidation(b bool) *ReplaceOptions {
ro.BypassDocumentValidation = &b
return ro
}
// SetCollation sets the value for the Collation field.
func (ro *ReplaceOptions) SetCollation(c *Collation) *ReplaceOptions {
ro.Collation = c
return ro
}
// SetComment sets the value for the Comment field.
func (ro *ReplaceOptions) SetComment(comment interface{}) *ReplaceOptions {
ro.Comment = comment
return ro
}
// SetHint sets the value for the Hint field.
func (ro *ReplaceOptions) SetHint(h interface{}) *ReplaceOptions {
ro.Hint = h
return ro
}
// SetUpsert sets the value for the Upsert field.
func (ro *ReplaceOptions) SetUpsert(b bool) *ReplaceOptions {
ro.Upsert = &b
return ro
}
// SetLet sets the value for the Let field.
func (ro *ReplaceOptions) SetLet(l interface{}) *ReplaceOptions {
ro.Let = l
return ro
}
// MergeReplaceOptions combines the given ReplaceOptions instances into a single ReplaceOptions in a last-one-wins
// fashion.
func MergeReplaceOptions(opts ...*ReplaceOptions) *ReplaceOptions {
rOpts := Replace()
for _, ro := range opts {
if ro == nil {
continue
}
if ro.BypassDocumentValidation != nil {
rOpts.BypassDocumentValidation = ro.BypassDocumentValidation
}
if ro.Collation != nil {
rOpts.Collation = ro.Collation
}
if ro.Comment != nil {
rOpts.Comment = ro.Comment
}
if ro.Hint != nil {
rOpts.Hint = ro.Hint
}
if ro.Upsert != nil {
rOpts.Upsert = ro.Upsert
}
if ro.Let != nil {
rOpts.Let = ro.Let
}
}
return rOpts
}

View File

@@ -0,0 +1,52 @@
// Copyright (C) MongoDB, Inc. 2022-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// RewrapManyDataKeyOptions represents all possible options used to decrypt and encrypt all matching data keys with a
// possibly new masterKey.
type RewrapManyDataKeyOptions struct {
// Provider identifies the new KMS provider. If omitted, encrypting uses the current KMS provider.
Provider *string
// MasterKey identifies the new masterKey. If omitted, rewraps with the current masterKey.
MasterKey interface{}
}
// RewrapManyDataKey creates a new RewrapManyDataKeyOptions instance.
func RewrapManyDataKey() *RewrapManyDataKeyOptions {
return new(RewrapManyDataKeyOptions)
}
// SetProvider sets the value for the Provider field.
func (rmdko *RewrapManyDataKeyOptions) SetProvider(provider string) *RewrapManyDataKeyOptions {
rmdko.Provider = &provider
return rmdko
}
// SetMasterKey sets the value for the MasterKey field.
func (rmdko *RewrapManyDataKeyOptions) SetMasterKey(masterKey interface{}) *RewrapManyDataKeyOptions {
rmdko.MasterKey = masterKey
return rmdko
}
// MergeRewrapManyDataKeyOptions combines the given RewrapManyDataKeyOptions instances into a single
// RewrapManyDataKeyOptions in a last one wins fashion.
func MergeRewrapManyDataKeyOptions(opts ...*RewrapManyDataKeyOptions) *RewrapManyDataKeyOptions {
rmdkOpts := RewrapManyDataKey()
for _, rmdko := range opts {
if rmdko == nil {
continue
}
if provider := rmdko.Provider; provider != nil {
rmdkOpts.Provider = provider
}
if masterKey := rmdko.MasterKey; masterKey != nil {
rmdkOpts.MasterKey = masterKey
}
}
return rmdkOpts
}

View File

@@ -0,0 +1,42 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import "go.mongodb.org/mongo-driver/mongo/readpref"
// RunCmdOptions represents options that can be used to configure a RunCommand operation.
type RunCmdOptions struct {
// The read preference to use for the operation. The default value is nil, which means that the primary read
// preference will be used.
ReadPreference *readpref.ReadPref
}
// RunCmd creates a new RunCmdOptions instance.
func RunCmd() *RunCmdOptions {
return &RunCmdOptions{}
}
// SetReadPreference sets value for the ReadPreference field.
func (rc *RunCmdOptions) SetReadPreference(rp *readpref.ReadPref) *RunCmdOptions {
rc.ReadPreference = rp
return rc
}
// MergeRunCmdOptions combines the given RunCmdOptions instances into one *RunCmdOptions in a last-one-wins fashion.
func MergeRunCmdOptions(opts ...*RunCmdOptions) *RunCmdOptions {
rc := RunCmd()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.ReadPreference != nil {
rc.ReadPreference = opt.ReadPreference
}
}
return rc
}

View File

@@ -0,0 +1,60 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"fmt"
)
// ServerAPIOptions represents options used to configure the API version sent to the server
// when running commands.
//
// Sending a specified server API version causes the server to behave in a manner compatible with that
// API version. It also causes the driver to behave in a manner compatible with the drivers behavior as
// of the release when the driver first started to support the specified server API version.
//
// The user must specify a ServerAPIVersion if including ServerAPIOptions in their client. That version
// must also be currently supported by the driver. This version of the driver supports API version "1".
type ServerAPIOptions struct {
ServerAPIVersion ServerAPIVersion
Strict *bool
DeprecationErrors *bool
}
// ServerAPI creates a new ServerAPIOptions configured with the provided serverAPIversion.
func ServerAPI(serverAPIVersion ServerAPIVersion) *ServerAPIOptions {
return &ServerAPIOptions{ServerAPIVersion: serverAPIVersion}
}
// SetStrict specifies whether the server should return errors for features that are not part of the API version.
func (s *ServerAPIOptions) SetStrict(strict bool) *ServerAPIOptions {
s.Strict = &strict
return s
}
// SetDeprecationErrors specifies whether the server should return errors for deprecated features.
func (s *ServerAPIOptions) SetDeprecationErrors(deprecationErrors bool) *ServerAPIOptions {
s.DeprecationErrors = &deprecationErrors
return s
}
// ServerAPIVersion represents an API version that can be used in ServerAPIOptions.
type ServerAPIVersion string
const (
// ServerAPIVersion1 is the first API version.
ServerAPIVersion1 ServerAPIVersion = "1"
)
// Validate determines if the provided ServerAPIVersion is currently supported by the driver.
func (sav ServerAPIVersion) Validate() error {
switch sav {
case ServerAPIVersion1:
return nil
}
return fmt.Errorf("api version %q not supported; this driver version only supports API version \"1\"", sav)
}

View File

@@ -0,0 +1,131 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
// DefaultCausalConsistency is the default value for the CausalConsistency option.
var DefaultCausalConsistency = true
// SessionOptions represents options that can be used to configure a Session.
type SessionOptions struct {
// If true, causal consistency will be enabled for the session. This option cannot be set to true if Snapshot is
// set to true. The default value is true unless Snapshot is set to true. See
// https://www.mongodb.com/docs/manual/core/read-isolation-consistency-recency/#sessions for more information.
CausalConsistency *bool
// The default read concern for transactions started in the session. The default value is nil, which means that
// the read concern of the client used to start the session will be used.
DefaultReadConcern *readconcern.ReadConcern
// The default read preference for transactions started in the session. The default value is nil, which means that
// the read preference of the client used to start the session will be used.
DefaultReadPreference *readpref.ReadPref
// The default write concern for transactions started in the session. The default value is nil, which means that
// the write concern of the client used to start the session will be used.
DefaultWriteConcern *writeconcern.WriteConcern
// The default maximum amount of time that a CommitTransaction operation executed in the session can run on the
// server. The default value is nil, which means that that there is no time limit for execution.
//
// NOTE(benjirewis): DefaultMaxCommitTime will be deprecated in a future release. The more general Timeout option
// may be used in its place to control the amount of time that a single operation can run before returning an
// error. DefaultMaxCommitTime is ignored if Timeout is set on the client.
DefaultMaxCommitTime *time.Duration
// If true, all read operations performed with this session will be read from the same snapshot. This option cannot
// be set to true if CausalConsistency is set to true. Transactions and write operations are not allowed on
// snapshot sessions and will error. The default value is false.
Snapshot *bool
}
// Session creates a new SessionOptions instance.
func Session() *SessionOptions {
return &SessionOptions{}
}
// SetCausalConsistency sets the value for the CausalConsistency field.
func (s *SessionOptions) SetCausalConsistency(b bool) *SessionOptions {
s.CausalConsistency = &b
return s
}
// SetDefaultReadConcern sets the value for the DefaultReadConcern field.
func (s *SessionOptions) SetDefaultReadConcern(rc *readconcern.ReadConcern) *SessionOptions {
s.DefaultReadConcern = rc
return s
}
// SetDefaultReadPreference sets the value for the DefaultReadPreference field.
func (s *SessionOptions) SetDefaultReadPreference(rp *readpref.ReadPref) *SessionOptions {
s.DefaultReadPreference = rp
return s
}
// SetDefaultWriteConcern sets the value for the DefaultWriteConcern field.
func (s *SessionOptions) SetDefaultWriteConcern(wc *writeconcern.WriteConcern) *SessionOptions {
s.DefaultWriteConcern = wc
return s
}
// SetDefaultMaxCommitTime sets the value for the DefaultMaxCommitTime field.
//
// NOTE(benjirewis): DefaultMaxCommitTime will be deprecated in a future release. The more
// general Timeout option may be used in its place to control the amount of time that a
// single operation can run before returning an error. DefaultMaxCommitTime is ignored if
// Timeout is set on the client.
func (s *SessionOptions) SetDefaultMaxCommitTime(mct *time.Duration) *SessionOptions {
s.DefaultMaxCommitTime = mct
return s
}
// SetSnapshot sets the value for the Snapshot field.
func (s *SessionOptions) SetSnapshot(b bool) *SessionOptions {
s.Snapshot = &b
return s
}
// MergeSessionOptions combines the given SessionOptions instances into a single SessionOptions in a last-one-wins
// fashion.
func MergeSessionOptions(opts ...*SessionOptions) *SessionOptions {
s := Session()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.CausalConsistency != nil {
s.CausalConsistency = opt.CausalConsistency
}
if opt.DefaultReadConcern != nil {
s.DefaultReadConcern = opt.DefaultReadConcern
}
if opt.DefaultReadPreference != nil {
s.DefaultReadPreference = opt.DefaultReadPreference
}
if opt.DefaultWriteConcern != nil {
s.DefaultWriteConcern = opt.DefaultWriteConcern
}
if opt.DefaultMaxCommitTime != nil {
s.DefaultMaxCommitTime = opt.DefaultMaxCommitTime
}
if opt.Snapshot != nil {
s.Snapshot = opt.Snapshot
}
}
if s.CausalConsistency == nil && (s.Snapshot == nil || !*s.Snapshot) {
s.CausalConsistency = &DefaultCausalConsistency
}
return s
}

View File

@@ -0,0 +1,100 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
import (
"time"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
// TransactionOptions represents options that can be used to configure a transaction.
type TransactionOptions struct {
// The read concern for operations in the transaction. The default value is nil, which means that the default
// read concern of the session used to start the transaction will be used.
ReadConcern *readconcern.ReadConcern
// The read preference for operations in the transaction. The default value is nil, which means that the default
// read preference of the session used to start the transaction will be used.
ReadPreference *readpref.ReadPref
// The write concern for operations in the transaction. The default value is nil, which means that the default
// write concern of the session used to start the transaction will be used.
WriteConcern *writeconcern.WriteConcern
// The default maximum amount of time that a CommitTransaction operation executed in the session can run on the
// server. The default value is nil, meaning that there is no time limit for execution.
// The maximum amount of time that a CommitTransaction operation can executed in the transaction can run on the
// server. The default value is nil, which means that the default maximum commit time of the session used to
// start the transaction will be used.
//
// NOTE(benjirewis): MaxCommitTime will be deprecated in a future release. The more general Timeout option may
// be used in its place to control the amount of time that a single operation can run before returning an error.
// MaxCommitTime is ignored if Timeout is set on the client.
MaxCommitTime *time.Duration
}
// Transaction creates a new TransactionOptions instance.
func Transaction() *TransactionOptions {
return &TransactionOptions{}
}
// SetReadConcern sets the value for the ReadConcern field.
func (t *TransactionOptions) SetReadConcern(rc *readconcern.ReadConcern) *TransactionOptions {
t.ReadConcern = rc
return t
}
// SetReadPreference sets the value for the ReadPreference field.
func (t *TransactionOptions) SetReadPreference(rp *readpref.ReadPref) *TransactionOptions {
t.ReadPreference = rp
return t
}
// SetWriteConcern sets the value for the WriteConcern field.
func (t *TransactionOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *TransactionOptions {
t.WriteConcern = wc
return t
}
// SetMaxCommitTime sets the value for the MaxCommitTime field.
//
// NOTE(benjirewis): MaxCommitTime will be deprecated in a future release. The more general Timeout
// option may be used in its place to control the amount of time that a single operation can run before
// returning an error. MaxCommitTime is ignored if Timeout is set on the client.
func (t *TransactionOptions) SetMaxCommitTime(mct *time.Duration) *TransactionOptions {
t.MaxCommitTime = mct
return t
}
// MergeTransactionOptions combines the given TransactionOptions instances into a single TransactionOptions in a
// last-one-wins fashion.
func MergeTransactionOptions(opts ...*TransactionOptions) *TransactionOptions {
t := Transaction()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.ReadConcern != nil {
t.ReadConcern = opt.ReadConcern
}
if opt.ReadPreference != nil {
t.ReadPreference = opt.ReadPreference
}
if opt.WriteConcern != nil {
t.WriteConcern = opt.WriteConcern
}
if opt.MaxCommitTime != nil {
t.MaxCommitTime = opt.MaxCommitTime
}
}
return t
}

View File

@@ -0,0 +1,128 @@
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package options
// UpdateOptions represents options that can be used to configure UpdateOne and UpdateMany operations.
type UpdateOptions struct {
// A set of filters specifying to which array elements an update should apply. This option is only valid for MongoDB
// versions >= 3.6. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the update will apply to all array elements.
ArrayFilters *ArrayFilters
// If true, writes executed as part of the operation will opt out of document-level validation on the server. This
// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is
// false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document
// validation.
BypassDocumentValidation *bool
// Specifies a collation to use for string comparisons during the operation. This option is only valid for MongoDB
// versions >= 3.4. For previous server versions, the driver will return an error if this option is used. The
// default value is nil, which means the default collation of the collection will be used.
Collation *Collation
// A string or document that will be included in server logs, profiling logs, and currentOp queries to help trace
// the operation. The default value is nil, which means that no comment will be included in the logs.
Comment interface{}
// The index to use for the operation. This should either be the index name as a string or the index specification
// as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error
// if this option is specified. For server versions < 3.4, the driver will return a client-side error if this option
// is specified. The driver will return an error if this option is specified during an unacknowledged write
// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil,
// which means that no hint will be sent.
Hint interface{}
// If true, a new document will be inserted if the filter does not match any documents in the collection. The
// default value is false.
Upsert *bool
// Specifies parameters for the update expression. This option is only valid for MongoDB versions >= 5.0. Older
// servers will report an error for using this option. This must be a document mapping parameter names to values.
// Values must be constant or closed expressions that do not reference document fields. Parameters can then be
// accessed as variables in an aggregate expression context (e.g. "$$var").
Let interface{}
}
// Update creates a new UpdateOptions instance.
func Update() *UpdateOptions {
return &UpdateOptions{}
}
// SetArrayFilters sets the value for the ArrayFilters field.
func (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions {
uo.ArrayFilters = &af
return uo
}
// SetBypassDocumentValidation sets the value for the BypassDocumentValidation field.
func (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions {
uo.BypassDocumentValidation = &b
return uo
}
// SetCollation sets the value for the Collation field.
func (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions {
uo.Collation = c
return uo
}
// SetComment sets the value for the Comment field.
func (uo *UpdateOptions) SetComment(comment interface{}) *UpdateOptions {
uo.Comment = comment
return uo
}
// SetHint sets the value for the Hint field.
func (uo *UpdateOptions) SetHint(h interface{}) *UpdateOptions {
uo.Hint = h
return uo
}
// SetUpsert sets the value for the Upsert field.
func (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {
uo.Upsert = &b
return uo
}
// SetLet sets the value for the Let field.
func (uo *UpdateOptions) SetLet(l interface{}) *UpdateOptions {
uo.Let = l
return uo
}
// MergeUpdateOptions combines the given UpdateOptions instances into a single UpdateOptions in a last-one-wins fashion.
func MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {
uOpts := Update()
for _, uo := range opts {
if uo == nil {
continue
}
if uo.ArrayFilters != nil {
uOpts.ArrayFilters = uo.ArrayFilters
}
if uo.BypassDocumentValidation != nil {
uOpts.BypassDocumentValidation = uo.BypassDocumentValidation
}
if uo.Collation != nil {
uOpts.Collation = uo.Collation
}
if uo.Comment != nil {
uOpts.Comment = uo.Comment
}
if uo.Hint != nil {
uOpts.Hint = uo.Hint
}
if uo.Upsert != nil {
uOpts.Upsert = uo.Upsert
}
if uo.Let != nil {
uOpts.Let = uo.Let
}
}
return uOpts
}