newline battles continue

This commit is contained in:
bel
2020-01-19 20:41:30 +00:00
parent 98adb53caf
commit 573696774e
1456 changed files with 501133 additions and 6 deletions

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"
// AggregateOptions represents all possible options to the Aggregate() function.
type AggregateOptions struct {
AllowDiskUse *bool // Enables writing to temporary files. When set to true, aggregation stages can write data to the _tmp subdirectory in the dbPath directory
BatchSize *int32 // The number of documents to return per batch
BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation. This only applies when the $out stage is specified
Collation *Collation // Specifies a collation
MaxTime *time.Duration // The maximum amount of time to allow the query to run
MaxAwaitTime *time.Duration // The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query
Comment *string // Enables users to specify an arbitrary string to help trace the operation through the database profiler, currentOp and logs.
Hint interface{} // The index to use for the aggregation. The hint does not apply to $lookup and $graphLookup stages
}
// Aggregate returns a pointer to a new AggregateOptions
func Aggregate() *AggregateOptions {
return &AggregateOptions{}
}
// SetAllowDiskUse enables writing to temporary files. When set to true,
// aggregation stages can write data to the _tmp subdirectory in the
// dbPath directory
func (ao *AggregateOptions) SetAllowDiskUse(b bool) *AggregateOptions {
ao.AllowDiskUse = &b
return ao
}
// SetBatchSize specifies the number of documents to return per batch
func (ao *AggregateOptions) SetBatchSize(i int32) *AggregateOptions {
ao.BatchSize = &i
return ao
}
// SetBypassDocumentValidation allows the write to opt-out of document level
// validation. This only applies when the $out stage is specified
// Valid for server versions >= 3.2. For servers < 3.2, this option is ignored.
func (ao *AggregateOptions) SetBypassDocumentValidation(b bool) *AggregateOptions {
ao.BypassDocumentValidation = &b
return ao
}
// SetCollation specifies a collation.
// Valid for server versions >= 3.4
func (ao *AggregateOptions) SetCollation(c *Collation) *AggregateOptions {
ao.Collation = c
return ao
}
// SetMaxTime specifies the maximum amount of time to allow the query to run
func (ao *AggregateOptions) SetMaxTime(d time.Duration) *AggregateOptions {
ao.MaxTime = &d
return ao
}
// SetMaxAwaitTime specifies the maximum amount of time for the server to
// wait on new documents to satisfy a tailable cursor query
// For servers < 3.2, this option is ignored
func (ao *AggregateOptions) SetMaxAwaitTime(d time.Duration) *AggregateOptions {
ao.MaxAwaitTime = &d
return ao
}
// SetComment enables users to specify an arbitrary string to help trace the
// operation through the database profiler, currentOp and logs.
func (ao *AggregateOptions) SetComment(s string) *AggregateOptions {
ao.Comment = &s
return ao
}
// SetHint specifies the index to use for the aggregation. The hint does not
// apply to $lookup and $graphLookup stages
func (ao *AggregateOptions) SetHint(h interface{}) *AggregateOptions {
ao.Hint = h
return ao
}
// MergeAggregateOptions combines the argued AggregateOptions 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
}
}
return aggOpts
}

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
// DefaultOrdered is the default order for a BulkWriteOptions struct created from BulkWrite.
var DefaultOrdered = true
// BulkWriteOptions represent all possible options for a bulkWrite operation.
type BulkWriteOptions struct {
BypassDocumentValidation *bool // If true, allows the write to opt out of document-level validation.
Ordered *bool // If true, when a write fails, return without performing remaining writes. Defaults to true.
}
// BulkWrite creates a new *BulkWriteOptions
func BulkWrite() *BulkWriteOptions {
return &BulkWriteOptions{
Ordered: &DefaultOrdered,
}
}
// SetOrdered configures the ordered option. If true, when a write fails, the function will return without attempting
// remaining writes. Defaults to true.
func (b *BulkWriteOptions) SetOrdered(ordered bool) *BulkWriteOptions {
b.Ordered = &ordered
return b
}
// SetBypassDocumentValidation specifies if the write should opt out of document-level validation.
// Valid for server versions >= 3.2. For servers < 3.2, this option is ignored.
func (b *BulkWriteOptions) SetBypassDocumentValidation(bypass bool) *BulkWriteOptions {
b.BypassDocumentValidation = &bypass
return b
}
// MergeBulkWriteOptions combines the given *BulkWriteOptions 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.Ordered != nil {
b.Ordered = opt.Ordered
}
if opt.BypassDocumentValidation != nil {
b.BypassDocumentValidation = opt.BypassDocumentValidation
}
}
return b
}

View File

@@ -0,0 +1,110 @@
// 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"
"time"
)
// ChangeStreamOptions represents all possible options to a change stream
type ChangeStreamOptions struct {
BatchSize *int32 // The number of documents to return per batch
Collation *Collation // Specifies a collation
FullDocument *FullDocument // When set to updateLookup, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
MaxAwaitTime *time.Duration // The maximum amount of time for the server to wait on new documents to satisfy a change stream query
ResumeAfter interface{} // Specifies the logical starting point for the new change stream
StartAtOperationTime *primitive.Timestamp // Ensures that a change stream will only provide changes that occurred after a timestamp.
StartAfter interface{} // Specifies a resume token. The started change stream will return the first notification after the token.
}
// ChangeStream returns a pointer to a new ChangeStreamOptions
func ChangeStream() *ChangeStreamOptions {
cso := &ChangeStreamOptions{}
cso.SetFullDocument(Default)
return cso
}
// SetBatchSize specifies the number of documents to return per batch
func (cso *ChangeStreamOptions) SetBatchSize(i int32) *ChangeStreamOptions {
cso.BatchSize = &i
return cso
}
// SetCollation specifies a collation
func (cso *ChangeStreamOptions) SetCollation(c Collation) *ChangeStreamOptions {
cso.Collation = &c
return cso
}
// SetFullDocument specifies the fullDocument option.
// When set to updateLookup, the change notification for partial updates will
// include both a delta describing the changes to the document, as well as a
// copy of the entire document that was changed from some time after the change
// occurred.
func (cso *ChangeStreamOptions) SetFullDocument(fd FullDocument) *ChangeStreamOptions {
cso.FullDocument = &fd
return cso
}
// SetMaxAwaitTime specifies the maximum amount of time for the server to wait on new documents to satisfy a change stream query
func (cso *ChangeStreamOptions) SetMaxAwaitTime(d time.Duration) *ChangeStreamOptions {
cso.MaxAwaitTime = &d
return cso
}
// SetResumeAfter specifies the logical starting point for the new change stream
func (cso *ChangeStreamOptions) SetResumeAfter(rt interface{}) *ChangeStreamOptions {
cso.ResumeAfter = rt
return cso
}
// SetStartAtOperationTime ensures that a change stream will only provide changes that occurred after a specified timestamp.
func (cso *ChangeStreamOptions) SetStartAtOperationTime(t *primitive.Timestamp) *ChangeStreamOptions {
cso.StartAtOperationTime = t
return cso
}
// SetStartAfter specifies a resume token. The resulting change stream will return the first notification after the token.
// Cannot be used in conjunction with ResumeAfter.
func (cso *ChangeStreamOptions) SetStartAfter(sa interface{}) *ChangeStreamOptions {
cso.StartAfter = sa
return cso
}
// MergeChangeStreamOptions combines the argued ChangeStreamOptions 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.FullDocument != nil {
csOpts.FullDocument = cso.FullDocument
}
if cso.MaxAwaitTime != nil {
csOpts.MaxAwaitTime = cso.MaxAwaitTime
}
if cso.ResumeAfter != nil {
csOpts.ResumeAfter = cso.ResumeAfter
}
if cso.StartAtOperationTime != nil {
csOpts.StartAtOperationTime = cso.StartAtOperationTime
}
if cso.StartAfter != nil {
csOpts.StartAfter = cso.StartAfter
}
}
return csOpts
}

View File

@@ -0,0 +1,633 @@
// 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/options"
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"net"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/tag"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
)
// ContextDialer makes new network connections
type ContextDialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
// Credential holds auth options.
//
// AuthMechanism indicates the mechanism to use for authentication.
// Supported values include "SCRAM-SHA-256", "SCRAM-SHA-1", "MONGODB-CR", "PLAIN", "GSSAPI", and "MONGODB-X509".
//
// AuthMechanismProperties specifies additional configuration options which may be used by certain
// authentication mechanisms. Supported properties are:
// SERVICE_NAME: Specifies the name of the service. Defaults to mongodb.
// CANONICALIZE_HOST_NAME: If true, tells the driver to canonicalize the given hostname. Defaults to false. This
// property may not be used on Linux and Darwin systems and may not be used at the same time as SERVICE_HOST.
// SERVICE_REALM: Specifies the realm of the service.
// SERVICE_HOST: Specifies a hostname for GSSAPI authentication if it is different from the server's address. For
// authentication mechanisms besides GSSAPI, this property is ignored.
//
// AuthSource specifies the database to authenticate against.
//
// Username specifies the username that will be authenticated.
//
// Password specifies the password used for authentication.
//
// PasswordSet specifies if the password is actually set, since an empty password is a valid password.
type Credential struct {
AuthMechanism string
AuthMechanismProperties map[string]string
AuthSource string
Username string
Password string
PasswordSet bool
}
// ClientOptions represents all possible options to configure a client.
type ClientOptions struct {
AppName *string
Auth *Credential
ConnectTimeout *time.Duration
Compressors []string
Dialer ContextDialer
HeartbeatInterval *time.Duration
Hosts []string
LocalThreshold *time.Duration
MaxConnIdleTime *time.Duration
MaxPoolSize *uint16
Monitor *event.CommandMonitor
ReadConcern *readconcern.ReadConcern
ReadPreference *readpref.ReadPref
Registry *bsoncodec.Registry
ReplicaSet *string
RetryWrites *bool
ServerSelectionTimeout *time.Duration
Direct *bool
SocketTimeout *time.Duration
TLSConfig *tls.Config
WriteConcern *writeconcern.WriteConcern
ZlibLevel *int
err error
// Adds an option for internal use only and should not be set. This option is deprecated and is
// not part of the stability guarantee. It may be removed in the future.
AuthenticateToAnything *bool
}
// Client creates a new ClientOptions instance.
func Client() *ClientOptions {
return new(ClientOptions)
}
// Validate validates the client options. This method will return the first error found.
func (c *ClientOptions) Validate() error { return c.err }
// ApplyURI parses the provided connection string and sets the values and options accordingly.
//
// Errors that occur in this method can be retrieved by calling Validate.
//
// If the URI contains ssl=true this method will overwrite TLSConfig, even if there aren't any other
// tls options specified.
func (c *ClientOptions) ApplyURI(uri string) *ClientOptions {
if c.err != nil {
return c
}
cs, err := connstring.Parse(uri)
if err != nil {
c.err = err
return c
}
if cs.AppName != "" {
c.AppName = &cs.AppName
}
if cs.AuthMechanism != "" || cs.AuthMechanismProperties != nil || cs.AuthSource != "" ||
cs.Username != "" || cs.PasswordSet {
c.Auth = &Credential{
AuthMechanism: cs.AuthMechanism,
AuthMechanismProperties: cs.AuthMechanismProperties,
AuthSource: cs.AuthSource,
Username: cs.Username,
Password: cs.Password,
PasswordSet: cs.PasswordSet,
}
}
if cs.ConnectSet {
direct := cs.Connect == connstring.SingleConnect
c.Direct = &direct
}
if cs.ConnectTimeoutSet {
c.ConnectTimeout = &cs.ConnectTimeout
}
if len(cs.Compressors) > 0 {
c.Compressors = cs.Compressors
}
if cs.HeartbeatIntervalSet {
c.HeartbeatInterval = &cs.HeartbeatInterval
}
c.Hosts = cs.Hosts
if cs.LocalThresholdSet {
c.LocalThreshold = &cs.LocalThreshold
}
if cs.MaxConnIdleTimeSet {
c.MaxConnIdleTime = &cs.MaxConnIdleTime
}
if cs.MaxPoolSizeSet {
c.MaxPoolSize = &cs.MaxPoolSize
}
if cs.ReadConcernLevel != "" {
c.ReadConcern = readconcern.New(readconcern.Level(cs.ReadConcernLevel))
}
if cs.ReadPreference != "" || len(cs.ReadPreferenceTagSets) > 0 || cs.MaxStalenessSet {
opts := make([]readpref.Option, 0, 1)
tagSets := tag.NewTagSetsFromMaps(cs.ReadPreferenceTagSets)
if len(tagSets) > 0 {
opts = append(opts, readpref.WithTagSets(tagSets...))
}
if cs.MaxStaleness != 0 {
opts = append(opts, readpref.WithMaxStaleness(cs.MaxStaleness))
}
mode, err := readpref.ModeFromString(cs.ReadPreference)
if err != nil {
c.err = err
return c
}
c.ReadPreference, c.err = readpref.New(mode, opts...)
if c.err != nil {
return c
}
}
if cs.RetryWritesSet {
c.RetryWrites = &cs.RetryWrites
}
if cs.ReplicaSet != "" {
c.ReplicaSet = &cs.ReplicaSet
}
if cs.ServerSelectionTimeoutSet {
c.ServerSelectionTimeout = &cs.ServerSelectionTimeout
}
if cs.SocketTimeoutSet {
c.SocketTimeout = &cs.SocketTimeout
}
if cs.SSL {
tlsConfig := new(tls.Config)
if cs.SSLCaFileSet {
c.err = addCACertFromFile(tlsConfig, cs.SSLCaFile)
if c.err != nil {
return c
}
}
if cs.SSLInsecure {
tlsConfig.InsecureSkipVerify = true
}
if cs.SSLClientCertificateKeyFileSet {
var keyPasswd string
if cs.SSLClientCertificateKeyPasswordSet && cs.SSLClientCertificateKeyPassword != nil {
keyPasswd = cs.SSLClientCertificateKeyPassword()
}
s, err := addClientCertFromFile(tlsConfig, cs.SSLClientCertificateKeyFile, keyPasswd)
if err != nil {
c.err = err
return c
}
// If a username wasn't specified, add one from the certificate.
if c.Auth != nil && strings.ToLower(c.Auth.AuthMechanism) == "mongodb-x509" && c.Auth.Username == "" {
// The Go x509 package gives the subject with the pairs in reverse order that we want.
pairs := strings.Split(s, ",")
for left, right := 0, len(pairs)-1; left < right; left, right = left+1, right-1 {
pairs[left], pairs[right] = pairs[right], pairs[left]
}
c.Auth.Username = strings.Join(pairs, ",")
}
}
c.TLSConfig = tlsConfig
}
if cs.JSet || cs.WString != "" || cs.WNumberSet || cs.WTimeoutSet {
opts := make([]writeconcern.Option, 0, 1)
if len(cs.WString) > 0 {
opts = append(opts, writeconcern.WTagSet(cs.WString))
} else if cs.WNumberSet {
opts = append(opts, writeconcern.W(cs.WNumber))
}
if cs.JSet {
opts = append(opts, writeconcern.J(cs.J))
}
if cs.WTimeoutSet {
opts = append(opts, writeconcern.WTimeout(cs.WTimeout))
}
c.WriteConcern = writeconcern.New(opts...)
}
if cs.ZlibLevelSet {
c.ZlibLevel = &cs.ZlibLevel
}
return c
}
// SetAppName specifies the client application name. This value is used by MongoDB when it logs
// connection information and profile information, such as slow queries.
func (c *ClientOptions) SetAppName(s string) *ClientOptions {
c.AppName = &s
return c
}
// SetAuth sets the authentication options.
func (c *ClientOptions) SetAuth(auth Credential) *ClientOptions {
c.Auth = &auth
return c
}
// SetCompressors sets the compressors that can be used when communicating with a server.
func (c *ClientOptions) SetCompressors(comps []string) *ClientOptions {
c.Compressors = comps
return c
}
// SetConnectTimeout specifies the timeout for an initial connection to a server.
// If a custom Dialer is used, this method won't be set and the user is
// responsible for setting the ConnectTimeout for connections on the dialer
// themselves.
func (c *ClientOptions) SetConnectTimeout(d time.Duration) *ClientOptions {
c.ConnectTimeout = &d
return c
}
// SetDialer specifies a custom dialer used to dial new connections to a server.
// If a custom dialer is not set, a net.Dialer with a 300 second keepalive time will be used by default.
func (c *ClientOptions) SetDialer(d ContextDialer) *ClientOptions {
c.Dialer = d
return c
}
// SetDirect specifies whether the driver should connect directly to the server instead of
// auto-discovering other servers in the cluster.
func (c *ClientOptions) SetDirect(b bool) *ClientOptions {
c.Direct = &b
return c
}
// SetHeartbeatInterval specifies the interval to wait between server monitoring checks.
func (c *ClientOptions) SetHeartbeatInterval(d time.Duration) *ClientOptions {
c.HeartbeatInterval = &d
return c
}
// SetHosts specifies the initial list of addresses from which to discover the rest of the cluster.
func (c *ClientOptions) SetHosts(s []string) *ClientOptions {
c.Hosts = s
return c
}
// SetLocalThreshold specifies how far to distribute queries, beyond the server with the fastest
// round-trip time. If a server's roundtrip time is more than LocalThreshold slower than the
// the fastest, the driver will not send queries to that server.
func (c *ClientOptions) SetLocalThreshold(d time.Duration) *ClientOptions {
c.LocalThreshold = &d
return c
}
// SetMaxConnIdleTime specifies the maximum number of milliseconds that a connection can remain idle
// in a connection pool before being removed and closed.
func (c *ClientOptions) SetMaxConnIdleTime(d time.Duration) *ClientOptions {
c.MaxConnIdleTime = &d
return c
}
// SetMaxPoolSize specifies the max size of a server's connection pool.
func (c *ClientOptions) SetMaxPoolSize(u uint16) *ClientOptions {
c.MaxPoolSize = &u
return c
}
// SetMonitor specifies a command monitor used to see commands for a client.
func (c *ClientOptions) SetMonitor(m *event.CommandMonitor) *ClientOptions {
c.Monitor = m
return c
}
// SetReadConcern specifies the read concern.
func (c *ClientOptions) SetReadConcern(rc *readconcern.ReadConcern) *ClientOptions {
c.ReadConcern = rc
return c
}
// SetReadPreference specifies the read preference.
func (c *ClientOptions) SetReadPreference(rp *readpref.ReadPref) *ClientOptions {
c.ReadPreference = rp
return c
}
// SetRegistry specifies the bsoncodec.Registry.
func (c *ClientOptions) SetRegistry(registry *bsoncodec.Registry) *ClientOptions {
c.Registry = registry
return c
}
// SetReplicaSet specifies the name of the replica set of the cluster.
func (c *ClientOptions) SetReplicaSet(s string) *ClientOptions {
c.ReplicaSet = &s
return c
}
// SetRetryWrites specifies whether the client has retryable writes enabled.
func (c *ClientOptions) SetRetryWrites(b bool) *ClientOptions {
c.RetryWrites = &b
return c
}
// SetServerSelectionTimeout specifies a timeout in milliseconds to block for server selection.
func (c *ClientOptions) SetServerSelectionTimeout(d time.Duration) *ClientOptions {
c.ServerSelectionTimeout = &d
return c
}
// SetSocketTimeout specifies the time in milliseconds to attempt to send or receive on a socket
// before the attempt times out.
func (c *ClientOptions) SetSocketTimeout(d time.Duration) *ClientOptions {
c.SocketTimeout = &d
return c
}
// SetTLSConfig sets the tls.Config.
func (c *ClientOptions) SetTLSConfig(cfg *tls.Config) *ClientOptions {
c.TLSConfig = cfg
return c
}
// SetWriteConcern sets the write concern.
func (c *ClientOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *ClientOptions {
c.WriteConcern = wc
return c
}
// SetZlibLevel sets the level for the zlib compressor.
func (c *ClientOptions) SetZlibLevel(level int) *ClientOptions {
c.ZlibLevel = &level
return c
}
// MergeClientOptions combines the given connstring and *ClientOptions into a single *ClientOptions in a last one wins
// fashion. The given connstring will be used for the default options, which can be overwritten using the given
// *ClientOptions.
func MergeClientOptions(opts ...*ClientOptions) *ClientOptions {
c := Client()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Dialer != nil {
c.Dialer = opt.Dialer
}
if opt.AppName != nil {
c.AppName = opt.AppName
}
if opt.Auth != nil {
c.Auth = opt.Auth
}
if opt.AuthenticateToAnything != nil {
c.AuthenticateToAnything = opt.AuthenticateToAnything
}
if opt.Compressors != nil {
c.Compressors = opt.Compressors
}
if opt.ConnectTimeout != nil {
c.ConnectTimeout = opt.ConnectTimeout
}
if opt.HeartbeatInterval != nil {
c.HeartbeatInterval = opt.HeartbeatInterval
}
if len(opt.Hosts) > 0 {
c.Hosts = opt.Hosts
}
if opt.LocalThreshold != nil {
c.LocalThreshold = opt.LocalThreshold
}
if opt.MaxConnIdleTime != nil {
c.MaxConnIdleTime = opt.MaxConnIdleTime
}
if opt.MaxPoolSize != nil {
c.MaxPoolSize = opt.MaxPoolSize
}
if opt.Monitor != nil {
c.Monitor = opt.Monitor
}
if opt.ReadConcern != nil {
c.ReadConcern = opt.ReadConcern
}
if opt.ReadPreference != nil {
c.ReadPreference = opt.ReadPreference
}
if opt.Registry != nil {
c.Registry = opt.Registry
}
if opt.ReplicaSet != nil {
c.ReplicaSet = opt.ReplicaSet
}
if opt.RetryWrites != nil {
c.RetryWrites = opt.RetryWrites
}
if opt.ServerSelectionTimeout != nil {
c.ServerSelectionTimeout = opt.ServerSelectionTimeout
}
if opt.Direct != nil {
c.Direct = opt.Direct
}
if opt.SocketTimeout != nil {
c.SocketTimeout = opt.SocketTimeout
}
if opt.TLSConfig != nil {
c.TLSConfig = opt.TLSConfig
}
if opt.WriteConcern != nil {
c.WriteConcern = opt.WriteConcern
}
if opt.ZlibLevel != nil {
c.ZlibLevel = opt.ZlibLevel
}
if opt.err != nil {
c.err = opt.err
}
}
return c
}
// addCACertFromFile adds a root CA certificate to the configuration given a path
// to the containing file.
func addCACertFromFile(cfg *tls.Config, file string) error {
data, err := ioutil.ReadFile(file)
if err != nil {
return err
}
certBytes, err := loadCert(data)
if err != nil {
return err
}
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return err
}
if cfg.RootCAs == nil {
cfg.RootCAs = x509.NewCertPool()
}
cfg.RootCAs.AddCert(cert)
return nil
}
func loadCert(data []byte) ([]byte, error) {
var certBlock *pem.Block
for certBlock == nil {
if data == nil || len(data) == 0 {
return nil, errors.New(".pem file must have both a CERTIFICATE and an RSA PRIVATE KEY section")
}
block, rest := pem.Decode(data)
if block == nil {
return nil, errors.New("invalid .pem file")
}
switch block.Type {
case "CERTIFICATE":
if certBlock != nil {
return nil, errors.New("multiple CERTIFICATE sections in .pem file")
}
certBlock = block
}
data = rest
}
return certBlock.Bytes, nil
}
// addClientCertFromFile adds a client certificate to the configuration given a path to the
// containing file and returns the certificate's subject name.
func addClientCertFromFile(cfg *tls.Config, clientFile, keyPasswd string) (string, error) {
data, err := ioutil.ReadFile(clientFile)
if err != nil {
return "", err
}
var currentBlock *pem.Block
var certBlock, certDecodedBlock, keyBlock []byte
remaining := data
start := 0
for {
currentBlock, remaining = pem.Decode(remaining)
if currentBlock == nil {
break
}
if currentBlock.Type == "CERTIFICATE" {
certBlock = data[start : len(data)-len(remaining)]
certDecodedBlock = currentBlock.Bytes
start += len(certBlock)
} else if strings.HasSuffix(currentBlock.Type, "PRIVATE KEY") {
if keyPasswd != "" && x509.IsEncryptedPEMBlock(currentBlock) {
var encoded bytes.Buffer
buf, err := x509.DecryptPEMBlock(currentBlock, []byte(keyPasswd))
if err != nil {
return "", err
}
pem.Encode(&encoded, &pem.Block{Type: currentBlock.Type, Bytes: buf})
keyBlock = encoded.Bytes()
start = len(data) - len(remaining)
} else {
keyBlock = data[start : len(data)-len(remaining)]
start += len(keyBlock)
}
}
}
if len(certBlock) == 0 {
return "", fmt.Errorf("failed to find CERTIFICATE")
}
if len(keyBlock) == 0 {
return "", fmt.Errorf("failed to find PRIVATE KEY")
}
cert, err := tls.X509KeyPair(certBlock, keyBlock)
if err != nil {
return "", err
}
cfg.Certificates = append(cfg.Certificates, cert)
// The documentation for the tls.X509KeyPair indicates that the Leaf certificate is not
// retained.
crt, err := x509.ParseCertificate(certDecodedBlock)
if err != nil {
return "", err
}
return x509CertSubject(crt), nil
}

View File

@@ -0,0 +1,9 @@
// +build go1.10
package options
import "crypto/x509"
func x509CertSubject(cert *x509.Certificate) string {
return cert.Subject.String()
}

View File

@@ -0,0 +1,13 @@
// +build !go1.10
package options
import (
"crypto/x509"
)
// We don't support version less then 1.10, but Evergreen needs to be able to compile the driver
// using version 1.8.
func x509CertSubject(cert *x509.Certificate) string {
return ""
}

View File

@@ -0,0 +1,77 @@
// 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 represent all possible options to configure a Collection.
type CollectionOptions struct {
ReadConcern *readconcern.ReadConcern // The read concern for operations in the collection.
WriteConcern *writeconcern.WriteConcern // The write concern for operations in the collection.
ReadPreference *readpref.ReadPref // The read preference for operations in the collection.
Registry *bsoncodec.Registry // The registry to be used to construct BSON encoders and decoders for the collection.
}
// Collection creates a new CollectionOptions instance
func Collection() *CollectionOptions {
return &CollectionOptions{}
}
// SetReadConcern sets the read concern for the collection.
func (c *CollectionOptions) SetReadConcern(rc *readconcern.ReadConcern) *CollectionOptions {
c.ReadConcern = rc
return c
}
// SetWriteConcern sets the write concern for the collection.
func (c *CollectionOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *CollectionOptions {
c.WriteConcern = wc
return c
}
// SetReadPreference sets the read preference for the collection.
func (c *CollectionOptions) SetReadPreference(rp *readpref.ReadPref) *CollectionOptions {
c.ReadPreference = rp
return c
}
// SetRegistry sets the bsoncodec Registry for the collection.
func (c *CollectionOptions) SetRegistry(r *bsoncodec.Registry) *CollectionOptions {
c.Registry = r
return c
}
// MergeCollectionOptions combines the *CollectionOptions arguments 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,81 @@
// 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 all possible options to the Count() function.
type CountOptions struct {
Collation *Collation // Specifies a collation
Hint interface{} // The index to use
Limit *int64 // The maximum number of documents to count
MaxTime *time.Duration // The maximum amount of time to allow the operation to run
Skip *int64 // The number of documents to skip before counting
}
// Count returns a pointer to a new CountOptions
func Count() *CountOptions {
return &CountOptions{}
}
// SetCollation specifies a collation
// Valid for server versions >= 3.4
func (co *CountOptions) SetCollation(c *Collation) *CountOptions {
co.Collation = c
return co
}
// SetHint specifies the index to use
func (co *CountOptions) SetHint(h interface{}) *CountOptions {
co.Hint = h
return co
}
// SetLimit specifies the maximum number of documents to count
func (co *CountOptions) SetLimit(i int64) *CountOptions {
co.Limit = &i
return co
}
// SetMaxTime specifies the maximum amount of time to allow the operation to run
func (co *CountOptions) SetMaxTime(d time.Duration) *CountOptions {
co.MaxTime = &d
return co
}
// SetSkip specifies the number of documents to skip before counting
func (co *CountOptions) SetSkip(i int64) *CountOptions {
co.Skip = &i
return co
}
// MergeCountOptions combines the argued CountOptions 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.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,77 @@
// 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 represent all possible options to configure a Database.
type DatabaseOptions struct {
ReadConcern *readconcern.ReadConcern // The read concern for operations in the database.
WriteConcern *writeconcern.WriteConcern // The write concern for operations in the database.
ReadPreference *readpref.ReadPref // The read preference for operations in the database.
Registry *bsoncodec.Registry // The registry to be used to construct BSON encoders and decoders for the database.
}
// Database creates a new DatabaseOptions instance
func Database() *DatabaseOptions {
return &DatabaseOptions{}
}
// SetReadConcern sets the read concern for the database.
func (d *DatabaseOptions) SetReadConcern(rc *readconcern.ReadConcern) *DatabaseOptions {
d.ReadConcern = rc
return d
}
// SetWriteConcern sets the write concern for the database.
func (d *DatabaseOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *DatabaseOptions {
d.WriteConcern = wc
return d
}
// SetReadPreference sets the read preference for the database.
func (d *DatabaseOptions) SetReadPreference(rp *readpref.ReadPref) *DatabaseOptions {
d.ReadPreference = rp
return d
}
// SetRegistry sets the bsoncodec Registry for the database.
func (d *DatabaseOptions) SetRegistry(r *bsoncodec.Registry) *DatabaseOptions {
d.Registry = r
return d
}
// MergeDatabaseOptions combines the *DatabaseOptions arguments 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,39 @@
// 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 all possible options to the DeleteOne() and DeleteMany() functions.
type DeleteOptions struct {
Collation *Collation // Specifies a collation
}
// Delete returns a pointer to a new DeleteOptions
func Delete() *DeleteOptions {
return &DeleteOptions{}
}
// SetCollation specifies a collation
// Valid for servers >= 3.4.
func (do *DeleteOptions) SetCollation(c *Collation) *DeleteOptions {
do.Collation = c
return do
}
// MergeDeleteOptions combines the argued DeleteOptions 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
}
}
return dOpts
}

View File

@@ -0,0 +1,51 @@
// 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 all possible options to the Distinct() function.
type DistinctOptions struct {
Collation *Collation // Specifies a collation
MaxTime *time.Duration // The maximum amount of time to allow the operation to run
}
// Distinct returns a pointer to a new DistinctOptions
func Distinct() *DistinctOptions {
return &DistinctOptions{}
}
// SetCollation specifies a collation
// Valid for server versions >= 3.4
func (do *DistinctOptions) SetCollation(c *Collation) *DistinctOptions {
do.Collation = c
return do
}
// SetMaxTime specifies the maximum amount of time to allow the operation to run
func (do *DistinctOptions) SetMaxTime(d time.Duration) *DistinctOptions {
do.MaxTime = &d
return do
}
// MergeDistinctOptions combines the argued DistinctOptions 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.MaxTime != nil {
distinctOpts.MaxTime = do.MaxTime
}
}
return distinctOpts
}

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 "time"
// EstimatedDocumentCountOptions represents all possible options to the EstimatedDocumentCount() function.
type EstimatedDocumentCountOptions struct {
MaxTime *time.Duration // The maximum amount of time to allow the operation to run
}
// EstimatedDocumentCount returns a pointer to a new EstimatedDocumentCountOptions
func EstimatedDocumentCount() *EstimatedDocumentCountOptions {
return &EstimatedDocumentCountOptions{}
}
// SetMaxTime specifies the maximum amount of time to allow the operation to run
func (eco *EstimatedDocumentCountOptions) SetMaxTime(d time.Duration) *EstimatedDocumentCountOptions {
eco.MaxTime = &d
return eco
}
// MergeEstimatedDocumentCountOptions combines the given *EstimatedDocumentCountOptions 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.MaxTime != nil {
e.MaxTime = opt.MaxTime
}
}
return e
}

View File

@@ -0,0 +1,693 @@
// 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"
)
// FindOptions represent all possible options to the Find() function.
type FindOptions struct {
AllowPartialResults *bool // If true, allows partial results to be returned if some shards are down.
BatchSize *int32 // Specifies the number of documents to return in every batch.
Collation *Collation // Specifies a collation to be used
Comment *string // Specifies a string to help trace the operation through the database.
CursorType *CursorType // Specifies the type of cursor to use
Hint interface{} // Specifies the index to use.
Limit *int64 // Sets a limit on the number of results to return.
Max interface{} // Sets an exclusive upper bound for a specific index
MaxAwaitTime *time.Duration // Specifies the maximum amount of time for the server to wait on new documents.
MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run.
Min interface{} // Specifies the inclusive lower bound for a specific index.
NoCursorTimeout *bool // If true, prevents cursors from timing out after an inactivity period.
OplogReplay *bool // Adds an option for internal use only and should not be set.
Projection interface{} // Limits the fields returned for all documents.
ReturnKey *bool // If true, only returns index keys for all result documents.
ShowRecordID *bool // If true, a $recordId field with the record identifier will be added to the returned documents.
Skip *int64 // Specifies the number of documents to skip before returning
Snapshot *bool // If true, prevents the cursor from returning a document more than once because of an intervening write operation.
Sort interface{} // Specifies the order in which to return results.
}
// Find creates a new FindOptions instance.
func Find() *FindOptions {
return &FindOptions{}
}
// SetAllowPartialResults sets whether partial results can be returned if some shards are down.
// For server versions < 3.2, this defaults to false.
func (f *FindOptions) SetAllowPartialResults(b bool) *FindOptions {
f.AllowPartialResults = &b
return f
}
// SetBatchSize sets the number of documents to return in each batch.
func (f *FindOptions) SetBatchSize(i int32) *FindOptions {
f.BatchSize = &i
return f
}
// SetCollation specifies a Collation to use for the Find operation.
// Valid for server versions >= 3.4
func (f *FindOptions) SetCollation(collation *Collation) *FindOptions {
f.Collation = collation
return f
}
// SetComment specifies a string to help trace the operation through the database.
func (f *FindOptions) SetComment(comment string) *FindOptions {
f.Comment = &comment
return f
}
// SetCursorType specifes the type of cursor to use.
func (f *FindOptions) SetCursorType(ct CursorType) *FindOptions {
f.CursorType = &ct
return f
}
// SetHint specifies the index to use.
func (f *FindOptions) SetHint(hint interface{}) *FindOptions {
f.Hint = hint
return f
}
// SetLimit specifies a limit on the number of results.
// A negative limit implies that only 1 batch should be returned.
func (f *FindOptions) SetLimit(i int64) *FindOptions {
f.Limit = &i
return f
}
// SetMax specifies an exclusive upper bound for a specific index.
func (f *FindOptions) SetMax(max interface{}) *FindOptions {
f.Max = max
return f
}
// SetMaxAwaitTime specifies the max amount of time for the server to wait on new documents.
// If the cursor type is not TailableAwait, this option is ignored.
// For server versions < 3.2, this option is ignored.
func (f *FindOptions) SetMaxAwaitTime(d time.Duration) *FindOptions {
f.MaxAwaitTime = &d
return f
}
// SetMaxTime specifies the max time to allow the query to run.
func (f *FindOptions) SetMaxTime(d time.Duration) *FindOptions {
f.MaxTime = &d
return f
}
// SetMin specifies the inclusive lower bound for a specific index.
func (f *FindOptions) SetMin(min interface{}) *FindOptions {
f.Min = min
return f
}
// SetNoCursorTimeout specifies whether or not cursors should time out after a period of inactivity.
// For server versions < 3.2, this defaults to false.
func (f *FindOptions) SetNoCursorTimeout(b bool) *FindOptions {
f.NoCursorTimeout = &b
return f
}
// SetOplogReplay adds an option for internal use only and should not be set.
// For server versions < 3.2, this defaults to false.
func (f *FindOptions) SetOplogReplay(b bool) *FindOptions {
f.OplogReplay = &b
return f
}
// SetProjection adds an option to limit the fields returned for all documents.
func (f *FindOptions) SetProjection(projection interface{}) *FindOptions {
f.Projection = projection
return f
}
// SetReturnKey adds an option to only return index keys for all result documents.
func (f *FindOptions) SetReturnKey(b bool) *FindOptions {
f.ReturnKey = &b
return f
}
// SetShowRecordID adds an option to determine whether to return the record identifier for each document.
// If true, a $recordId field will be added to each returned document.
func (f *FindOptions) SetShowRecordID(b bool) *FindOptions {
f.ShowRecordID = &b
return f
}
// SetSkip specifies the number of documents to skip before returning.
// For server versions < 3.2, this defaults to 0.
func (f *FindOptions) SetSkip(i int64) *FindOptions {
f.Skip = &i
return f
}
// SetSnapshot prevents the cursor from returning a document more than once because of an intervening write operation.
func (f *FindOptions) SetSnapshot(b bool) *FindOptions {
f.Snapshot = &b
return f
}
// SetSort specifies the order in which to return documents.
func (f *FindOptions) SetSort(sort interface{}) *FindOptions {
f.Sort = sort
return f
}
// MergeFindOptions combines the argued FindOptions into a single FindOptions in a last-one-wins fashion
func MergeFindOptions(opts ...*FindOptions) *FindOptions {
fo := Find()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.AllowPartialResults != nil {
fo.AllowPartialResults = opt.AllowPartialResults
}
if opt.BatchSize != nil {
fo.BatchSize = opt.BatchSize
}
if opt.Collation != nil {
fo.Collation = opt.Collation
}
if opt.Comment != nil {
fo.Comment = opt.Comment
}
if opt.CursorType != nil {
fo.CursorType = opt.CursorType
}
if opt.Hint != nil {
fo.Hint = opt.Hint
}
if opt.Limit != nil {
fo.Limit = opt.Limit
}
if opt.Max != nil {
fo.Max = opt.Max
}
if opt.MaxAwaitTime != nil {
fo.MaxAwaitTime = opt.MaxAwaitTime
}
if opt.MaxTime != nil {
fo.MaxTime = opt.MaxTime
}
if opt.Min != nil {
fo.Min = opt.Min
}
if opt.NoCursorTimeout != nil {
fo.NoCursorTimeout = opt.NoCursorTimeout
}
if opt.OplogReplay != nil {
fo.OplogReplay = opt.OplogReplay
}
if opt.Projection != nil {
fo.Projection = opt.Projection
}
if opt.ReturnKey != nil {
fo.ReturnKey = opt.ReturnKey
}
if opt.ShowRecordID != nil {
fo.ShowRecordID = opt.ShowRecordID
}
if opt.Skip != nil {
fo.Skip = opt.Skip
}
if opt.Snapshot != nil {
fo.Snapshot = opt.Snapshot
}
if opt.Sort != nil {
fo.Sort = opt.Sort
}
}
return fo
}
// FindOneOptions represent all possible options to the FindOne() function.
type FindOneOptions struct {
AllowPartialResults *bool // If true, allows partial results to be returned if some shards are down.
BatchSize *int32 // Specifies the number of documents to return in every batch.
Collation *Collation // Specifies a collation to be used
Comment *string // Specifies a string to help trace the operation through the database.
CursorType *CursorType // Specifies the type of cursor to use
Hint interface{} // Specifies the index to use.
Max interface{} // Sets an exclusive upper bound for a specific index
MaxAwaitTime *time.Duration // Specifies the maximum amount of time for the server to wait on new documents.
MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run.
Min interface{} // Specifies the inclusive lower bound for a specific index.
NoCursorTimeout *bool // If true, prevents cursors from timing out after an inactivity period.
OplogReplay *bool // Adds an option for internal use only and should not be set.
Projection interface{} // Limits the fields returned for all documents.
ReturnKey *bool // If true, only returns index keys for all result documents.
ShowRecordID *bool // If true, a $recordId field with the record identifier will be added to the returned documents.
Skip *int64 // Specifies the number of documents to skip before returning
Snapshot *bool // If true, prevents the cursor from returning a document more than once because of an intervening write operation.
Sort interface{} // Specifies the order in which to return results.
}
// FindOne creates a new FindOneOptions instance.
func FindOne() *FindOneOptions {
return &FindOneOptions{}
}
// SetAllowPartialResults sets whether partial results can be returned if some shards are down.
func (f *FindOneOptions) SetAllowPartialResults(b bool) *FindOneOptions {
f.AllowPartialResults = &b
return f
}
// SetBatchSize sets the number of documents to return in each batch.
func (f *FindOneOptions) SetBatchSize(i int32) *FindOneOptions {
f.BatchSize = &i
return f
}
// SetCollation specifies a Collation to use for the Find operation.
func (f *FindOneOptions) SetCollation(collation *Collation) *FindOneOptions {
f.Collation = collation
return f
}
// SetComment specifies a string to help trace the operation through the database.
func (f *FindOneOptions) SetComment(comment string) *FindOneOptions {
f.Comment = &comment
return f
}
// SetCursorType specifes the type of cursor to use.
func (f *FindOneOptions) SetCursorType(ct CursorType) *FindOneOptions {
f.CursorType = &ct
return f
}
// SetHint specifies the index to use.
func (f *FindOneOptions) SetHint(hint interface{}) *FindOneOptions {
f.Hint = hint
return f
}
// SetMax specifies an exclusive upper bound for a specific index.
func (f *FindOneOptions) SetMax(max interface{}) *FindOneOptions {
f.Max = max
return f
}
// SetMaxAwaitTime specifies the max amount of time for the server to wait on new documents.
// For server versions < 3.2, this option is ignored.
func (f *FindOneOptions) SetMaxAwaitTime(d time.Duration) *FindOneOptions {
f.MaxAwaitTime = &d
return f
}
// SetMaxTime specifies the max time to allow the query to run.
func (f *FindOneOptions) SetMaxTime(d time.Duration) *FindOneOptions {
f.MaxTime = &d
return f
}
// SetMin specifies the inclusive lower bound for a specific index.
func (f *FindOneOptions) SetMin(min interface{}) *FindOneOptions {
f.Min = min
return f
}
// SetNoCursorTimeout specifies whether or not cursors should time out after a period of inactivity.
func (f *FindOneOptions) SetNoCursorTimeout(b bool) *FindOneOptions {
f.NoCursorTimeout = &b
return f
}
// SetOplogReplay adds an option for internal use only and should not be set.
func (f *FindOneOptions) SetOplogReplay(b bool) *FindOneOptions {
f.OplogReplay = &b
return f
}
// SetProjection adds an option to limit the fields returned for all documents.
func (f *FindOneOptions) SetProjection(projection interface{}) *FindOneOptions {
f.Projection = projection
return f
}
// SetReturnKey adds an option to only return index keys for all result documents.
func (f *FindOneOptions) SetReturnKey(b bool) *FindOneOptions {
f.ReturnKey = &b
return f
}
// SetShowRecordID adds an option to determine whether to return the record identifier for each document.
// If true, a $recordId field will be added to each returned document.
func (f *FindOneOptions) SetShowRecordID(b bool) *FindOneOptions {
f.ShowRecordID = &b
return f
}
// SetSkip specifies the number of documents to skip before returning.
func (f *FindOneOptions) SetSkip(i int64) *FindOneOptions {
f.Skip = &i
return f
}
// SetSnapshot prevents the cursor from returning a document more than once because of an intervening write operation.
func (f *FindOneOptions) SetSnapshot(b bool) *FindOneOptions {
f.Snapshot = &b
return f
}
// SetSort specifies the order in which to return documents.
func (f *FindOneOptions) SetSort(sort interface{}) *FindOneOptions {
f.Sort = sort
return f
}
// MergeFindOneOptions combines the argued FindOneOptions into a single FindOneOptions in a last-one-wins fashion
func MergeFindOneOptions(opts ...*FindOneOptions) *FindOneOptions {
fo := FindOne()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.AllowPartialResults != nil {
fo.AllowPartialResults = opt.AllowPartialResults
}
if opt.BatchSize != nil {
fo.BatchSize = opt.BatchSize
}
if opt.Collation != nil {
fo.Collation = opt.Collation
}
if opt.Comment != nil {
fo.Comment = opt.Comment
}
if opt.CursorType != nil {
fo.CursorType = opt.CursorType
}
if opt.Hint != nil {
fo.Hint = opt.Hint
}
if opt.Max != nil {
fo.Max = opt.Max
}
if opt.MaxAwaitTime != nil {
fo.MaxAwaitTime = opt.MaxAwaitTime
}
if opt.MaxTime != nil {
fo.MaxTime = opt.MaxTime
}
if opt.Min != nil {
fo.Min = opt.Min
}
if opt.NoCursorTimeout != nil {
fo.NoCursorTimeout = opt.NoCursorTimeout
}
if opt.OplogReplay != nil {
fo.OplogReplay = opt.OplogReplay
}
if opt.Projection != nil {
fo.Projection = opt.Projection
}
if opt.ReturnKey != nil {
fo.ReturnKey = opt.ReturnKey
}
if opt.ShowRecordID != nil {
fo.ShowRecordID = opt.ShowRecordID
}
if opt.Skip != nil {
fo.Skip = opt.Skip
}
if opt.Snapshot != nil {
fo.Snapshot = opt.Snapshot
}
if opt.Sort != nil {
fo.Sort = opt.Sort
}
}
return fo
}
// FindOneAndReplaceOptions represent all possible options to the FindOneAndReplace() function.
type FindOneAndReplaceOptions struct {
BypassDocumentValidation *bool // If true, allows the write to opt out of document-level validation.
Collation *Collation // Specifies a collation to be used
MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run.
Projection interface{} // Limits the fields returned for all documents.
ReturnDocument *ReturnDocument // Specifies whether the original or updated document should be returned.
Sort interface{} // Specifies the order in which to return results.
Upsert *bool // If true, creates a a new document if no document matches the query.
}
// FindOneAndReplace creates a new FindOneAndReplaceOptions instance.
func FindOneAndReplace() *FindOneAndReplaceOptions {
return &FindOneAndReplaceOptions{}
}
// SetBypassDocumentValidation specifies whether or not the write should opt out of document-level validation.
// Valid for server versions >= 3.2. For servers < 3.2, this option is ignored.
func (f *FindOneAndReplaceOptions) SetBypassDocumentValidation(b bool) *FindOneAndReplaceOptions {
f.BypassDocumentValidation = &b
return f
}
// SetCollation specifies a Collation to use for the Find operation.
func (f *FindOneAndReplaceOptions) SetCollation(collation *Collation) *FindOneAndReplaceOptions {
f.Collation = collation
return f
}
// SetMaxTime specifies the max time to allow the query to run.
func (f *FindOneAndReplaceOptions) SetMaxTime(d time.Duration) *FindOneAndReplaceOptions {
f.MaxTime = &d
return f
}
// SetProjection adds an option to limit the fields returned for all documents.
func (f *FindOneAndReplaceOptions) SetProjection(projection interface{}) *FindOneAndReplaceOptions {
f.Projection = projection
return f
}
// SetReturnDocument specifies whether the original or updated document should be returned.
// If set to Before, the original document will be returned. If set to After, the updated document
// will be returned.
func (f *FindOneAndReplaceOptions) SetReturnDocument(rd ReturnDocument) *FindOneAndReplaceOptions {
f.ReturnDocument = &rd
return f
}
// SetSort specifies the order in which to return documents.
func (f *FindOneAndReplaceOptions) SetSort(sort interface{}) *FindOneAndReplaceOptions {
f.Sort = sort
return f
}
// SetUpsert specifies if a new document should be created if no document matches the query.
func (f *FindOneAndReplaceOptions) SetUpsert(b bool) *FindOneAndReplaceOptions {
f.Upsert = &b
return f
}
// MergeFindOneAndReplaceOptions combines the argued FindOneAndReplaceOptions into a single FindOneAndReplaceOptions in a last-one-wins fashion
func MergeFindOneAndReplaceOptions(opts ...*FindOneAndReplaceOptions) *FindOneAndReplaceOptions {
fo := FindOneAndReplace()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.BypassDocumentValidation != nil {
fo.BypassDocumentValidation = opt.BypassDocumentValidation
}
if opt.Collation != nil {
fo.Collation = opt.Collation
}
if opt.MaxTime != nil {
fo.MaxTime = opt.MaxTime
}
if opt.Projection != nil {
fo.Projection = opt.Projection
}
if opt.ReturnDocument != nil {
fo.ReturnDocument = opt.ReturnDocument
}
if opt.Sort != nil {
fo.Sort = opt.Sort
}
if opt.Upsert != nil {
fo.Upsert = opt.Upsert
}
}
return fo
}
// FindOneAndUpdateOptions represent all possible options to the FindOneAndUpdate() function.
type FindOneAndUpdateOptions struct {
ArrayFilters *ArrayFilters // A set of filters specifying to which array elements an update should apply.
BypassDocumentValidation *bool // If true, allows the write to opt out of document-level validation.
Collation *Collation // Specifies a collation to be used
MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run.
Projection interface{} // Limits the fields returned for all documents.
ReturnDocument *ReturnDocument // Specifies whether the original or updated document should be returned.
Sort interface{} // Specifies the order in which to return results.
Upsert *bool // If true, creates a a new document if no document matches the query.
}
// FindOneAndUpdate creates a new FindOneAndUpdateOptions instance.
func FindOneAndUpdate() *FindOneAndUpdateOptions {
return &FindOneAndUpdateOptions{}
}
// SetBypassDocumentValidation sets filters that specify to which array elements an update should apply.
func (f *FindOneAndUpdateOptions) SetBypassDocumentValidation(b bool) *FindOneAndUpdateOptions {
f.BypassDocumentValidation = &b
return f
}
// SetArrayFilters specifies a set of filters, which
func (f *FindOneAndUpdateOptions) SetArrayFilters(filters ArrayFilters) *FindOneAndUpdateOptions {
f.ArrayFilters = &filters
return f
}
// SetCollation specifies a Collation to use for the Find operation.
func (f *FindOneAndUpdateOptions) SetCollation(collation *Collation) *FindOneAndUpdateOptions {
f.Collation = collation
return f
}
// SetMaxTime specifies the max time to allow the query to run.
func (f *FindOneAndUpdateOptions) SetMaxTime(d time.Duration) *FindOneAndUpdateOptions {
f.MaxTime = &d
return f
}
// SetProjection adds an option to limit the fields returned for all documents.
func (f *FindOneAndUpdateOptions) SetProjection(projection interface{}) *FindOneAndUpdateOptions {
f.Projection = projection
return f
}
// SetReturnDocument specifies whether the original or updated document should be returned.
// If set to Before, the original document will be returned. If set to After, the updated document
// will be returned.
func (f *FindOneAndUpdateOptions) SetReturnDocument(rd ReturnDocument) *FindOneAndUpdateOptions {
f.ReturnDocument = &rd
return f
}
// SetSort specifies the order in which to return documents.
func (f *FindOneAndUpdateOptions) SetSort(sort interface{}) *FindOneAndUpdateOptions {
f.Sort = sort
return f
}
// SetUpsert specifies if a new document should be created if no document matches the query.
func (f *FindOneAndUpdateOptions) SetUpsert(b bool) *FindOneAndUpdateOptions {
f.Upsert = &b
return f
}
// MergeFindOneAndUpdateOptions combines the argued FindOneAndUpdateOptions into a single FindOneAndUpdateOptions in a last-one-wins fashion
func MergeFindOneAndUpdateOptions(opts ...*FindOneAndUpdateOptions) *FindOneAndUpdateOptions {
fo := FindOneAndUpdate()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.ArrayFilters != nil {
fo.ArrayFilters = opt.ArrayFilters
}
if opt.BypassDocumentValidation != nil {
fo.BypassDocumentValidation = opt.BypassDocumentValidation
}
if opt.Collation != nil {
fo.Collation = opt.Collation
}
if opt.MaxTime != nil {
fo.MaxTime = opt.MaxTime
}
if opt.Projection != nil {
fo.Projection = opt.Projection
}
if opt.ReturnDocument != nil {
fo.ReturnDocument = opt.ReturnDocument
}
if opt.Sort != nil {
fo.Sort = opt.Sort
}
if opt.Upsert != nil {
fo.Upsert = opt.Upsert
}
}
return fo
}
// FindOneAndDeleteOptions represent all possible options to the FindOneAndDelete() function.
type FindOneAndDeleteOptions struct {
Collation *Collation // Specifies a collation to be used
MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run.
Projection interface{} // Limits the fields returned for all documents.
Sort interface{} // Specifies the order in which to return results.
}
// FindOneAndDelete creates a new FindOneAndDeleteOptions instance.
func FindOneAndDelete() *FindOneAndDeleteOptions {
return &FindOneAndDeleteOptions{}
}
// SetCollation specifies a Collation to use for the Find operation.
// Valid for server versions >= 3.4
func (f *FindOneAndDeleteOptions) SetCollation(collation *Collation) *FindOneAndDeleteOptions {
f.Collation = collation
return f
}
// SetMaxTime specifies the max time to allow the query to run.
func (f *FindOneAndDeleteOptions) SetMaxTime(d time.Duration) *FindOneAndDeleteOptions {
f.MaxTime = &d
return f
}
// SetProjection adds an option to limit the fields returned for all documents.
func (f *FindOneAndDeleteOptions) SetProjection(projection interface{}) *FindOneAndDeleteOptions {
f.Projection = projection
return f
}
// SetSort specifies the order in which to return documents.
func (f *FindOneAndDeleteOptions) SetSort(sort interface{}) *FindOneAndDeleteOptions {
f.Sort = sort
return f
}
// MergeFindOneAndDeleteOptions combines the argued FindOneAndDeleteOptions into a single FindOneAndDeleteOptions in a last-one-wins fashion
func MergeFindOneAndDeleteOptions(opts ...*FindOneAndDeleteOptions) *FindOneAndDeleteOptions {
fo := FindOneAndDelete()
for _, opt := range opts {
if opt == nil {
continue
}
if opt.Collation != nil {
fo.Collation = opt.Collation
}
if opt.MaxTime != nil {
fo.MaxTime = opt.MaxTime
}
if opt.Projection != nil {
fo.Projection = opt.Projection
}
if opt.Sort != nil {
fo.Sort = opt.Sort
}
}
return fo
}

View File

@@ -0,0 +1,274 @@
// 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.
var DefaultChunkSize int32 = 255 * 1024 // 255 KiB
// DefaultRevision is the default revision number for a download by name operation.
var DefaultRevision int32 = -1
// BucketOptions represents all possible options to configure a GridFS bucket.
type BucketOptions struct {
Name *string // The bucket name. Defaults to "fs".
ChunkSizeBytes *int32 // The chunk size in bytes. Defaults to 255KB.
WriteConcern *writeconcern.WriteConcern // The write concern for the bucket. Defaults to the write concern of the database.
ReadConcern *readconcern.ReadConcern // The read concern for the bucket. Defaults to the read concern of the database.
ReadPreference *readpref.ReadPref // The read preference for the bucket. Defaults to the read preference of the database.
}
// GridFSBucket creates a new *BucketOptions
func GridFSBucket() *BucketOptions {
return &BucketOptions{
Name: &DefaultName,
ChunkSizeBytes: &DefaultChunkSize,
}
}
// SetName sets the name for the bucket. Defaults to "fs" if not set.
func (b *BucketOptions) SetName(name string) *BucketOptions {
b.Name = &name
return b
}
// SetChunkSizeBytes sets the chunk size in bytes for the bucket. Defaults to 255KB if not set.
func (b *BucketOptions) SetChunkSizeBytes(i int32) *BucketOptions {
b.ChunkSizeBytes = &i
return b
}
// SetWriteConcern sets the write concern for the bucket.
func (b *BucketOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *BucketOptions {
b.WriteConcern = wc
return b
}
// SetReadConcern sets the read concern for the bucket.
func (b *BucketOptions) SetReadConcern(rc *readconcern.ReadConcern) *BucketOptions {
b.ReadConcern = rc
return b
}
// SetReadPreference sets the read preference for the bucket.
func (b *BucketOptions) SetReadPreference(rp *readpref.ReadPref) *BucketOptions {
b.ReadPreference = rp
return b
}
// MergeBucketOptions combines the given *BucketOptions into a single *BucketOptions.
// If the name or chunk size is not set in any of the given *BucketOptions, the resulting *BucketOptions will have
// name "fs" and chunk size 255KB.
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 all possible options for a GridFS upload operation. If a registry is nil, bson.DefaultRegistry
// will be used when converting the Metadata interface to BSON.
type UploadOptions struct {
ChunkSizeBytes *int32 // Chunk size in bytes. Defaults to the chunk size of the bucket.
Metadata interface{} // User data for the 'metadata' field of the files collection document.
Registry *bsoncodec.Registry // The registry to use for converting filters. Defaults to bson.DefaultRegistry.
}
// GridFSUpload creates a new *UploadOptions
func GridFSUpload() *UploadOptions {
return &UploadOptions{Registry: bson.DefaultRegistry}
}
// SetChunkSizeBytes sets the chunk size in bytes for the upload. Defaults to 255KB if not set.
func (u *UploadOptions) SetChunkSizeBytes(i int32) *UploadOptions {
u.ChunkSizeBytes = &i
return u
}
// SetMetadata specfies the metadata for the upload.
func (u *UploadOptions) SetMetadata(doc interface{}) *UploadOptions {
u.Metadata = doc
return u
}
// MergeUploadOptions combines the given *UploadOptions into a single *UploadOptions.
// If the chunk size is not set in any of the given *UploadOptions, the resulting *UploadOptions will have chunk size
// 255KB.
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 all options that can be used for a GridFS download by name operation.
type NameOptions struct {
Revision *int32 // Which revision (documents with the same filename and different uploadDate). Defaults to -1 (the most recent revision).
}
// GridFSName creates a new *NameOptions
func GridFSName() *NameOptions {
return &NameOptions{}
}
// SetRevision specifies which revision of the file to retrieve. Defaults to -1.
// * 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
func (n *NameOptions) SetRevision(r int32) *NameOptions {
n.Revision = &r
return n
}
// MergeNameOptions combines the given *NameOptions 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 all options for a GridFS find operation.
type GridFSFindOptions struct {
BatchSize *int32
Limit *int32
MaxTime *time.Duration
NoCursorTimeout *bool
Skip *int32
Sort interface{}
}
// GridFSFind creates a new GridFSFindOptions instance.
func GridFSFind() *GridFSFindOptions {
return &GridFSFindOptions{}
}
// SetBatchSize sets the number of documents to return in each batch.
func (f *GridFSFindOptions) SetBatchSize(i int32) *GridFSFindOptions {
f.BatchSize = &i
return f
}
// SetLimit specifies a limit on the number of results.
// A negative limit implies that only 1 batch should be returned.
func (f *GridFSFindOptions) SetLimit(i int32) *GridFSFindOptions {
f.Limit = &i
return f
}
// SetMaxTime specifies the max time to allow the query to run.
func (f *GridFSFindOptions) SetMaxTime(d time.Duration) *GridFSFindOptions {
f.MaxTime = &d
return f
}
// SetNoCursorTimeout specifies whether or not cursors should time out after a period of inactivity.
func (f *GridFSFindOptions) SetNoCursorTimeout(b bool) *GridFSFindOptions {
f.NoCursorTimeout = &b
return f
}
// SetSkip specifies the number of documents to skip before returning.
func (f *GridFSFindOptions) SetSkip(i int32) *GridFSFindOptions {
f.Skip = &i
return f
}
// SetSort specifies the order in which to return documents.
func (f *GridFSFindOptions) SetSort(sort interface{}) *GridFSFindOptions {
f.Sort = sort
return f
}
// MergeGridFSFindOptions combines the argued GridFSFindOptions 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.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,336 @@
// 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 all possible options for the CreateOne() and CreateMany() functions.
type CreateIndexesOptions struct {
MaxTime *time.Duration // The maximum amount of time to allow the query to run.
}
// CreateIndexes creates a new CreateIndexesOptions instance.
func CreateIndexes() *CreateIndexesOptions {
return &CreateIndexesOptions{}
}
// SetMaxTime specifies the maximum amount of time to allow the query to run.
func (c *CreateIndexesOptions) SetMaxTime(d time.Duration) *CreateIndexesOptions {
c.MaxTime = &d
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
}
}
return c
}
// DropIndexesOptions represents all possible options for the DropIndexes() function.
type DropIndexesOptions struct {
MaxTime *time.Duration
}
// DropIndexes creates a new DropIndexesOptions instance.
func DropIndexes() *DropIndexesOptions {
return &DropIndexesOptions{}
}
// SetMaxTime specifies the maximum amount of time to allow the query to run.
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 all possible options for the ListIndexes() function.
type ListIndexesOptions struct {
BatchSize *int32
MaxTime *time.Duration
}
// ListIndexes creates a new ListIndexesOptions instance.
func ListIndexes() *ListIndexesOptions {
return &ListIndexesOptions{}
}
// SetBatchSize specifies the number of documents to return in every batch.
func (l *ListIndexesOptions) SetBatchSize(i int32) *ListIndexesOptions {
l.BatchSize = &i
return l
}
// SetMaxTime specifies the maximum amount of time to allow the query to run.
func (l *ListIndexesOptions) SetMaxTime(d time.Duration) *ListIndexesOptions {
l.MaxTime = &d
return l
}
// MergeListIndexesOptions combines the given *ListIndexesOptions 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.MaxTime != nil {
c.MaxTime = opt.MaxTime
}
}
return c
}
// IndexOptions represents all possible options to configure a new index.
type IndexOptions struct {
Background *bool
ExpireAfterSeconds *int32
Name *string
Sparse *bool
StorageEngine interface{}
Unique *bool
Version *int32
DefaultLanguage *string
LanguageOverride *string
TextVersion *int32
Weights interface{}
SphereVersion *int32
Bits *int32
Max *float64
Min *float64
BucketSize *int32
PartialFilterExpression interface{}
Collation *Collation
WildcardProjection interface{}
}
// Index creates a new *IndexOptions
func Index() *IndexOptions {
return &IndexOptions{}
}
// SetBackground sets the background option. If true, the server will create the index in the background and not block
// other tasks
func (i *IndexOptions) SetBackground(background bool) *IndexOptions {
i.Background = &background
return i
}
// SetExpireAfterSeconds specifies the number of seconds for a document to remain in a collection.
func (i *IndexOptions) SetExpireAfterSeconds(seconds int32) *IndexOptions {
i.ExpireAfterSeconds = &seconds
return i
}
// SetName specifies a name for the index.
// If not set, a name will be generated in the format "[field]_[direction]".
// If multiple indexes are created for the same key pattern with different collations, a name must be provided to avoid
// ambiguity.
func (i *IndexOptions) SetName(name string) *IndexOptions {
i.Name = &name
return i
}
// SetSparse sets the sparse option.
// If true, the index will only reference documents with the specified field in the index.
func (i *IndexOptions) SetSparse(sparse bool) *IndexOptions {
i.Sparse = &sparse
return i
}
// SetStorageEngine specifies the storage engine to use.
// Valid for server versions >= 3.0
func (i *IndexOptions) SetStorageEngine(engine interface{}) *IndexOptions {
i.StorageEngine = engine
return i
}
// SetUnique forces the index to be unique.
func (i *IndexOptions) SetUnique(unique bool) *IndexOptions {
i.Unique = &unique
return i
}
// SetVersion specifies the index version number, either 0 or 1.
func (i *IndexOptions) SetVersion(version int32) *IndexOptions {
i.Version = &version
return i
}
// SetDefaultLanguage specifies the default language for text indexes.
// If not set, this will default to english.
func (i *IndexOptions) SetDefaultLanguage(language string) *IndexOptions {
i.DefaultLanguage = &language
return i
}
// SetLanguageOverride specifies the field in the document to override the language.
func (i *IndexOptions) SetLanguageOverride(override string) *IndexOptions {
i.LanguageOverride = &override
return i
}
// SetTextVersion specifies the text index version number.
// MongoDB version 2.4 can only support version 1.
// MongoDB versions 2.6 and higher can support versions 1 or 2.
func (i *IndexOptions) SetTextVersion(version int32) *IndexOptions {
i.TextVersion = &version
return i
}
// SetWeights specifies fields in the index and their corresponding weight values.
func (i *IndexOptions) SetWeights(weights interface{}) *IndexOptions {
i.Weights = weights
return i
}
// SetSphereVersion specifies the 2dsphere index version number.
// MongoDB version 2.4 can only support version 1.
// MongoDB versions 2.6 and higher can support versions 1 or 2.
func (i *IndexOptions) SetSphereVersion(version int32) *IndexOptions {
i.SphereVersion = &version
return i
}
// SetBits specifies the precision of the stored geo hash in the 2d index, from 1 to 32.
func (i *IndexOptions) SetBits(bits int32) *IndexOptions {
i.Bits = &bits
return i
}
// SetMax specifies the maximum boundary for latitude and longitude in the 2d index.
func (i *IndexOptions) SetMax(max float64) *IndexOptions {
i.Max = &max
return i
}
// SetMin specifies the minimum boundary for latitude and longitude in the 2d index.
func (i *IndexOptions) SetMin(min float64) *IndexOptions {
i.Min = &min
return i
}
// SetBucketSize specifies number of units within which to group the location values in a geo haystack index.
func (i *IndexOptions) SetBucketSize(bucketSize int32) *IndexOptions {
i.BucketSize = &bucketSize
return i
}
// SetPartialFilterExpression specifies a filter for use in a partial index. Only documents that match the filter
// expression are included in the index.
func (i *IndexOptions) SetPartialFilterExpression(expression interface{}) *IndexOptions {
i.PartialFilterExpression = expression
return i
}
// SetCollation specifies a Collation to use for the operation.
// Valid for server versions >= 3.4
func (i *IndexOptions) SetCollation(collation *Collation) *IndexOptions {
i.Collation = collation
return i
}
// SetWildcardProjection specifies a wildcard projection for a wildcard index.
func (i *IndexOptions) SetWildcardProjection(wildcardProjection interface{}) *IndexOptions {
i.WildcardProjection = wildcardProjection
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.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
}
}
return i
}

View File

@@ -0,0 +1,84 @@
// 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 all possible options to the InsertOne() function.
type InsertOneOptions struct {
BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation
}
// InsertOne returns a pointer to a new InsertOneOptions
func InsertOne() *InsertOneOptions {
return &InsertOneOptions{}
}
// SetBypassDocumentValidation allows the write to opt-out of document level validation.
// Valid for server versions >= 3.2. For servers < 3.2, this option is ignored.
func (ioo *InsertOneOptions) SetBypassDocumentValidation(b bool) *InsertOneOptions {
ioo.BypassDocumentValidation = &b
return ioo
}
// MergeInsertOneOptions combines the argued InsertOneOptions 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
}
}
return ioOpts
}
// InsertManyOptions represents all possible options to the InsertMany() function.
type InsertManyOptions struct {
BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation
Ordered *bool // If true, when an insert fails, return without performing the remaining inserts. Defaults to true.
}
// InsertMany returns a pointer to a new InsertManyOptions
func InsertMany() *InsertManyOptions {
return &InsertManyOptions{
Ordered: &DefaultOrdered,
}
}
// SetBypassDocumentValidation allows the write to opt-out of document level validation.
// Valid for server versions >= 3.2. For servers < 3.2, this option is ignored.
func (imo *InsertManyOptions) SetBypassDocumentValidation(b bool) *InsertManyOptions {
imo.BypassDocumentValidation = &b
return imo
}
// SetOrdered configures the ordered option. If true, when a write fails, the function will return without attempting
// remaining writes. Defaults to true.
func (imo *InsertManyOptions) SetOrdered(b bool) *InsertManyOptions {
imo.Ordered = &b
return imo
}
// MergeInsertManyOptions combines the argued InsertManyOptions 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.Ordered != nil {
imOpts.Ordered = imo.Ordered
}
}
return imOpts
}

View File

@@ -0,0 +1,39 @@
// 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 all possible options for a listCollections command.
type ListCollectionsOptions struct {
NameOnly *bool // If true, only the collection names will be returned.
}
// ListCollections creates a new *ListCollectionsOptions
func ListCollections() *ListCollectionsOptions {
return &ListCollectionsOptions{}
}
// SetNameOnly specifies whether to return only the collection names.
func (lc *ListCollectionsOptions) SetNameOnly(b bool) *ListCollectionsOptions {
lc.NameOnly = &b
return lc
}
// MergeListCollectionsOptions combines the given *ListCollectionsOptions 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
}
}
return lc
}

View File

@@ -0,0 +1,39 @@
// 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 all possible options for a listDatabases command.
type ListDatabasesOptions struct {
NameOnly *bool // If true, only the database names will be returned.
}
// ListDatabases creates a new *ListDatabasesOptions
func ListDatabases() *ListDatabasesOptions {
return &ListDatabasesOptions{}
}
// SetNameOnly specifies whether to return only the database names.
func (ld *ListDatabasesOptions) SetNameOnly(b bool) *ListDatabasesOptions {
ld.NameOnly = &b
return ld
}
// MergeListDatabasesOptions combines the given *ListDatabasesOptions into a single *ListDatabasesOptions in a last one
// wins fashion.
func MergeListDatabasesOptions(opts ...*ListDatabasesOptions) *ListDatabasesOptions {
ld := ListDatabases()
for _, opt := range opts {
if opts == nil {
continue
}
if opt.NameOnly != nil {
ld.NameOnly = opt.NameOnly
}
}
return ld
}

View File

@@ -0,0 +1,161 @@
// 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 comparision 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 whether a change stream should include a copy of the entire document that was changed from
// some time after the change occurred.
type FullDocument string
const (
// Default does not include a document copy
Default FullDocument = "default"
// UpdateLookup includes a delta describing the changes to the document and a copy of the entire document that
// was changed
UpdateLookup FullDocument = "updateLookup"
)
// 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))
}
var defaultRegistry = bson.DefaultRegistry

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
// ReplaceOptions represents all possible options to the ReplaceOne() function.
type ReplaceOptions struct {
BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation
Collation *Collation // Specifies a collation
Upsert *bool // When true, creates a new document if no document matches the query
}
// Replace returns a pointer to a new ReplaceOptions
func Replace() *ReplaceOptions {
return &ReplaceOptions{}
}
// SetBypassDocumentValidation allows the write to opt-out of document level validation.
// Valid for server versions >= 3.2. For servers < 3.2, this option is ignored.
func (ro *ReplaceOptions) SetBypassDocumentValidation(b bool) *ReplaceOptions {
ro.BypassDocumentValidation = &b
return ro
}
// SetCollation specifies a collation.
// Valid for servers >= 3.4
func (ro *ReplaceOptions) SetCollation(c *Collation) *ReplaceOptions {
ro.Collation = c
return ro
}
// SetUpsert allows the creation of a new document if not document matches the query
func (ro *ReplaceOptions) SetUpsert(b bool) *ReplaceOptions {
ro.Upsert = &b
return ro
}
// MergeReplaceOptions combines the argued ReplaceOptions 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.Upsert != nil {
rOpts.Upsert = ro.Upsert
}
}
return rOpts
}

View File

@@ -0,0 +1,40 @@
// 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 all possible options for a runCommand operation.
type RunCmdOptions struct {
ReadPreference *readpref.ReadPref // The read preference for the operation.
}
// RunCmd creates a new *RunCmdOptions
func RunCmd() *RunCmdOptions {
return &RunCmdOptions{}
}
// SetReadPreference sets the read preference for the operation.
func (rc *RunCmdOptions) SetReadPreference(rp *readpref.ReadPref) *RunCmdOptions {
rc.ReadPreference = rp
return rc
}
// MergeRunCmdOptions combines the given *RunCmdOptions 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,79 @@
// 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/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 all possible options for creating a new session.
type SessionOptions struct {
CausalConsistency *bool // Specifies if reads should be causally consistent. Defaults to true.
DefaultReadConcern *readconcern.ReadConcern // The default read concern for transactions started in the session.
DefaultReadPreference *readpref.ReadPref // The default read preference for transactions started in the session.
DefaultWriteConcern *writeconcern.WriteConcern // The default write concern for transactions started in the session.
}
// Session creates a new *SessionOptions
func Session() *SessionOptions {
return &SessionOptions{
CausalConsistency: &DefaultCausalConsistency,
}
}
// SetCausalConsistency specifies if a session should be causally consistent. Defaults to true.
func (s *SessionOptions) SetCausalConsistency(b bool) *SessionOptions {
s.CausalConsistency = &b
return s
}
// SetDefaultReadConcern sets the default read concern for transactions started in a session.
func (s *SessionOptions) SetDefaultReadConcern(rc *readconcern.ReadConcern) *SessionOptions {
s.DefaultReadConcern = rc
return s
}
// SetDefaultReadPreference sets the default read preference for transactions started in a session.
func (s *SessionOptions) SetDefaultReadPreference(rp *readpref.ReadPref) *SessionOptions {
s.DefaultReadPreference = rp
return s
}
// SetDefaultWriteConcern sets the default write concern for transactions started in a session.
func (s *SessionOptions) SetDefaultWriteConcern(wc *writeconcern.WriteConcern) *SessionOptions {
s.DefaultWriteConcern = wc
return s
}
// MergeSessionOptions combines the given *SessionOptions 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
}
}
return s
}

View File

@@ -0,0 +1,65 @@
// 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/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
// TransactionOptions represents all possible options for starting a transaction.
type TransactionOptions struct {
ReadConcern *readconcern.ReadConcern // The read concern for the transaction. Defaults to the session's read concern.
ReadPreference *readpref.ReadPref // The read preference for the transaction. Defaults to the session's read preference.
WriteConcern *writeconcern.WriteConcern // The write concern for the transaction. Defaults to the session's write concern.
}
// Transaction creates a new *TransactionOptions
func Transaction() *TransactionOptions {
return &TransactionOptions{}
}
// SetReadConcern sets the read concern for the transaction.
func (t *TransactionOptions) SetReadConcern(rc *readconcern.ReadConcern) *TransactionOptions {
t.ReadConcern = rc
return t
}
// SetReadPreference sets the read preference for the transaction.
func (t *TransactionOptions) SetReadPreference(rp *readpref.ReadPref) *TransactionOptions {
t.ReadPreference = rp
return t
}
// SetWriteConcern sets the write concern for the transaction.
func (t *TransactionOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *TransactionOptions {
t.WriteConcern = wc
return t
}
// MergeTransactionOptions combines the given *TransactionOptions 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
}
}
return t
}

View File

@@ -0,0 +1,71 @@
// 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 all possible options to the UpdateOne() and UpdateMany() functions.
type UpdateOptions struct {
ArrayFilters *ArrayFilters // A set of filters specifying to which array elements an update should apply
BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation
Collation *Collation // Specifies a collation
Upsert *bool // When true, creates a new document if no document matches the query
}
// Update returns a pointer to a new UpdateOptions
func Update() *UpdateOptions {
return &UpdateOptions{}
}
// SetArrayFilters specifies a set of filters specifying to which array elements an update should apply
// Valid for server versions >= 3.6.
func (uo *UpdateOptions) SetArrayFilters(af ArrayFilters) *UpdateOptions {
uo.ArrayFilters = &af
return uo
}
// SetBypassDocumentValidation allows the write to opt-out of document level validation.
// Valid for server versions >= 3.2. For servers < 3.2, this option is ignored.
func (uo *UpdateOptions) SetBypassDocumentValidation(b bool) *UpdateOptions {
uo.BypassDocumentValidation = &b
return uo
}
// SetCollation specifies a collation.
// Valid for server versions >= 3.4.
func (uo *UpdateOptions) SetCollation(c *Collation) *UpdateOptions {
uo.Collation = c
return uo
}
// SetUpsert allows the creation of a new document if not document matches the query
func (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {
uo.Upsert = &b
return uo
}
// MergeUpdateOptions combines the argued UpdateOptions 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.Upsert != nil {
uOpts.Upsert = uo.Upsert
}
}
return uOpts
}