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,328 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson/bsontype"
"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/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// Performs an aggregate operation
type Aggregate struct {
allowDiskUse *bool
batchSize *int32
bypassDocumentValidation *bool
collation bsoncore.Document
comment *string
hint bsoncore.Value
maxTimeMS *int64
pipeline bsoncore.Document
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
readConcern *readconcern.ReadConcern
readPreference *readpref.ReadPref
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
result driver.CursorResponse
}
// NewAggregate constructs and returns a new Aggregate.
func NewAggregate(pipeline bsoncore.Document) *Aggregate {
return &Aggregate{
pipeline: pipeline,
}
}
// Result returns the result of executing this operation.
func (a *Aggregate) Result(opts driver.CursorOptions) (*driver.BatchCursor, error) {
clientSession := a.session
clock := a.clock
return driver.NewBatchCursor(a.result, clientSession, clock, opts)
}
func (a *Aggregate) ResultCursorResponse() driver.CursorResponse {
return a.result
}
func (a *Aggregate) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
a.result, err = driver.NewCursorResponse(response, srvr, desc)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (a *Aggregate) Execute(ctx context.Context) error {
if a.deployment == nil {
return errors.New("the Aggregate operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: a.command,
ProcessResponseFn: a.processResponse,
Client: a.session,
Clock: a.clock,
CommandMonitor: a.monitor,
Database: a.database,
Deployment: a.deployment,
ReadConcern: a.readConcern,
ReadPreference: a.readPreference,
Selector: a.selector,
WriteConcern: a.writeConcern,
MinimumWriteConcernWireVersion: 5,
}.Execute(ctx, nil)
}
func (a *Aggregate) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
header := bsoncore.Value{Type: bsontype.String, Data: bsoncore.AppendString(nil, a.collection)}
if a.collection == "" {
header = bsoncore.Value{Type: bsontype.Int32, Data: []byte{0x01, 0x00, 0x00, 0x00}}
}
dst = bsoncore.AppendValueElement(dst, "aggregate", header)
cursorIdx, cursorDoc := bsoncore.AppendDocumentStart(nil)
if a.allowDiskUse != nil {
dst = bsoncore.AppendBooleanElement(dst, "allowDiskUse", *a.allowDiskUse)
}
if a.batchSize != nil {
cursorDoc = bsoncore.AppendInt32Element(cursorDoc, "batchSize", *a.batchSize)
}
if a.bypassDocumentValidation != nil {
dst = bsoncore.AppendBooleanElement(dst, "bypassDocumentValidation", *a.bypassDocumentValidation)
}
if a.collation != nil {
if desc.WireVersion == nil || !desc.WireVersion.Includes(5) {
return nil, errors.New("the 'collation' command parameter requires a minimum server wire version of 5")
}
dst = bsoncore.AppendDocumentElement(dst, "collation", a.collation)
}
if a.comment != nil {
dst = bsoncore.AppendStringElement(dst, "comment", *a.comment)
}
if a.hint.Type != bsontype.Type(0) {
dst = bsoncore.AppendValueElement(dst, "hint", a.hint)
}
if a.maxTimeMS != nil {
dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", *a.maxTimeMS)
}
if a.pipeline != nil {
dst = bsoncore.AppendArrayElement(dst, "pipeline", a.pipeline)
}
cursorDoc, _ = bsoncore.AppendDocumentEnd(cursorDoc, cursorIdx)
dst = bsoncore.AppendDocumentElement(dst, "cursor", cursorDoc)
return dst, nil
}
// AllowDiskUse enables writing to temporary files. When true, aggregation stages can write to the dbPath/_tmp directory.
func (a *Aggregate) AllowDiskUse(allowDiskUse bool) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.allowDiskUse = &allowDiskUse
return a
}
// BatchSize specifies the number of documents to return in every batch.
func (a *Aggregate) BatchSize(batchSize int32) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.batchSize = &batchSize
return a
}
// BypassDocumentValidation allows the write to opt-out of document level validation. This only applies when the $out stage is specified.
func (a *Aggregate) BypassDocumentValidation(bypassDocumentValidation bool) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.bypassDocumentValidation = &bypassDocumentValidation
return a
}
// Collation specifies a collation. This option is only valid for server versions 3.4 and above.
func (a *Aggregate) Collation(collation bsoncore.Document) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.collation = collation
return a
}
// Comment specifies an arbitrary string to help trace the operation through the database profiler, currentOp, and logs.
func (a *Aggregate) Comment(comment string) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.comment = &comment
return a
}
// Hint specifies the index to use.
func (a *Aggregate) Hint(hint bsoncore.Value) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.hint = hint
return a
}
// MaxTimeMS specifies the maximum amount of time to allow the query to run.
func (a *Aggregate) MaxTimeMS(maxTimeMS int64) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.maxTimeMS = &maxTimeMS
return a
}
// Pipeline determines how data is transformed for an aggregation.
func (a *Aggregate) Pipeline(pipeline bsoncore.Document) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.pipeline = pipeline
return a
}
// Session sets the session for this operation.
func (a *Aggregate) Session(session *session.Client) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.session = session
return a
}
// ClusterClock sets the cluster clock for this operation.
func (a *Aggregate) ClusterClock(clock *session.ClusterClock) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.clock = clock
return a
}
// Collection sets the collection that this command will run against.
func (a *Aggregate) Collection(collection string) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.collection = collection
return a
}
// CommandMonitor sets the monitor to use for APM events.
func (a *Aggregate) CommandMonitor(monitor *event.CommandMonitor) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.monitor = monitor
return a
}
// Database sets the database to run this operation against.
func (a *Aggregate) Database(database string) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.database = database
return a
}
// Deployment sets the deployment to use for this operation.
func (a *Aggregate) Deployment(deployment driver.Deployment) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.deployment = deployment
return a
}
// ReadConcern specifies the read concern for this operation.
func (a *Aggregate) ReadConcern(readConcern *readconcern.ReadConcern) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.readConcern = readConcern
return a
}
// ReadPreference set the read prefernce used with this operation.
func (a *Aggregate) ReadPreference(readPreference *readpref.ReadPref) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.readPreference = readPreference
return a
}
// ServerSelector sets the selector used to retrieve a server.
func (a *Aggregate) ServerSelector(selector description.ServerSelector) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.selector = selector
return a
}
// WriteConcern sets the write concern for this operation.
func (a *Aggregate) WriteConcern(writeConcern *writeconcern.WriteConcern) *Aggregate {
if a == nil {
a = new(Aggregate)
}
a.writeConcern = writeConcern
return a
}

View File

@@ -0,0 +1,47 @@
version = 0
name = "Aggregate"
documentation = "Performs an aggregate operation"
response.type = "batch cursor"
[properties]
enabled = ["read concern", "read preference", "write concern"]
MinimumWriteConcernWireVersion = 5
[command]
name = "aggregate"
parameter = "collection"
database = true
[request.pipeline]
type = "array"
constructor = true
documentation = "Pipeline determines how data is transformed for an aggregation."
[request.allowDiskUse]
type = "boolean"
documentation = "AllowDiskUse enables writing to temporary files. When true, aggregation stages can write to the dbPath/_tmp directory."
[request.batchSize]
type = "int32"
documentation = "BatchSize specifies the number of documents to return in every batch."
[request.bypassDocumentValidation]
type = "boolean"
documentation = "BypassDocumentValidation allows the write to opt-out of document level validation. This only applies when the $out stage is specified."
[request.collation]
type = "document"
minWireVersionRequired = 5
documentation = "Collation specifies a collation. This option is only valid for server versions 3.4 and above."
[request.maxTimeMS]
type = "int64"
documentation = "MaxTimeMS specifies the maximum amount of time to allow the query to run."
[request.comment]
type = "string"
documentation = "Comment specifies an arbitrary string to help trace the operation through the database profiler, currentOp, and logs."
[request.hint]
type = "value"
documentation = "Hint specifies the index to use."

View File

@@ -0,0 +1,164 @@
// NOTE: This file is maintained by hand because operationgen cannot generate it.
package operation
import (
"context"
"errors"
"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/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// Command is used to run a generic operation.
type Command struct {
command bsoncore.Document
readConcern *readconcern.ReadConcern
database string
deployment driver.Deployment
selector description.ServerSelector
readPreference *readpref.ReadPref
clock *session.ClusterClock
session *session.Client
monitor *event.CommandMonitor
result bsoncore.Document
srvr driver.Server
desc description.Server
}
// NewCommand constructs and returns a new Command.
func NewCommand(command bsoncore.Document) *Command { return &Command{command: command} }
// Result returns the result of executing this operation.
func (c *Command) Result() bsoncore.Document { return c.result }
// ResultCursor parses the command response as a cursor and returns the resulting BatchCursor.
func (c *Command) ResultCursor(opts driver.CursorOptions) (*driver.BatchCursor, error) {
cursorRes, err := driver.NewCursorResponse(c.result, c.srvr, c.desc)
if err != nil {
return nil, err
}
return driver.NewBatchCursor(cursorRes, c.session, c.clock, opts)
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (c *Command) Execute(ctx context.Context) error {
if c.deployment == nil {
return errors.New("the Command operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: func(dst []byte, desc description.SelectedServer) ([]byte, error) {
return append(dst, c.command[4:len(c.command)-1]...), nil
},
ProcessResponseFn: func(resp bsoncore.Document, srvr driver.Server, desc description.Server) error {
c.result = resp
c.srvr = srvr
c.desc = desc
return nil
},
Client: c.session,
Clock: c.clock,
CommandMonitor: c.monitor,
Database: c.database,
Deployment: c.deployment,
ReadPreference: c.readPreference,
Selector: c.selector,
}.Execute(ctx, nil)
}
// Command sets the command to be run.
func (c *Command) Command(command bsoncore.Document) *Command {
if c == nil {
c = new(Command)
}
c.command = command
return c
}
// Session sets the session for this operation.
func (c *Command) Session(session *session.Client) *Command {
if c == nil {
c = new(Command)
}
c.session = session
return c
}
// ClusterClock sets the cluster clock for this operation.
func (c *Command) ClusterClock(clock *session.ClusterClock) *Command {
if c == nil {
c = new(Command)
}
c.clock = clock
return c
}
// CommandMonitor sets the monitor to use for APM events.
func (c *Command) CommandMonitor(monitor *event.CommandMonitor) *Command {
if c == nil {
c = new(Command)
}
c.monitor = monitor
return c
}
// Database sets the database to run this operation against.
func (c *Command) Database(database string) *Command {
if c == nil {
c = new(Command)
}
c.database = database
return c
}
// Deployment sets the deployment to use for this operation.
func (c *Command) Deployment(deployment driver.Deployment) *Command {
if c == nil {
c = new(Command)
}
c.deployment = deployment
return c
}
// ReadConcern specifies the read concern for this operation.
func (c *Command) ReadConcern(readConcern *readconcern.ReadConcern) *Command {
if c == nil {
c = new(Command)
}
c.readConcern = readConcern
return c
}
// ReadPreference set the read prefernce used with this operation.
func (c *Command) ReadPreference(readPreference *readpref.ReadPref) *Command {
if c == nil {
c = new(Command)
}
c.readPreference = readPreference
return c
}
// ServerSelector sets the selector used to retrieve a server.
func (c *Command) ServerSelector(selector description.ServerSelector) *Command {
if c == nil {
c = new(Command)
}
c.selector = selector
return c
}

View File

@@ -0,0 +1,167 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// CommitTransaction attempts to commit a transaction.
type CommitTransaction struct {
recoveryToken bsoncore.Document
session *session.Client
clock *session.ClusterClock
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
retry *driver.RetryMode
}
// NewCommitTransaction constructs and returns a new CommitTransaction.
func NewCommitTransaction() *CommitTransaction {
return &CommitTransaction{}
}
func (ct *CommitTransaction) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (ct *CommitTransaction) Execute(ctx context.Context) error {
if ct.deployment == nil {
return errors.New("the CommitTransaction operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: ct.command,
ProcessResponseFn: ct.processResponse,
RetryMode: ct.retry,
RetryType: driver.RetryWrite,
Client: ct.session,
Clock: ct.clock,
CommandMonitor: ct.monitor,
Database: ct.database,
Deployment: ct.deployment,
Selector: ct.selector,
WriteConcern: ct.writeConcern,
}.Execute(ctx, nil)
}
func (ct *CommitTransaction) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendInt32Element(dst, "commitTransaction", 1)
if ct.recoveryToken != nil {
dst = bsoncore.AppendDocumentElement(dst, "recoveryToken", ct.recoveryToken)
}
return dst, nil
}
// RecoveryToken sets the recovery token to use when committing or aborting a sharded transaction.
func (ct *CommitTransaction) RecoveryToken(recoveryToken bsoncore.Document) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.recoveryToken = recoveryToken
return ct
}
// Session sets the session for this operation.
func (ct *CommitTransaction) Session(session *session.Client) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.session = session
return ct
}
// ClusterClock sets the cluster clock for this operation.
func (ct *CommitTransaction) ClusterClock(clock *session.ClusterClock) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.clock = clock
return ct
}
// CommandMonitor sets the monitor to use for APM events.
func (ct *CommitTransaction) CommandMonitor(monitor *event.CommandMonitor) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.monitor = monitor
return ct
}
// Database sets the database to run this operation against.
func (ct *CommitTransaction) Database(database string) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.database = database
return ct
}
// Deployment sets the deployment to use for this operation.
func (ct *CommitTransaction) Deployment(deployment driver.Deployment) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.deployment = deployment
return ct
}
// ServerSelector sets the selector used to retrieve a server.
func (ct *CommitTransaction) ServerSelector(selector description.ServerSelector) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.selector = selector
return ct
}
// WriteConcern sets the write concern for this operation.
func (ct *CommitTransaction) WriteConcern(writeConcern *writeconcern.WriteConcern) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.writeConcern = writeConcern
return ct
}
// Retry enables retryable writes for this operation. Retries are not handled automatically,
// instead a boolean is returned from Execute and SelectAndExecute that indicates if the
// operation can be retried. Retrying is handled by calling RetryExecute.
func (ct *CommitTransaction) Retry(retry driver.RetryMode) *CommitTransaction {
if ct == nil {
ct = new(CommitTransaction)
}
ct.retry = &retry
return ct
}

View File

@@ -0,0 +1,18 @@
version = 0
name = "CommitTransaction"
documentation = "CommitTransaction attempts to commit a transaction."
[properties]
enabled = ["write concern"]
disabled = ["collection"]
retryable = {mode = "once per command", type = "writes"}
[command]
name = "commitTransaction"
parameter = "database"
[request.recoveryToken]
type = "document"
documentation = """
RecoveryToken sets the recovery token to use when committing or aborting a sharded transaction.\
"""

View File

@@ -0,0 +1,211 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// CreateIndexes performs a createIndexes operation.
type CreateIndexes struct {
indexes bsoncore.Document
maxTimeMS *int64
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
result CreateIndexesResult
}
type CreateIndexesResult struct {
// If the collection was created automatically.
CreatedCollectionAutomatically bool
// The number of indexes existing after this command.
IndexesAfter int32
// The number of indexes existing before this command.
IndexesBefore int32
}
func buildCreateIndexesResult(response bsoncore.Document, srvr driver.Server) (CreateIndexesResult, error) {
elements, err := response.Elements()
if err != nil {
return CreateIndexesResult{}, err
}
cir := CreateIndexesResult{}
for _, element := range elements {
switch element.Key() {
case "createdCollectionAutomatically":
var ok bool
cir.CreatedCollectionAutomatically, ok = element.Value().BooleanOK()
if !ok {
err = fmt.Errorf("response field 'createdCollectionAutomatically' is type bool, but received BSON type %s", element.Value().Type)
}
case "indexesAfter":
var ok bool
cir.IndexesAfter, ok = element.Value().AsInt32OK()
if !ok {
err = fmt.Errorf("response field 'indexesAfter' is type int32, but received BSON type %s", element.Value().Type)
}
case "indexesBefore":
var ok bool
cir.IndexesBefore, ok = element.Value().AsInt32OK()
if !ok {
err = fmt.Errorf("response field 'indexesBefore' is type int32, but received BSON type %s", element.Value().Type)
}
}
}
return cir, nil
}
// NewCreateIndexes constructs and returns a new CreateIndexes.
func NewCreateIndexes(indexes bsoncore.Document) *CreateIndexes {
return &CreateIndexes{
indexes: indexes,
}
}
// Result returns the result of executing this operation.
func (ci *CreateIndexes) Result() CreateIndexesResult { return ci.result }
func (ci *CreateIndexes) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
ci.result, err = buildCreateIndexesResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (ci *CreateIndexes) Execute(ctx context.Context) error {
if ci.deployment == nil {
return errors.New("the CreateIndexes operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: ci.command,
ProcessResponseFn: ci.processResponse,
Client: ci.session,
Clock: ci.clock,
CommandMonitor: ci.monitor,
Database: ci.database,
Deployment: ci.deployment,
Selector: ci.selector,
}.Execute(ctx, nil)
}
func (ci *CreateIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "createIndexes", ci.collection)
if ci.indexes != nil {
dst = bsoncore.AppendArrayElement(dst, "indexes", ci.indexes)
}
if ci.maxTimeMS != nil {
dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", *ci.maxTimeMS)
}
return dst, nil
}
// An array containing index specification documents for the indexes being created.
func (ci *CreateIndexes) Indexes(indexes bsoncore.Document) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.indexes = indexes
return ci
}
// MaxTimeMS specifies the maximum amount of time to allow the query to run.
func (ci *CreateIndexes) MaxTimeMS(maxTimeMS int64) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.maxTimeMS = &maxTimeMS
return ci
}
// Session sets the session for this operation.
func (ci *CreateIndexes) Session(session *session.Client) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.session = session
return ci
}
// ClusterClock sets the cluster clock for this operation.
func (ci *CreateIndexes) ClusterClock(clock *session.ClusterClock) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.clock = clock
return ci
}
// Collection sets the collection that this command will run against.
func (ci *CreateIndexes) Collection(collection string) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.collection = collection
return ci
}
// CommandMonitor sets the monitor to use for APM events.
func (ci *CreateIndexes) CommandMonitor(monitor *event.CommandMonitor) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.monitor = monitor
return ci
}
// Database sets the database to run this operation against.
func (ci *CreateIndexes) Database(database string) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.database = database
return ci
}
// Deployment sets the deployment to use for this operation.
func (ci *CreateIndexes) Deployment(deployment driver.Deployment) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.deployment = deployment
return ci
}
// ServerSelector sets the selector used to retrieve a server.
func (ci *CreateIndexes) ServerSelector(selector description.ServerSelector) *CreateIndexes {
if ci == nil {
ci = new(CreateIndexes)
}
ci.selector = selector
return ci
}

View File

@@ -0,0 +1,31 @@
version = 0
name = "CreateIndexes"
documentation = "CreateIndexes performs a createIndexes operation."
[command]
name = "createIndexes"
parameter = "collection"
[request.indexes]
type = "array"
constructor = true
documentation = "An array containing index specification documents for the indexes being created."
[request.maxTimeMS]
type = "int64"
documentation = "MaxTimeMS specifies the maximum amount of time to allow the query to run."
[response]
name = "CreateIndexesResult"
[response.field.createdCollectionAutomatically]
type = "boolean"
documentation = "If the collection was created automatically."
[response.field.indexesBefore]
type = "int32"
documentation = "The number of indexes existing before this command."
[response.field.indexesAfter]
type = "int32"
documentation = "The number of indexes existing after this command."

View File

@@ -0,0 +1,229 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// Delete performs a delete operation
type Delete struct {
deletes []bsoncore.Document
ordered *bool
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
retry *driver.RetryMode
result DeleteResult
}
type DeleteResult struct {
// Number of documents successfully deleted.
N int32
}
func buildDeleteResult(response bsoncore.Document, srvr driver.Server) (DeleteResult, error) {
elements, err := response.Elements()
if err != nil {
return DeleteResult{}, err
}
dr := DeleteResult{}
for _, element := range elements {
switch element.Key() {
case "n":
var ok bool
dr.N, ok = element.Value().AsInt32OK()
if !ok {
err = fmt.Errorf("response field 'n' is type int32, but received BSON type %s", element.Value().Type)
}
}
}
return dr, nil
}
// NewDelete constructs and returns a new Delete.
func NewDelete(deletes ...bsoncore.Document) *Delete {
return &Delete{
deletes: deletes,
}
}
// Result returns the result of executing this operation.
func (d *Delete) Result() DeleteResult { return d.result }
func (d *Delete) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
d.result, err = buildDeleteResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (d *Delete) Execute(ctx context.Context) error {
if d.deployment == nil {
return errors.New("the Delete operation must have a Deployment set before Execute can be called")
}
batches := &driver.Batches{
Identifier: "deletes",
Documents: d.deletes,
Ordered: d.ordered,
}
return driver.Operation{
CommandFn: d.command,
ProcessResponseFn: d.processResponse,
Batches: batches,
RetryMode: d.retry,
RetryType: driver.RetryWrite,
Client: d.session,
Clock: d.clock,
CommandMonitor: d.monitor,
Database: d.database,
Deployment: d.deployment,
Selector: d.selector,
WriteConcern: d.writeConcern,
}.Execute(ctx, nil)
}
func (d *Delete) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "delete", d.collection)
if d.ordered != nil {
dst = bsoncore.AppendBooleanElement(dst, "ordered", *d.ordered)
}
return dst, nil
}
// Deletes adds documents to this operation that will be used to determine what documents to delete when this operation
// is executed. These documents should have the form {q: <query>, limit: <integer limit>, collation: <document>}. The
// collation field is optional. If limit is 0, there will be no limit on the number of documents deleted.
func (d *Delete) Deletes(deletes ...bsoncore.Document) *Delete {
if d == nil {
d = new(Delete)
}
d.deletes = deletes
return d
}
// Ordered sets ordered. If true, when a write fails, the operation will return the error, when
// false write failures do not stop execution of the operation.
func (d *Delete) Ordered(ordered bool) *Delete {
if d == nil {
d = new(Delete)
}
d.ordered = &ordered
return d
}
// Session sets the session for this operation.
func (d *Delete) Session(session *session.Client) *Delete {
if d == nil {
d = new(Delete)
}
d.session = session
return d
}
// ClusterClock sets the cluster clock for this operation.
func (d *Delete) ClusterClock(clock *session.ClusterClock) *Delete {
if d == nil {
d = new(Delete)
}
d.clock = clock
return d
}
// Collection sets the collection that this command will run against.
func (d *Delete) Collection(collection string) *Delete {
if d == nil {
d = new(Delete)
}
d.collection = collection
return d
}
// CommandMonitor sets the monitor to use for APM events.
func (d *Delete) CommandMonitor(monitor *event.CommandMonitor) *Delete {
if d == nil {
d = new(Delete)
}
d.monitor = monitor
return d
}
// Database sets the database to run this operation against.
func (d *Delete) Database(database string) *Delete {
if d == nil {
d = new(Delete)
}
d.database = database
return d
}
// Deployment sets the deployment to use for this operation.
func (d *Delete) Deployment(deployment driver.Deployment) *Delete {
if d == nil {
d = new(Delete)
}
d.deployment = deployment
return d
}
// ServerSelector sets the selector used to retrieve a server.
func (d *Delete) ServerSelector(selector description.ServerSelector) *Delete {
if d == nil {
d = new(Delete)
}
d.selector = selector
return d
}
// WriteConcern sets the write concern for this operation.
func (d *Delete) WriteConcern(writeConcern *writeconcern.WriteConcern) *Delete {
if d == nil {
d = new(Delete)
}
d.writeConcern = writeConcern
return d
}
// Retry enables retryable writes for this operation. Retries are not handled automatically,
// instead a boolean is returned from Execute and SelectAndExecute that indicates if the
// operation can be retried. Retrying is handled by calling RetryExecute.
func (d *Delete) Retry(retry driver.RetryMode) *Delete {
if d == nil {
d = new(Delete)
}
d.retry = &retry
return d
}

View File

@@ -0,0 +1,38 @@
version = 0
name = "Delete"
documentation = "Delete performs a delete operation"
[properties]
enabled = ["write concern"]
retryable = {mode = "once per command", type = "writes"}
batches = "deletes"
[command]
name = "delete"
parameter = "collection"
[request.deletes]
type = "document"
slice = true
constructor = true
variadic = true
required = true
documentation = """
Deletes adds documents to this operation that will be used to determine what documents to delete when this operation
is executed. These documents should have the form {q: <query>, limit: <integer limit>, collation: <document>}. The
collation field is optional. If limit is 0, there will be no limit on the number of documents deleted.\
"""
[request.ordered]
type = "boolean"
documentation = """
Ordered sets ordered. If true, when a write fails, the operation will return the error, when
false write failures do not stop execution of the operation.\
"""
[response]
name = "DeleteResult"
[response.field.n]
type = "int32"
documentation = "Number of documents successfully deleted."

View File

@@ -0,0 +1,248 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"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/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// Distinct performs a distinct operation.
type Distinct struct {
collation bsoncore.Document
key *string
maxTimeMS *int64
query bsoncore.Document
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
readConcern *readconcern.ReadConcern
readPreference *readpref.ReadPref
selector description.ServerSelector
result DistinctResult
}
type DistinctResult struct {
// The distinct values for the field.
Values bsoncore.Value
}
func buildDistinctResult(response bsoncore.Document, srvr driver.Server) (DistinctResult, error) {
elements, err := response.Elements()
if err != nil {
return DistinctResult{}, err
}
dr := DistinctResult{}
for _, element := range elements {
switch element.Key() {
case "values":
dr.Values = element.Value()
}
}
return dr, nil
}
// NewDistinct constructs and returns a new Distinct.
func NewDistinct(key string, query bsoncore.Document) *Distinct {
return &Distinct{
key: &key,
query: query,
}
}
// Result returns the result of executing this operation.
func (d *Distinct) Result() DistinctResult { return d.result }
func (d *Distinct) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
d.result, err = buildDistinctResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (d *Distinct) Execute(ctx context.Context) error {
if d.deployment == nil {
return errors.New("the Distinct operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: d.command,
ProcessResponseFn: d.processResponse,
Client: d.session,
Clock: d.clock,
CommandMonitor: d.monitor,
Database: d.database,
Deployment: d.deployment,
ReadConcern: d.readConcern,
ReadPreference: d.readPreference,
Selector: d.selector,
}.Execute(ctx, nil)
}
func (d *Distinct) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "distinct", d.collection)
if d.collation != nil {
if desc.WireVersion == nil || !desc.WireVersion.Includes(5) {
return nil, errors.New("the 'collation' command parameter requires a minimum server wire version of 5")
}
dst = bsoncore.AppendDocumentElement(dst, "collation", d.collation)
}
if d.key != nil {
dst = bsoncore.AppendStringElement(dst, "key", *d.key)
}
if d.maxTimeMS != nil {
dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", *d.maxTimeMS)
}
if d.query != nil {
dst = bsoncore.AppendDocumentElement(dst, "query", d.query)
}
return dst, nil
}
// Collation specifies a collation to be used.
func (d *Distinct) Collation(collation bsoncore.Document) *Distinct {
if d == nil {
d = new(Distinct)
}
d.collation = collation
return d
}
// Key specifies which field to return distinct values for.
func (d *Distinct) Key(key string) *Distinct {
if d == nil {
d = new(Distinct)
}
d.key = &key
return d
}
// MaxTimeMS specifies the maximum amount of time to allow the query to run.
func (d *Distinct) MaxTimeMS(maxTimeMS int64) *Distinct {
if d == nil {
d = new(Distinct)
}
d.maxTimeMS = &maxTimeMS
return d
}
// Query specifies which documents to return distinct values from.
func (d *Distinct) Query(query bsoncore.Document) *Distinct {
if d == nil {
d = new(Distinct)
}
d.query = query
return d
}
// Session sets the session for this operation.
func (d *Distinct) Session(session *session.Client) *Distinct {
if d == nil {
d = new(Distinct)
}
d.session = session
return d
}
// ClusterClock sets the cluster clock for this operation.
func (d *Distinct) ClusterClock(clock *session.ClusterClock) *Distinct {
if d == nil {
d = new(Distinct)
}
d.clock = clock
return d
}
// Collection sets the collection that this command will run against.
func (d *Distinct) Collection(collection string) *Distinct {
if d == nil {
d = new(Distinct)
}
d.collection = collection
return d
}
// CommandMonitor sets the monitor to use for APM events.
func (d *Distinct) CommandMonitor(monitor *event.CommandMonitor) *Distinct {
if d == nil {
d = new(Distinct)
}
d.monitor = monitor
return d
}
// Database sets the database to run this operation against.
func (d *Distinct) Database(database string) *Distinct {
if d == nil {
d = new(Distinct)
}
d.database = database
return d
}
// Deployment sets the deployment to use for this operation.
func (d *Distinct) Deployment(deployment driver.Deployment) *Distinct {
if d == nil {
d = new(Distinct)
}
d.deployment = deployment
return d
}
// ReadConcern specifies the read concern for this operation.
func (d *Distinct) ReadConcern(readConcern *readconcern.ReadConcern) *Distinct {
if d == nil {
d = new(Distinct)
}
d.readConcern = readConcern
return d
}
// ReadPreference set the read prefernce used with this operation.
func (d *Distinct) ReadPreference(readPreference *readpref.ReadPref) *Distinct {
if d == nil {
d = new(Distinct)
}
d.readPreference = readPreference
return d
}
// ServerSelector sets the selector used to retrieve a server.
func (d *Distinct) ServerSelector(selector description.ServerSelector) *Distinct {
if d == nil {
d = new(Distinct)
}
d.selector = selector
return d
}

View File

@@ -0,0 +1,36 @@
version = 0
name = "Distinct"
documentation = "Distinct performs a distinct operation."
[properties]
enabled = ["read concern", "read preference"]
[command]
name = "distinct"
parameter = "collection"
[request.key]
type = "string"
constructor = true
documentation = "Key specifies which field to return distinct values for."
[request.query]
type = "document"
constructor = true
documentation = "Query specifies which documents to return distinct values from."
[request.maxTimeMS]
type = "int64"
documentation = "MaxTimeMS specifies the maximum amount of time to allow the query to run."
[request.collation]
type = "document"
minWireVersionRequired = 5
documentation = "Collation specifies a collation to be used."
[response]
name = "DistinctResult"
[response.field.values]
type = "value"
documentation = "The distinct values for the field."

View File

@@ -0,0 +1,186 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// DropCollection performs a drop operation.
type DropCollection struct {
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
result DropCollectionResult
}
type DropCollectionResult struct {
// The number of indexes in the dropped collection.
NIndexesWas int32
// The namespace of the dropped collection.
Ns string
}
func buildDropCollectionResult(response bsoncore.Document, srvr driver.Server) (DropCollectionResult, error) {
elements, err := response.Elements()
if err != nil {
return DropCollectionResult{}, err
}
dcr := DropCollectionResult{}
for _, element := range elements {
switch element.Key() {
case "nIndexesWas":
var ok bool
dcr.NIndexesWas, ok = element.Value().AsInt32OK()
if !ok {
err = fmt.Errorf("response field 'nIndexesWas' is type int32, but received BSON type %s", element.Value().Type)
}
case "ns":
var ok bool
dcr.Ns, ok = element.Value().StringValueOK()
if !ok {
err = fmt.Errorf("response field 'ns' is type string, but received BSON type %s", element.Value().Type)
}
}
}
return dcr, nil
}
// NewDropCollection constructs and returns a new DropCollection.
func NewDropCollection() *DropCollection {
return &DropCollection{}
}
// Result returns the result of executing this operation.
func (dc *DropCollection) Result() DropCollectionResult { return dc.result }
func (dc *DropCollection) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
dc.result, err = buildDropCollectionResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (dc *DropCollection) Execute(ctx context.Context) error {
if dc.deployment == nil {
return errors.New("the DropCollection operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: dc.command,
ProcessResponseFn: dc.processResponse,
Client: dc.session,
Clock: dc.clock,
CommandMonitor: dc.monitor,
Database: dc.database,
Deployment: dc.deployment,
Selector: dc.selector,
WriteConcern: dc.writeConcern,
}.Execute(ctx, nil)
}
func (dc *DropCollection) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "drop", dc.collection)
return dst, nil
}
// Session sets the session for this operation.
func (dc *DropCollection) Session(session *session.Client) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.session = session
return dc
}
// ClusterClock sets the cluster clock for this operation.
func (dc *DropCollection) ClusterClock(clock *session.ClusterClock) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.clock = clock
return dc
}
// Collection sets the collection that this command will run against.
func (dc *DropCollection) Collection(collection string) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.collection = collection
return dc
}
// CommandMonitor sets the monitor to use for APM events.
func (dc *DropCollection) CommandMonitor(monitor *event.CommandMonitor) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.monitor = monitor
return dc
}
// Database sets the database to run this operation against.
func (dc *DropCollection) Database(database string) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.database = database
return dc
}
// Deployment sets the deployment to use for this operation.
func (dc *DropCollection) Deployment(deployment driver.Deployment) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.deployment = deployment
return dc
}
// ServerSelector sets the selector used to retrieve a server.
func (dc *DropCollection) ServerSelector(selector description.ServerSelector) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.selector = selector
return dc
}
// WriteConcern sets the write concern for this operation.
func (dc *DropCollection) WriteConcern(writeConcern *writeconcern.WriteConcern) *DropCollection {
if dc == nil {
dc = new(DropCollection)
}
dc.writeConcern = writeConcern
return dc
}

View File

@@ -0,0 +1,21 @@
version = 0
name = "DropCollection"
documentation = "DropCollection performs a drop operation."
[command]
name = "drop"
parameter = "collection"
[properties]
enabled = ["write concern"]
[response]
name = "DropCollectionResult"
[response.field.ns]
type = "string"
documentation = "The namespace of the dropped collection."
[response.field.nIndexesWas]
type = "int32"
documentation = "The number of indexes in the dropped collection."

View File

@@ -0,0 +1,168 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// DropDatabase performs a dropDatabase operation
type DropDatabase struct {
session *session.Client
clock *session.ClusterClock
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
result DropDatabaseResult
}
type DropDatabaseResult struct {
// The dropped database.
Dropped string
}
func buildDropDatabaseResult(response bsoncore.Document, srvr driver.Server) (DropDatabaseResult, error) {
elements, err := response.Elements()
if err != nil {
return DropDatabaseResult{}, err
}
ddr := DropDatabaseResult{}
for _, element := range elements {
switch element.Key() {
case "dropped":
var ok bool
ddr.Dropped, ok = element.Value().StringValueOK()
if !ok {
err = fmt.Errorf("response field 'dropped' is type string, but received BSON type %s", element.Value().Type)
}
}
}
return ddr, nil
}
// NewDropDatabase constructs and returns a new DropDatabase.
func NewDropDatabase() *DropDatabase {
return &DropDatabase{}
}
// Result returns the result of executing this operation.
func (dd *DropDatabase) Result() DropDatabaseResult { return dd.result }
func (dd *DropDatabase) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
dd.result, err = buildDropDatabaseResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (dd *DropDatabase) Execute(ctx context.Context) error {
if dd.deployment == nil {
return errors.New("the DropDatabase operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: dd.command,
ProcessResponseFn: dd.processResponse,
Client: dd.session,
Clock: dd.clock,
CommandMonitor: dd.monitor,
Database: dd.database,
Deployment: dd.deployment,
Selector: dd.selector,
WriteConcern: dd.writeConcern,
}.Execute(ctx, nil)
}
func (dd *DropDatabase) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendInt32Element(dst, "dropDatabase", 1)
return dst, nil
}
// Session sets the session for this operation.
func (dd *DropDatabase) Session(session *session.Client) *DropDatabase {
if dd == nil {
dd = new(DropDatabase)
}
dd.session = session
return dd
}
// ClusterClock sets the cluster clock for this operation.
func (dd *DropDatabase) ClusterClock(clock *session.ClusterClock) *DropDatabase {
if dd == nil {
dd = new(DropDatabase)
}
dd.clock = clock
return dd
}
// CommandMonitor sets the monitor to use for APM events.
func (dd *DropDatabase) CommandMonitor(monitor *event.CommandMonitor) *DropDatabase {
if dd == nil {
dd = new(DropDatabase)
}
dd.monitor = monitor
return dd
}
// Database sets the database to run this operation against.
func (dd *DropDatabase) Database(database string) *DropDatabase {
if dd == nil {
dd = new(DropDatabase)
}
dd.database = database
return dd
}
// Deployment sets the deployment to use for this operation.
func (dd *DropDatabase) Deployment(deployment driver.Deployment) *DropDatabase {
if dd == nil {
dd = new(DropDatabase)
}
dd.deployment = deployment
return dd
}
// ServerSelector sets the selector used to retrieve a server.
func (dd *DropDatabase) ServerSelector(selector description.ServerSelector) *DropDatabase {
if dd == nil {
dd = new(DropDatabase)
}
dd.selector = selector
return dd
}
// WriteConcern sets the write concern for this operation.
func (dd *DropDatabase) WriteConcern(writeConcern *writeconcern.WriteConcern) *DropDatabase {
if dd == nil {
dd = new(DropDatabase)
}
dd.writeConcern = writeConcern
return dd
}

View File

@@ -0,0 +1,18 @@
version = 0
name = "DropDatabase"
documentation = "DropDatabase performs a dropDatabase operation"
[properties]
enabled = ["write concern"]
disabled = ["collection"]
[command]
name = "dropDatabase"
parameter = "database"
[response]
name = "DropDatabaseResult"
[response.field.dropped]
type = "string"
documentation = "The dropped database."

View File

@@ -0,0 +1,209 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// DropIndexes performs an dropIndexes operation.
type DropIndexes struct {
index *string
maxTimeMS *int64
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
result DropIndexesResult
}
type DropIndexesResult struct {
// Number of indexes that existed before the drop was executed.
NIndexesWas int32
}
func buildDropIndexesResult(response bsoncore.Document, srvr driver.Server) (DropIndexesResult, error) {
elements, err := response.Elements()
if err != nil {
return DropIndexesResult{}, err
}
dir := DropIndexesResult{}
for _, element := range elements {
switch element.Key() {
case "nIndexesWas":
var ok bool
dir.NIndexesWas, ok = element.Value().AsInt32OK()
if !ok {
err = fmt.Errorf("response field 'nIndexesWas' is type int32, but received BSON type %s", element.Value().Type)
}
}
}
return dir, nil
}
// NewDropIndexes constructs and returns a new DropIndexes.
func NewDropIndexes(index string) *DropIndexes {
return &DropIndexes{
index: &index,
}
}
// Result returns the result of executing this operation.
func (di *DropIndexes) Result() DropIndexesResult { return di.result }
func (di *DropIndexes) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
di.result, err = buildDropIndexesResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (di *DropIndexes) Execute(ctx context.Context) error {
if di.deployment == nil {
return errors.New("the DropIndexes operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: di.command,
ProcessResponseFn: di.processResponse,
Client: di.session,
Clock: di.clock,
CommandMonitor: di.monitor,
Database: di.database,
Deployment: di.deployment,
Selector: di.selector,
WriteConcern: di.writeConcern,
}.Execute(ctx, nil)
}
func (di *DropIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "dropIndexes", di.collection)
if di.index != nil {
dst = bsoncore.AppendStringElement(dst, "index", *di.index)
}
if di.maxTimeMS != nil {
dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", *di.maxTimeMS)
}
return dst, nil
}
// Index specifies the name of the index to drop. If '*' is specified, all indexes will be dropped.
//
func (di *DropIndexes) Index(index string) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.index = &index
return di
}
// MaxTimeMS specifies the maximum amount of time to allow the query to run.
func (di *DropIndexes) MaxTimeMS(maxTimeMS int64) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.maxTimeMS = &maxTimeMS
return di
}
// Session sets the session for this operation.
func (di *DropIndexes) Session(session *session.Client) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.session = session
return di
}
// ClusterClock sets the cluster clock for this operation.
func (di *DropIndexes) ClusterClock(clock *session.ClusterClock) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.clock = clock
return di
}
// Collection sets the collection that this command will run against.
func (di *DropIndexes) Collection(collection string) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.collection = collection
return di
}
// CommandMonitor sets the monitor to use for APM events.
func (di *DropIndexes) CommandMonitor(monitor *event.CommandMonitor) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.monitor = monitor
return di
}
// Database sets the database to run this operation against.
func (di *DropIndexes) Database(database string) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.database = database
return di
}
// Deployment sets the deployment to use for this operation.
func (di *DropIndexes) Deployment(deployment driver.Deployment) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.deployment = deployment
return di
}
// ServerSelector sets the selector used to retrieve a server.
func (di *DropIndexes) ServerSelector(selector description.ServerSelector) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.selector = selector
return di
}
// WriteConcern sets the write concern for this operation.
func (di *DropIndexes) WriteConcern(writeConcern *writeconcern.WriteConcern) *DropIndexes {
if di == nil {
di = new(DropIndexes)
}
di.writeConcern = writeConcern
return di
}

View File

@@ -0,0 +1,28 @@
version = 0
name = "DropIndexes"
documentation = "DropIndexes performs an dropIndexes operation."
[properties]
enabled = ["write concern"]
[command]
name = "dropIndexes"
parameter = "collection"
[request.index]
type = "string"
constructor = true
documentation = """
Index specifies the name of the index to drop. If '*' is specified, all indexes will be dropped.
"""
[request.maxTimeMS]
type = "int64"
documentation = "MaxTimeMS specifies the maximum amount of time to allow the query to run."
[response]
name = "DropIndexesResult"
[response.field.nIndexesWas]
type = "int32"
documentation = "Number of indexes that existed before the drop was executed."

View File

@@ -0,0 +1,469 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson/bsontype"
"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/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// Find performs a find operation.
type Find struct {
allowPartialResults *bool
awaitData *bool
batchSize *int32
collation bsoncore.Document
comment *string
filter bsoncore.Document
hint bsoncore.Value
limit *int64
max bsoncore.Document
maxTimeMS *int64
min bsoncore.Document
noCursorTimeout *bool
oplogReplay *bool
projection bsoncore.Document
returnKey *bool
showRecordID *bool
singleBatch *bool
skip *int64
snapshot *bool
sort bsoncore.Document
tailable *bool
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
readConcern *readconcern.ReadConcern
readPreference *readpref.ReadPref
selector description.ServerSelector
result driver.CursorResponse
}
// NewFind constructs and returns a new Find.
func NewFind(filter bsoncore.Document) *Find {
return &Find{
filter: filter,
}
}
// Result returns the result of executing this operation.
func (f *Find) Result(opts driver.CursorOptions) (*driver.BatchCursor, error) {
return driver.NewBatchCursor(f.result, f.session, f.clock, opts)
}
func (f *Find) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
f.result, err = driver.NewCursorResponse(response, srvr, desc)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (f *Find) Execute(ctx context.Context) error {
if f.deployment == nil {
return errors.New("the Find operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: f.command,
ProcessResponseFn: f.processResponse,
Client: f.session,
Clock: f.clock,
CommandMonitor: f.monitor,
Database: f.database,
Deployment: f.deployment,
ReadConcern: f.readConcern,
ReadPreference: f.readPreference,
Selector: f.selector,
Legacy: driver.LegacyFind,
}.Execute(ctx, nil)
}
func (f *Find) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "find", f.collection)
if f.allowPartialResults != nil {
dst = bsoncore.AppendBooleanElement(dst, "allowPartialResults", *f.allowPartialResults)
}
if f.awaitData != nil {
dst = bsoncore.AppendBooleanElement(dst, "awaitData", *f.awaitData)
}
if f.batchSize != nil {
dst = bsoncore.AppendInt32Element(dst, "batchSize", *f.batchSize)
}
if f.collation != nil {
if desc.WireVersion == nil || !desc.WireVersion.Includes(5) {
return nil, errors.New("the 'collation' command parameter requires a minimum server wire version of 5")
}
dst = bsoncore.AppendDocumentElement(dst, "collation", f.collation)
}
if f.comment != nil {
dst = bsoncore.AppendStringElement(dst, "comment", *f.comment)
}
if f.filter != nil {
dst = bsoncore.AppendDocumentElement(dst, "filter", f.filter)
}
if f.hint.Type != bsontype.Type(0) {
dst = bsoncore.AppendValueElement(dst, "hint", f.hint)
}
if f.limit != nil {
dst = bsoncore.AppendInt64Element(dst, "limit", *f.limit)
}
if f.max != nil {
dst = bsoncore.AppendDocumentElement(dst, "max", f.max)
}
if f.maxTimeMS != nil {
dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", *f.maxTimeMS)
}
if f.min != nil {
dst = bsoncore.AppendDocumentElement(dst, "min", f.min)
}
if f.noCursorTimeout != nil {
dst = bsoncore.AppendBooleanElement(dst, "noCursorTimeout", *f.noCursorTimeout)
}
if f.oplogReplay != nil {
dst = bsoncore.AppendBooleanElement(dst, "oplogReplay", *f.oplogReplay)
}
if f.projection != nil {
dst = bsoncore.AppendDocumentElement(dst, "projection", f.projection)
}
if f.returnKey != nil {
dst = bsoncore.AppendBooleanElement(dst, "returnKey", *f.returnKey)
}
if f.showRecordID != nil {
dst = bsoncore.AppendBooleanElement(dst, "showRecordId", *f.showRecordID)
}
if f.singleBatch != nil {
dst = bsoncore.AppendBooleanElement(dst, "singleBatch", *f.singleBatch)
}
if f.skip != nil {
dst = bsoncore.AppendInt64Element(dst, "skip", *f.skip)
}
if f.snapshot != nil {
dst = bsoncore.AppendBooleanElement(dst, "snapshot", *f.snapshot)
}
if f.sort != nil {
dst = bsoncore.AppendDocumentElement(dst, "sort", f.sort)
}
if f.tailable != nil {
dst = bsoncore.AppendBooleanElement(dst, "tailable", *f.tailable)
}
return dst, nil
}
// AllowPartialResults when true allows partial results to be returned if some shards are down.
func (f *Find) AllowPartialResults(allowPartialResults bool) *Find {
if f == nil {
f = new(Find)
}
f.allowPartialResults = &allowPartialResults
return f
}
// AwaitData when true makes a cursor block before returning when no data is available.
func (f *Find) AwaitData(awaitData bool) *Find {
if f == nil {
f = new(Find)
}
f.awaitData = &awaitData
return f
}
// BatchSize specifies the number of documents to return in every batch.
func (f *Find) BatchSize(batchSize int32) *Find {
if f == nil {
f = new(Find)
}
f.batchSize = &batchSize
return f
}
// Collation specifies a collation to be used.
func (f *Find) Collation(collation bsoncore.Document) *Find {
if f == nil {
f = new(Find)
}
f.collation = collation
return f
}
// Comment sets a string to help trace an operation.
func (f *Find) Comment(comment string) *Find {
if f == nil {
f = new(Find)
}
f.comment = &comment
return f
}
// Filter determines what results are returned from find.
func (f *Find) Filter(filter bsoncore.Document) *Find {
if f == nil {
f = new(Find)
}
f.filter = filter
return f
}
// Hint specifies the index to use.
func (f *Find) Hint(hint bsoncore.Value) *Find {
if f == nil {
f = new(Find)
}
f.hint = hint
return f
}
// Limit sets a limit on the number of documents to return.
func (f *Find) Limit(limit int64) *Find {
if f == nil {
f = new(Find)
}
f.limit = &limit
return f
}
// Max sets an exclusive upper bound for a specific index.
func (f *Find) Max(max bsoncore.Document) *Find {
if f == nil {
f = new(Find)
}
f.max = max
return f
}
// MaxTimeMS specifies the maximum amount of time to allow the query to run.
func (f *Find) MaxTimeMS(maxTimeMS int64) *Find {
if f == nil {
f = new(Find)
}
f.maxTimeMS = &maxTimeMS
return f
}
// Min sets an inclusive lower bound for a specific index.
func (f *Find) Min(min bsoncore.Document) *Find {
if f == nil {
f = new(Find)
}
f.min = min
return f
}
// NoCursorTimeout when true prevents cursor from timing out after an inactivity period.
func (f *Find) NoCursorTimeout(noCursorTimeout bool) *Find {
if f == nil {
f = new(Find)
}
f.noCursorTimeout = &noCursorTimeout
return f
}
// OplogReplay when true replays a replica set's oplog.
func (f *Find) OplogReplay(oplogReplay bool) *Find {
if f == nil {
f = new(Find)
}
f.oplogReplay = &oplogReplay
return f
}
// Project limits the fields returned for all documents.
func (f *Find) Projection(projection bsoncore.Document) *Find {
if f == nil {
f = new(Find)
}
f.projection = projection
return f
}
// ReturnKey when true returns index keys for all result documents.
func (f *Find) ReturnKey(returnKey bool) *Find {
if f == nil {
f = new(Find)
}
f.returnKey = &returnKey
return f
}
// ShowRecordID when true adds a $recordId field with the record identifier to returned documents.
func (f *Find) ShowRecordID(showRecordID bool) *Find {
if f == nil {
f = new(Find)
}
f.showRecordID = &showRecordID
return f
}
// SingleBatch specifies whether the results should be returned in a single batch.
func (f *Find) SingleBatch(singleBatch bool) *Find {
if f == nil {
f = new(Find)
}
f.singleBatch = &singleBatch
return f
}
// Skip specifies the number of documents to skip before returning.
func (f *Find) Skip(skip int64) *Find {
if f == nil {
f = new(Find)
}
f.skip = &skip
return f
}
// Snapshot prevents the cursor from returning a document more than once because of an intervening write operation.
func (f *Find) Snapshot(snapshot bool) *Find {
if f == nil {
f = new(Find)
}
f.snapshot = &snapshot
return f
}
// Sort specifies the order in which to return results.
func (f *Find) Sort(sort bsoncore.Document) *Find {
if f == nil {
f = new(Find)
}
f.sort = sort
return f
}
// Tailable keeps a cursor open and resumable after the last data has been retrieved.
func (f *Find) Tailable(tailable bool) *Find {
if f == nil {
f = new(Find)
}
f.tailable = &tailable
return f
}
// Session sets the session for this operation.
func (f *Find) Session(session *session.Client) *Find {
if f == nil {
f = new(Find)
}
f.session = session
return f
}
// ClusterClock sets the cluster clock for this operation.
func (f *Find) ClusterClock(clock *session.ClusterClock) *Find {
if f == nil {
f = new(Find)
}
f.clock = clock
return f
}
// Collection sets the collection that this command will run against.
func (f *Find) Collection(collection string) *Find {
if f == nil {
f = new(Find)
}
f.collection = collection
return f
}
// CommandMonitor sets the monitor to use for APM events.
func (f *Find) CommandMonitor(monitor *event.CommandMonitor) *Find {
if f == nil {
f = new(Find)
}
f.monitor = monitor
return f
}
// Database sets the database to run this operation against.
func (f *Find) Database(database string) *Find {
if f == nil {
f = new(Find)
}
f.database = database
return f
}
// Deployment sets the deployment to use for this operation.
func (f *Find) Deployment(deployment driver.Deployment) *Find {
if f == nil {
f = new(Find)
}
f.deployment = deployment
return f
}
// ReadConcern specifies the read concern for this operation.
func (f *Find) ReadConcern(readConcern *readconcern.ReadConcern) *Find {
if f == nil {
f = new(Find)
}
f.readConcern = readConcern
return f
}
// ReadPreference set the read prefernce used with this operation.
func (f *Find) ReadPreference(readPreference *readpref.ReadPref) *Find {
if f == nil {
f = new(Find)
}
f.readPreference = readPreference
return f
}
// ServerSelector sets the selector used to retrieve a server.
func (f *Find) ServerSelector(selector description.ServerSelector) *Find {
if f == nil {
f = new(Find)
}
f.selector = selector
return f
}

View File

@@ -0,0 +1,99 @@
version = 0
name = "Find"
documentation = "Find performs a find operation."
response.type = "batch cursor"
[properties]
enabled = ["collection", "read concern", "read preference", "command monitor", "client session", "cluster clock"]
legacy = "find"
[command]
name = "find"
parameter = "collection"
[request.filter]
type = "document"
constructor = true
documentation = "Filter determines what results are returned from find."
[request.sort]
type = "document"
documentation = "Sort specifies the order in which to return results."
[request.projection]
type = "document"
documentation = "Project limits the fields returned for all documents."
[request.hint]
type = "value"
documentation = "Hint specifies the index to use."
[request.skip]
type = "int64"
documentation = "Skip specifies the number of documents to skip before returning."
[request.limit]
type = "int64"
documentation = "Limit sets a limit on the number of documents to return."
[request.batchSize]
type = "int32"
documentation = "BatchSize specifies the number of documents to return in every batch."
[request.singleBatch]
type = "boolean"
documentation = "SingleBatch specifies whether the results should be returned in a single batch."
[request.comment]
type = "string"
documentation = "Comment sets a string to help trace an operation."
[request.maxTimeMS]
type = "int64"
documentation = "MaxTimeMS specifies the maximum amount of time to allow the query to run."
[request.max]
type = "document"
documentation = "Max sets an exclusive upper bound for a specific index."
[request.min]
type = "document"
documentation = "Min sets an inclusive lower bound for a specific index."
[request.returnKey]
type = "boolean"
documentation = "ReturnKey when true returns index keys for all result documents."
[request.showRecordID]
type = "boolean"
documentation = "ShowRecordID when true adds a $recordId field with the record identifier to returned documents."
keyName = "showRecordId"
[request.oplogReplay]
type = "boolean"
documentation = "OplogReplay when true replays a replica set's oplog."
[request.noCursorTimeout]
type = "boolean"
documentation = "NoCursorTimeout when true prevents cursor from timing out after an inactivity period."
[request.tailable]
type = "boolean"
documentation = "Tailable keeps a cursor open and resumable after the last data has been retrieved."
[request.awaitData]
type = "boolean"
documentation = "AwaitData when true makes a cursor block before returning when no data is available."
[request.allowPartialResults]
type = "boolean"
documentation = "AllowPartialResults when true allows partial results to be returned if some shards are down."
[request.collation]
type = "document"
minWireVersionRequired = 5
documentation = "Collation specifies a collation to be used."
[request.snapshot]
type = "boolean"
documentation = "Snapshot prevents the cursor from returning a document more than once because of an intervening write operation."

View File

@@ -0,0 +1,395 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// FindAndModify performs a findAndModify operation.
type FindAndModify struct {
arrayFilters bsoncore.Document
bypassDocumentValidation *bool
collation bsoncore.Document
fields bsoncore.Document
maxTimeMS *int64
newDocument *bool
query bsoncore.Document
remove *bool
sort bsoncore.Document
update bsoncore.Document
upsert *bool
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
retry *driver.RetryMode
result FindAndModifyResult
}
type LastErrorObject struct {
// True if an update modified an existing document
UpdatedExisting bool
// Object ID of the upserted document.
Upserted interface{}
}
type FindAndModifyResult struct {
// Either the old or modified document, depending on the value of the new parameter.
Value bsoncore.Document
// Contains information about updates and upserts.
LastErrorObject LastErrorObject
}
func buildFindAndModifyResult(response bsoncore.Document, srvr driver.Server) (FindAndModifyResult, error) {
elements, err := response.Elements()
if err != nil {
return FindAndModifyResult{}, err
}
famr := FindAndModifyResult{}
for _, element := range elements {
switch element.Key() {
case "value":
var ok bool
famr.Value, ok = element.Value().DocumentOK()
if !ok {
err = fmt.Errorf("response field 'value' is type document, but received BSON type %s", element.Value().Type)
}
case "lastErrorObject":
valDoc, ok := element.Value().DocumentOK()
if !ok {
err = fmt.Errorf("response field 'lastErrorObject' is type document, but received BSON type %s", element.Value().Type)
break
}
var leo LastErrorObject
if err = bson.Unmarshal(valDoc, &leo); err != nil {
break
}
famr.LastErrorObject = leo
}
}
return famr, nil
}
// NewFindAndModify constructs and returns a new FindAndModify.
func NewFindAndModify(query bsoncore.Document) *FindAndModify {
return &FindAndModify{
query: query,
}
}
// Result returns the result of executing this operation.
func (fam *FindAndModify) Result() FindAndModifyResult { return fam.result }
func (fam *FindAndModify) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
fam.result, err = buildFindAndModifyResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (fam *FindAndModify) Execute(ctx context.Context) error {
if fam.deployment == nil {
return errors.New("the FindAndModify operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: fam.command,
ProcessResponseFn: fam.processResponse,
RetryMode: fam.retry,
RetryType: driver.RetryWrite,
Client: fam.session,
Clock: fam.clock,
CommandMonitor: fam.monitor,
Database: fam.database,
Deployment: fam.deployment,
Selector: fam.selector,
WriteConcern: fam.writeConcern,
}.Execute(ctx, nil)
}
func (fam *FindAndModify) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "findAndModify", fam.collection)
if fam.arrayFilters != nil {
if desc.WireVersion == nil || !desc.WireVersion.Includes(6) {
return nil, errors.New("the 'arrayFilters' command parameter requires a minimum server wire version of 6")
}
dst = bsoncore.AppendArrayElement(dst, "arrayFilters", fam.arrayFilters)
}
if fam.bypassDocumentValidation != nil {
dst = bsoncore.AppendBooleanElement(dst, "bypassDocumentValidation", *fam.bypassDocumentValidation)
}
if fam.collation != nil {
if desc.WireVersion == nil || !desc.WireVersion.Includes(5) {
return nil, errors.New("the 'collation' command parameter requires a minimum server wire version of 5")
}
dst = bsoncore.AppendDocumentElement(dst, "collation", fam.collation)
}
if fam.fields != nil {
dst = bsoncore.AppendDocumentElement(dst, "fields", fam.fields)
}
if fam.maxTimeMS != nil {
dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", *fam.maxTimeMS)
}
if fam.newDocument != nil {
dst = bsoncore.AppendBooleanElement(dst, "new", *fam.newDocument)
}
if fam.query != nil {
dst = bsoncore.AppendDocumentElement(dst, "query", fam.query)
}
if fam.remove != nil {
dst = bsoncore.AppendBooleanElement(dst, "remove", *fam.remove)
}
if fam.sort != nil {
dst = bsoncore.AppendDocumentElement(dst, "sort", fam.sort)
}
if fam.update != nil {
dst = bsoncore.AppendDocumentElement(dst, "update", fam.update)
}
if fam.upsert != nil {
dst = bsoncore.AppendBooleanElement(dst, "upsert", *fam.upsert)
}
return dst, nil
}
// ArrayFilters specifies an array of filter documents that determines which array elements to modify for an update operation on an array field.
func (fam *FindAndModify) ArrayFilters(arrayFilters bsoncore.Document) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.arrayFilters = arrayFilters
return fam
}
// BypassDocumentValidation specifies if document validation can be skipped when executing the operation.
func (fam *FindAndModify) BypassDocumentValidation(bypassDocumentValidation bool) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.bypassDocumentValidation = &bypassDocumentValidation
return fam
}
// Collation specifies a collation to be used.
func (fam *FindAndModify) Collation(collation bsoncore.Document) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.collation = collation
return fam
}
// Fields specifies a subset of fields to return.
func (fam *FindAndModify) Fields(fields bsoncore.Document) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.fields = fields
return fam
}
// MaxTimeMS specifies the maximum amount of time to allow the operation to run.
func (fam *FindAndModify) MaxTimeMS(maxTimeMS int64) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.maxTimeMS = &maxTimeMS
return fam
}
// NewDocument specifies whether to return the modified document or the original. Defaults to false (return original).
func (fam *FindAndModify) NewDocument(newDocument bool) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.newDocument = &newDocument
return fam
}
// Query specifies the selection criteria for the modification.
func (fam *FindAndModify) Query(query bsoncore.Document) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.query = query
return fam
}
// Remove specifies that the matched document should be removed. Defaults to false.
func (fam *FindAndModify) Remove(remove bool) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.remove = &remove
return fam
}
// Sort determines which document the operation modifies if the query matches multiple documents.The first document matched by the sort order will be modified.
//
func (fam *FindAndModify) Sort(sort bsoncore.Document) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.sort = sort
return fam
}
// Update specifies the update document to perform on the matched document.
func (fam *FindAndModify) Update(update bsoncore.Document) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.update = update
return fam
}
// Upsert specifies whether or not to create a new document if no documents match the query when doing an update. Defaults to false.
func (fam *FindAndModify) Upsert(upsert bool) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.upsert = &upsert
return fam
}
// Session sets the session for this operation.
func (fam *FindAndModify) Session(session *session.Client) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.session = session
return fam
}
// ClusterClock sets the cluster clock for this operation.
func (fam *FindAndModify) ClusterClock(clock *session.ClusterClock) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.clock = clock
return fam
}
// Collection sets the collection that this command will run against.
func (fam *FindAndModify) Collection(collection string) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.collection = collection
return fam
}
// CommandMonitor sets the monitor to use for APM events.
func (fam *FindAndModify) CommandMonitor(monitor *event.CommandMonitor) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.monitor = monitor
return fam
}
// Database sets the database to run this operation against.
func (fam *FindAndModify) Database(database string) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.database = database
return fam
}
// Deployment sets the deployment to use for this operation.
func (fam *FindAndModify) Deployment(deployment driver.Deployment) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.deployment = deployment
return fam
}
// ServerSelector sets the selector used to retrieve a server.
func (fam *FindAndModify) ServerSelector(selector description.ServerSelector) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.selector = selector
return fam
}
// WriteConcern sets the write concern for this operation.
func (fam *FindAndModify) WriteConcern(writeConcern *writeconcern.WriteConcern) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.writeConcern = writeConcern
return fam
}
// Retry enables retryable writes for this operation. Retries are not handled automatically,
// instead a boolean is returned from Execute and SelectAndExecute that indicates if the
// operation can be retried. Retrying is handled by calling RetryExecute.
func (fam *FindAndModify) Retry(retry driver.RetryMode) *FindAndModify {
if fam == nil {
fam = new(FindAndModify)
}
fam.retry = &retry
return fam
}

View File

@@ -0,0 +1,68 @@
version = 0
name = "FindAndModify"
documentation = "FindAndModify performs a findAndModify operation."
[properties]
enabled = ["write concern"]
retryable = {mode = "once", type = "writes"}
[command]
name = "findAndModify"
parameter = "collection"
[request.query]
type = "document"
constructor = true
documentation = "Query specifies the selection criteria for the modification."
[request.sort]
type = "document"
documentation = """
Sort determines which document the operation modifies if the query matches multiple documents.\
The first document matched by the sort order will be modified.
"""
[request.remove]
type = "boolean"
documentation = "Remove specifies that the matched document should be removed. Defaults to false."
[request.update]
type = "document"
documentation = "Update specifies the update document to perform on the matched document."
[request.newDocument]
type = "boolean"
documentation = "NewDocument specifies whether to return the modified document or the original. Defaults to false (return original)."
[request.fields]
type = "document"
documentation = "Fields specifies a subset of fields to return."
[request.upsert]
type = "boolean"
documentation = "Upsert specifies whether or not to create a new document if no documents match the query when doing an update. Defaults to false."
[request.bypassDocumentValidation]
type = "boolean"
documentation = "BypassDocumentValidation specifies if document validation can be skipped when executing the operation."
[request.maxTimeMS]
type = "int64"
documentation = "MaxTimeMS specifies the maximum amount of time to allow the operation to run."
[request.collation]
type = "document"
minWireVersionRequired = 5
documentation = "Collation specifies a collation to be used."
[request.arrayFilters]
type = "array"
minWireVersionRequired = 6
documentation = "ArrayFilters specifies an array of filter documents that determines which array elements to modify for an update operation on an array field."
[response]
name = "FindAndModifyResult"
[response.field.value]
type = "document"
documentation = "Either the old or modified document, depending on the value of the new parameter."

View File

@@ -0,0 +1,243 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// Insert performs an insert operation.
type Insert struct {
bypassDocumentValidation *bool
documents []bsoncore.Document
ordered *bool
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
retry *driver.RetryMode
result InsertResult
}
type InsertResult struct {
// Number of documents successfully inserted.
N int32
}
func buildInsertResult(response bsoncore.Document, srvr driver.Server) (InsertResult, error) {
elements, err := response.Elements()
if err != nil {
return InsertResult{}, err
}
ir := InsertResult{}
for _, element := range elements {
switch element.Key() {
case "n":
var ok bool
ir.N, ok = element.Value().AsInt32OK()
if !ok {
err = fmt.Errorf("response field 'n' is type int32, but received BSON type %s", element.Value().Type)
}
}
}
return ir, nil
}
// NewInsert constructs and returns a new Insert.
func NewInsert(documents ...bsoncore.Document) *Insert {
return &Insert{
documents: documents,
}
}
// Result returns the result of executing this operation.
func (i *Insert) Result() InsertResult { return i.result }
func (i *Insert) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
i.result, err = buildInsertResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (i *Insert) Execute(ctx context.Context) error {
if i.deployment == nil {
return errors.New("the Insert operation must have a Deployment set before Execute can be called")
}
batches := &driver.Batches{
Identifier: "documents",
Documents: i.documents,
Ordered: i.ordered,
}
return driver.Operation{
CommandFn: i.command,
ProcessResponseFn: i.processResponse,
Batches: batches,
RetryMode: i.retry,
RetryType: driver.RetryWrite,
Client: i.session,
Clock: i.clock,
CommandMonitor: i.monitor,
Database: i.database,
Deployment: i.deployment,
Selector: i.selector,
WriteConcern: i.writeConcern,
}.Execute(ctx, nil)
}
func (i *Insert) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "insert", i.collection)
if i.bypassDocumentValidation != nil && (desc.WireVersion != nil && desc.WireVersion.Includes(4)) {
dst = bsoncore.AppendBooleanElement(dst, "bypassDocumentValidation", *i.bypassDocumentValidation)
}
if i.ordered != nil {
dst = bsoncore.AppendBooleanElement(dst, "ordered", *i.ordered)
}
return dst, nil
}
// BypassDocumentValidation allows the operation to opt-out of document level validation. Valid
// for server versions >= 3.2. For servers < 3.2, this setting is ignored.
func (i *Insert) BypassDocumentValidation(bypassDocumentValidation bool) *Insert {
if i == nil {
i = new(Insert)
}
i.bypassDocumentValidation = &bypassDocumentValidation
return i
}
// Documents adds documents to this operation that will be inserted when this operation is
// executed.
func (i *Insert) Documents(documents ...bsoncore.Document) *Insert {
if i == nil {
i = new(Insert)
}
i.documents = documents
return i
}
// Ordered sets ordered. If true, when a write fails, the operation will return the error, when
// false write failures do not stop execution of the operation.
func (i *Insert) Ordered(ordered bool) *Insert {
if i == nil {
i = new(Insert)
}
i.ordered = &ordered
return i
}
// Session sets the session for this operation.
func (i *Insert) Session(session *session.Client) *Insert {
if i == nil {
i = new(Insert)
}
i.session = session
return i
}
// ClusterClock sets the cluster clock for this operation.
func (i *Insert) ClusterClock(clock *session.ClusterClock) *Insert {
if i == nil {
i = new(Insert)
}
i.clock = clock
return i
}
// Collection sets the collection that this command will run against.
func (i *Insert) Collection(collection string) *Insert {
if i == nil {
i = new(Insert)
}
i.collection = collection
return i
}
// CommandMonitor sets the monitor to use for APM events.
func (i *Insert) CommandMonitor(monitor *event.CommandMonitor) *Insert {
if i == nil {
i = new(Insert)
}
i.monitor = monitor
return i
}
// Database sets the database to run this operation against.
func (i *Insert) Database(database string) *Insert {
if i == nil {
i = new(Insert)
}
i.database = database
return i
}
// Deployment sets the deployment to use for this operation.
func (i *Insert) Deployment(deployment driver.Deployment) *Insert {
if i == nil {
i = new(Insert)
}
i.deployment = deployment
return i
}
// ServerSelector sets the selector used to retrieve a server.
func (i *Insert) ServerSelector(selector description.ServerSelector) *Insert {
if i == nil {
i = new(Insert)
}
i.selector = selector
return i
}
// WriteConcern sets the write concern for this operation.
func (i *Insert) WriteConcern(writeConcern *writeconcern.WriteConcern) *Insert {
if i == nil {
i = new(Insert)
}
i.writeConcern = writeConcern
return i
}
// Retry enables retryable writes for this operation. Retries are not handled automatically,
// instead a boolean is returned from Execute and SelectAndExecute that indicates if the
// operation can be retried. Retrying is handled by calling RetryExecute.
func (i *Insert) Retry(retry driver.RetryMode) *Insert {
if i == nil {
i = new(Insert)
}
i.retry = &retry
return i
}

View File

@@ -0,0 +1,45 @@
version = 0
name = "Insert"
documentation = "Insert performs an insert operation."
[properties]
enabled = ["write concern"]
retryable = {mode = "once per command", type = "writes"}
batches = "documents"
[command]
name = "insert"
parameter = "collection"
[request.documents]
type = "document"
slice = true
constructor = true
variadic = true
required = true
documentation = """
Documents adds documents to this operation that will be inserted when this operation is
executed.\
"""
[request.ordered]
type = "boolean"
documentation = """
Ordered sets ordered. If true, when a write fails, the operation will return the error, when
false write failures do not stop execution of the operation.\
"""
[request.bypassDocumentValidation]
type = "boolean"
minWireVersion = 4
documentation = """
BypassDocumentValidation allows the operation to opt-out of document level validation. Valid
for server versions >= 3.2. For servers < 3.2, this setting is ignored.\
"""
[response]
name = "InsertResult"
[response.field.n]
type = "int32"
documentation = "Number of documents successfully inserted."

View File

@@ -0,0 +1,412 @@
package operation
import (
"context"
"errors"
"fmt"
"runtime"
"strconv"
"time"
"go.mongodb.org/mongo-driver/tag"
"go.mongodb.org/mongo-driver/version"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/address"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// IsMaster is used to run the isMaster handshake operation.
type IsMaster struct {
appname string
compressors []string
saslSupportedMechs string
d driver.Deployment
clock *session.ClusterClock
res bsoncore.Document
}
// NewIsMaster constructs an IsMaster.
func NewIsMaster() *IsMaster { return &IsMaster{} }
// AppName sets the application name in the client metadata sent in this operation.
func (im *IsMaster) AppName(appname string) *IsMaster {
im.appname = appname
return im
}
// ClusterClock sets the cluster clock for this operation.
func (im *IsMaster) ClusterClock(clock *session.ClusterClock) *IsMaster {
if im == nil {
im = new(IsMaster)
}
im.clock = clock
return im
}
// Compressors sets the compressors that can be used.
func (im *IsMaster) Compressors(compressors []string) *IsMaster {
im.compressors = compressors
return im
}
// SASLSupportedMechs retrieves the supported SASL mechanism for the given user when this operation
// is run.
func (im *IsMaster) SASLSupportedMechs(username string) *IsMaster {
im.saslSupportedMechs = username
return im
}
// Deployment sets the Deployment for this operation.
func (im *IsMaster) Deployment(d driver.Deployment) *IsMaster {
im.d = d
return im
}
// Result returns the result of executing this operaiton.
func (im *IsMaster) Result(addr address.Address) description.Server {
desc := description.Server{Addr: addr, CanonicalAddr: addr, LastUpdateTime: time.Now().UTC()}
elements, err := im.res.Elements()
if err != nil {
desc.LastError = err
return desc
}
var ok bool
var isReplicaSet, isMaster, hidden, secondary, arbiterOnly bool
var msg string
var version description.VersionRange
var hosts, passives, arbiters []string
for _, element := range elements {
switch element.Key() {
case "arbiters":
var err error
arbiters, err = im.decodeStringSlice(element, "arbiters")
if err != nil {
desc.LastError = err
return desc
}
case "arbiterOnly":
arbiterOnly, ok = element.Value().BooleanOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'arbiterOnly' to be a boolean but it's a BSON %s", element.Value().Type)
return desc
}
case "compression":
var err error
desc.Compression, err = im.decodeStringSlice(element, "compression")
if err != nil {
desc.LastError = err
return desc
}
case "electionId":
desc.ElectionID, ok = element.Value().ObjectIDOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'electionId' to be a objectID but it's a BSON %s", element.Value().Type)
return desc
}
case "hidden":
hidden, ok = element.Value().BooleanOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'hidden' to be a boolean but it's a BSON %s", element.Value().Type)
return desc
}
case "hosts":
var err error
hosts, err = im.decodeStringSlice(element, "hosts")
if err != nil {
desc.LastError = err
return desc
}
case "ismaster":
isMaster, ok = element.Value().BooleanOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'isMaster' to be a boolean but it's a BSON %s", element.Value().Type)
return desc
}
case "isreplicaset":
isReplicaSet, ok = element.Value().BooleanOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'isreplicaset' to be a boolean but it's a BSON %s", element.Value().Type)
return desc
}
case "lastWriteDate":
dt, ok := element.Value().DateTimeOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'lastWriteDate' to be a datetime but it's a BSON %s", element.Value().Type)
return desc
}
desc.LastWriteTime = time.Unix(dt/1000, dt%1000*1000000).UTC()
case "logicalSessionTimeoutMinutes":
i64, ok := element.Value().AsInt64OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'logicalSessionTimeoutMinutes' to be an integer but it's a BSON %s", element.Value().Type)
return desc
}
desc.SessionTimeoutMinutes = uint32(i64)
case "maxBsonObjectSize":
i64, ok := element.Value().AsInt64OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'maxBsonObjectSize' to be an integer but it's a BSON %s", element.Value().Type)
return desc
}
desc.MaxDocumentSize = uint32(i64)
case "maxMessageSizeBytes":
i64, ok := element.Value().AsInt64OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'maxMessageSizeBytes' to be an integer but it's a BSON %s", element.Value().Type)
return desc
}
desc.MaxMessageSize = uint32(i64)
case "maxWriteBatchSize":
i64, ok := element.Value().AsInt64OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'maxWriteBatchSize' to be an integer but it's a BSON %s", element.Value().Type)
return desc
}
desc.MaxBatchCount = uint32(i64)
case "me":
me, ok := element.Value().StringValueOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'me' to be a string but it's a BSON %s", element.Value().Type)
return desc
}
desc.CanonicalAddr = address.Address(me).Canonicalize()
case "maxWireVersion":
version.Max, ok = element.Value().AsInt32OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'maxWireVersion' to be an integer but it's a BSON %s", element.Value().Type)
return desc
}
case "minWireVersion":
version.Min, ok = element.Value().AsInt32OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'minWireVersion' to be an integer but it's a BSON %s", element.Value().Type)
return desc
}
case "msg":
msg, ok = element.Value().StringValueOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'msg' to be a string but it's a BSON %s", element.Value().Type)
return desc
}
case "ok":
okay, ok := element.Value().AsInt32OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'ok' to be a boolean but it's a BSON %s", element.Value().Type)
return desc
}
if okay != 1 {
desc.LastError = errors.New("not ok")
return desc
}
case "passives":
var err error
passives, err = im.decodeStringSlice(element, "passives")
if err != nil {
desc.LastError = err
return desc
}
case "readOnly":
desc.ReadOnly, ok = element.Value().BooleanOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'readOnly' to be a boolean but it's a BSON %s", element.Value().Type)
return desc
}
case "saslSupportedMechs":
var err error
desc.SaslSupportedMechs, err = im.decodeStringSlice(element, "saslSupportedMechs")
if err != nil {
desc.LastError = err
return desc
}
case "secondary":
secondary, ok = element.Value().BooleanOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'secondary' to be a boolean but it's a BSON %s", element.Value().Type)
return desc
}
case "setName":
desc.SetName, ok = element.Value().StringValueOK()
if !ok {
desc.LastError = fmt.Errorf("expected 'setName' to be a string but it's a BSON %s", element.Value().Type)
return desc
}
case "setVersion":
i64, ok := element.Value().AsInt64OK()
if !ok {
desc.LastError = fmt.Errorf("expected 'setVersion' to be an integer but it's a BSON %s", element.Value().Type)
return desc
}
desc.SetVersion = uint32(i64)
case "tags":
m, err := im.decodeStringMap(element, "tags")
if err != nil {
desc.LastError = err
return desc
}
desc.Tags = tag.NewTagSetFromMap(m)
}
}
for _, host := range hosts {
desc.Members = append(desc.Members, address.Address(host).Canonicalize())
}
for _, passive := range passives {
desc.Members = append(desc.Members, address.Address(passive).Canonicalize())
}
for _, arbiter := range arbiters {
desc.Members = append(desc.Members, address.Address(arbiter).Canonicalize())
}
desc.Kind = description.Standalone
if isReplicaSet {
desc.Kind = description.RSGhost
} else if desc.SetName != "" {
if isMaster {
desc.Kind = description.RSPrimary
} else if hidden {
desc.Kind = description.RSMember
} else if secondary {
desc.Kind = description.RSSecondary
} else if arbiterOnly {
desc.Kind = description.RSArbiter
} else {
desc.Kind = description.RSMember
}
} else if msg == "isdbgrid" {
desc.Kind = description.Mongos
}
desc.WireVersion = &version
return desc
}
func (im *IsMaster) decodeStringSlice(element bsoncore.Element, name string) ([]string, error) {
arr, ok := element.Value().ArrayOK()
if !ok {
return nil, fmt.Errorf("expected '%s' to be an array but it's a BSON %s", name, element.Value().Type)
}
vals, err := arr.Values()
if err != nil {
return nil, err
}
var strs []string
for _, val := range vals {
str, ok := val.StringValueOK()
if !ok {
return nil, fmt.Errorf("expected '%s' to be an array of strings, but found a BSON %s", name, val.Type)
}
strs = append(strs, str)
}
return strs, nil
}
func (im *IsMaster) decodeStringMap(element bsoncore.Element, name string) (map[string]string, error) {
doc, ok := element.Value().DocumentOK()
if !ok {
return nil, fmt.Errorf("expected '%s' to be a document but it's a BSON %s", name, element.Value().Type)
}
elements, err := doc.Elements()
if err != nil {
return nil, err
}
m := make(map[string]string)
for _, element := range elements {
key := element.Key()
value, ok := element.Value().StringValueOK()
if !ok {
return nil, fmt.Errorf("expected '%s' to be a document of strings, but found a BSON %s", name, element.Value().Type)
}
m[key] = value
}
return m, nil
}
// handshakeCommand appends all necessary command fields as well as client metadata, SASL supported mechs, and compression.
func (im *IsMaster) handshakeCommand(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst, err := im.command(dst, desc)
if err != nil {
return dst, err
}
if im.saslSupportedMechs != "" {
dst = bsoncore.AppendStringElement(dst, "saslSupportedMechs", im.saslSupportedMechs)
}
var idx int32
idx, dst = bsoncore.AppendArrayElementStart(dst, "compression")
for i, compressor := range im.compressors {
dst = bsoncore.AppendStringElement(dst, strconv.Itoa(i), compressor)
}
dst, _ = bsoncore.AppendArrayEnd(dst, idx)
// append client metadata
idx, dst = bsoncore.AppendDocumentElementStart(dst, "client")
didx, dst := bsoncore.AppendDocumentElementStart(dst, "driver")
dst = bsoncore.AppendStringElement(dst, "name", "mongo-go-driver")
dst = bsoncore.AppendStringElement(dst, "version", version.Driver)
dst, _ = bsoncore.AppendDocumentEnd(dst, didx)
didx, dst = bsoncore.AppendDocumentElementStart(dst, "os")
dst = bsoncore.AppendStringElement(dst, "type", runtime.GOOS)
dst = bsoncore.AppendStringElement(dst, "architecture", runtime.GOARCH)
dst, _ = bsoncore.AppendDocumentEnd(dst, didx)
dst = bsoncore.AppendStringElement(dst, "platform", runtime.Version())
if im.appname != "" {
didx, dst = bsoncore.AppendDocumentElementStart(dst, "application")
dst = bsoncore.AppendStringElement(dst, "name", im.appname)
dst, _ = bsoncore.AppendDocumentEnd(dst, didx)
}
dst, _ = bsoncore.AppendDocumentEnd(dst, idx)
return dst, nil
}
// command appends all necessary command fields.
func (im *IsMaster) command(dst []byte, _ description.SelectedServer) ([]byte, error) {
return bsoncore.AppendInt32Element(dst, "isMaster", 1), nil
}
// Execute runs this operation.
func (im *IsMaster) Execute(ctx context.Context) error {
if im.d == nil {
return errors.New("an IsMaster must have a Deployment set before Execute can be called")
}
return driver.Operation{
Clock: im.clock,
CommandFn: im.command,
Database: "admin",
Deployment: im.d,
ProcessResponseFn: func(response bsoncore.Document, _ driver.Server, _ description.Server) error {
im.res = response
return nil
},
}.Execute(ctx, nil)
}
// Handshake implements the Handshaker interface.
func (im *IsMaster) Handshake(ctx context.Context, _ address.Address, c driver.Connection) (description.Server, error) {
err := driver.Operation{
Clock: im.clock,
CommandFn: im.handshakeCommand,
Deployment: driver.SingleConnectionDeployment{c},
Database: "admin",
ProcessResponseFn: func(response bsoncore.Document, _ driver.Server, _ description.Server) error {
im.res = response
return nil
},
}.Execute(ctx, nil)
if err != nil {
return description.Server{}, err
}
return im.Result(c.Address()), nil
}

View File

@@ -0,0 +1,274 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// ListDatabases performs a listDatabases operation.
type ListDatabases struct {
filter bsoncore.Document
nameOnly *bool
session *session.Client
clock *session.ClusterClock
monitor *event.CommandMonitor
database string
deployment driver.Deployment
readPreference *readpref.ReadPref
selector description.ServerSelector
result ListDatabasesResult
}
type ListDatabasesResult struct {
// An array of documents, one document for each database
Databases []databaseRecord
// The sum of the size of all the database files on disk in bytes.
TotalSize int64
}
type databaseRecord struct {
Name string
SizeOnDisk int64 `bson:"sizeOnDisk"`
Empty bool
}
func buildListDatabasesResult(response bsoncore.Document, srvr driver.Server) (ListDatabasesResult, error) {
elements, err := response.Elements()
if err != nil {
return ListDatabasesResult{}, err
}
ir := ListDatabasesResult{}
for _, element := range elements {
switch element.Key() {
case "totalSize":
var ok bool
ir.TotalSize, ok = element.Value().AsInt64OK()
if !ok {
err = fmt.Errorf("response field 'totalSize' is type int64, but received BSON type %s: %s", element.Value().Type, element.Value())
}
case "databases":
// TODO: Make operationgen handle array results.
arr, ok := element.Value().ArrayOK()
if !ok {
err = fmt.Errorf("response field 'databases' is type array, but received BSON type %s", element.Value().Type)
continue
}
var tmp bsoncore.Document
marshalErr := bson.Unmarshal(arr, &tmp)
if marshalErr != nil {
err = marshalErr
continue
}
records, marshalErr := tmp.Elements()
if marshalErr != nil {
err = marshalErr
continue
}
ir.Databases = make([]databaseRecord, len(records))
for i, val := range records {
valueDoc, ok := val.Value().DocumentOK()
if !ok {
err = fmt.Errorf("'databases' element is type document, but received BSON type %s", val.Value().Type)
continue
}
elems, marshalErr := valueDoc.Elements()
if marshalErr != nil {
err = marshalErr
continue
}
for _, elem := range elems {
switch elem.Key() {
case "name":
ir.Databases[i].Name, ok = elem.Value().StringValueOK()
if !ok {
err = fmt.Errorf("response field 'name' is type string, but received BSON type %s", elem.Value().Type)
continue
}
case "sizeOnDisk":
ir.Databases[i].SizeOnDisk, ok = elem.Value().AsInt64OK()
if !ok {
err = fmt.Errorf("response field 'sizeOnDisk' is type int64, but received BSON type %s", elem.Value().Type)
continue
}
case "empty":
ir.Databases[i].Empty, ok = elem.Value().BooleanOK()
if !ok {
err = fmt.Errorf("response field 'empty' is type bool, but received BSON type %s", elem.Value().Type)
continue
}
}
}
}
}
}
return ir, err
}
// NewListDatabases constructs and returns a new ListDatabases.
func NewListDatabases(filter bsoncore.Document) *ListDatabases {
return &ListDatabases{
filter: filter,
}
}
// Result returns the result of executing this operation.
func (ld *ListDatabases) Result() ListDatabasesResult { return ld.result }
func (ld *ListDatabases) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
ld.result, err = buildListDatabasesResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (ld *ListDatabases) Execute(ctx context.Context) error {
if ld.deployment == nil {
return errors.New("the ListDatabases operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: ld.command,
ProcessResponseFn: ld.processResponse,
Client: ld.session,
Clock: ld.clock,
CommandMonitor: ld.monitor,
Database: ld.database,
Deployment: ld.deployment,
ReadPreference: ld.readPreference,
Selector: ld.selector,
}.Execute(ctx, nil)
}
func (ld *ListDatabases) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendInt32Element(dst, "listDatabases", 1)
if ld.filter != nil {
dst = bsoncore.AppendDocumentElement(dst, "filter", ld.filter)
}
if ld.nameOnly != nil {
dst = bsoncore.AppendBooleanElement(dst, "nameOnly", *ld.nameOnly)
}
return dst, nil
}
// Filter determines what results are returned from listDatabases.
func (ld *ListDatabases) Filter(filter bsoncore.Document) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.filter = filter
return ld
}
// NameOnly specifies whether to only return database names.
func (ld *ListDatabases) NameOnly(nameOnly bool) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.nameOnly = &nameOnly
return ld
}
// Session sets the session for this operation.
func (ld *ListDatabases) Session(session *session.Client) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.session = session
return ld
}
// ClusterClock sets the cluster clock for this operation.
func (ld *ListDatabases) ClusterClock(clock *session.ClusterClock) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.clock = clock
return ld
}
// CommandMonitor sets the monitor to use for APM events.
func (ld *ListDatabases) CommandMonitor(monitor *event.CommandMonitor) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.monitor = monitor
return ld
}
// Database sets the database to run this operation against.
func (ld *ListDatabases) Database(database string) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.database = database
return ld
}
// Deployment sets the deployment to use for this operation.
func (ld *ListDatabases) Deployment(deployment driver.Deployment) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.deployment = deployment
return ld
}
// ReadPreference set the read prefernce used with this operation.
func (ld *ListDatabases) ReadPreference(readPreference *readpref.ReadPref) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.readPreference = readPreference
return ld
}
// ServerSelector sets the selector used to retrieve a server.
func (ld *ListDatabases) ServerSelector(selector description.ServerSelector) *ListDatabases {
if ld == nil {
ld = new(ListDatabases)
}
ld.selector = selector
return ld
}

View File

@@ -0,0 +1,32 @@
version = 0
name = "ListDatabases"
documentation = "ListDatabases performs a listDatabases operation."
[properties]
enabled = ["read preference"]
disabled = ["collection"]
[command]
name = "listDatabases"
parameter = "database"
[request.filter]
type = "document"
constructor = true
documentation = "Filter determines what results are returned from listDatabases."
[request.nameOnly]
type = "boolean"
documentation = "NameOnly specifies whether to only return database names."
[response]
name = "ListDatabasesResult"
[response.field.totalSize]
type = "int64"
documentation = "The sum of the size of all the database files on disk in bytes."
[response.field.databases]
type = "value"
documentation = "An array of documents, one document for each database"

View File

@@ -0,0 +1,184 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// ListCollections performs a listCollections operation.
type ListCollections struct {
filter bsoncore.Document
nameOnly *bool
session *session.Client
clock *session.ClusterClock
monitor *event.CommandMonitor
database string
deployment driver.Deployment
readPreference *readpref.ReadPref
selector description.ServerSelector
result driver.CursorResponse
}
// NewListCollections constructs and returns a new ListCollections.
func NewListCollections(filter bsoncore.Document) *ListCollections {
return &ListCollections{
filter: filter,
}
}
// Result returns the result of executing this operation.
func (lc *ListCollections) Result(opts driver.CursorOptions) (*driver.ListCollectionsBatchCursor, error) {
bc, err := driver.NewBatchCursor(lc.result, lc.session, lc.clock, opts)
if err != nil {
return nil, err
}
desc := lc.result.Desc
if desc.WireVersion == nil || desc.WireVersion.Max < 3 {
return driver.NewLegacyListCollectionsBatchCursor(bc)
}
return driver.NewListCollectionsBatchCursor(bc)
}
func (lc *ListCollections) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
lc.result, err = driver.NewCursorResponse(response, srvr, desc)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (lc *ListCollections) Execute(ctx context.Context) error {
if lc.deployment == nil {
return errors.New("the ListCollections operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: lc.command,
ProcessResponseFn: lc.processResponse,
Client: lc.session,
Clock: lc.clock,
CommandMonitor: lc.monitor,
Database: lc.database,
Deployment: lc.deployment,
ReadPreference: lc.readPreference,
Selector: lc.selector,
Legacy: driver.LegacyListCollections,
}.Execute(ctx, nil)
}
func (lc *ListCollections) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendInt32Element(dst, "listCollections", 1)
if lc.filter != nil {
dst = bsoncore.AppendDocumentElement(dst, "filter", lc.filter)
}
if lc.nameOnly != nil {
dst = bsoncore.AppendBooleanElement(dst, "nameOnly", *lc.nameOnly)
}
return dst, nil
}
// Filter determines what results are returned from listCollections.
func (lc *ListCollections) Filter(filter bsoncore.Document) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.filter = filter
return lc
}
// NameOnly specifies whether to only return collection names.
func (lc *ListCollections) NameOnly(nameOnly bool) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.nameOnly = &nameOnly
return lc
}
// Session sets the session for this operation.
func (lc *ListCollections) Session(session *session.Client) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.session = session
return lc
}
// ClusterClock sets the cluster clock for this operation.
func (lc *ListCollections) ClusterClock(clock *session.ClusterClock) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.clock = clock
return lc
}
// CommandMonitor sets the monitor to use for APM events.
func (lc *ListCollections) CommandMonitor(monitor *event.CommandMonitor) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.monitor = monitor
return lc
}
// Database sets the database to run this operation against.
func (lc *ListCollections) Database(database string) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.database = database
return lc
}
// Deployment sets the deployment to use for this operation.
func (lc *ListCollections) Deployment(deployment driver.Deployment) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.deployment = deployment
return lc
}
// ReadPreference set the read prefernce used with this operation.
func (lc *ListCollections) ReadPreference(readPreference *readpref.ReadPref) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.readPreference = readPreference
return lc
}
// ServerSelector sets the selector used to retrieve a server.
func (lc *ListCollections) ServerSelector(selector description.ServerSelector) *ListCollections {
if lc == nil {
lc = new(ListCollections)
}
lc.selector = selector
return lc
}

View File

@@ -0,0 +1,22 @@
version = 0
name = "ListCollections"
documentation = "ListCollections performs a listCollections operation."
response.type = "list collections batch cursor"
[properties]
enabled = ["read preference"]
disabled = ["collection"]
legacy = "listCollections"
[command]
name = "listCollections"
parameter = "database"
[request.filter]
type = "document"
constructor = true
documentation = "Filter determines what results are returned from listCollections."
[request.nameOnly]
type = "boolean"
documentation = "NameOnly specifies whether to only return collection names."

View File

@@ -0,0 +1,186 @@
// Copyright (C) MongoDB, Inc. 2019-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
// Code generated by operationgen. DO NOT EDIT.
package operation
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// ListIndexes performs a listIndexes operation.
type ListIndexes struct {
batchSize *int32
maxTimeMS *int64
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
result driver.CursorResponse
}
// NewListIndexes constructs and returns a new ListIndexes.
func NewListIndexes() *ListIndexes {
return &ListIndexes{}
}
// Result returns the result of executing this operation.
func (li *ListIndexes) Result(opts driver.CursorOptions) (*driver.BatchCursor, error) {
clientSession := li.session
clock := li.clock
return driver.NewBatchCursor(li.result, clientSession, clock, opts)
}
func (li *ListIndexes) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
li.result, err = driver.NewCursorResponse(response, srvr, desc)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (li *ListIndexes) Execute(ctx context.Context) error {
if li.deployment == nil {
return errors.New("the ListIndexes operation must have a Deployment set before Execute can be called")
}
return driver.Operation{
CommandFn: li.command,
ProcessResponseFn: li.processResponse,
Client: li.session,
Clock: li.clock,
CommandMonitor: li.monitor,
Database: li.database,
Deployment: li.deployment,
Selector: li.selector,
Legacy: driver.LegacyListIndexes,
}.Execute(ctx, nil)
}
func (li *ListIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "listIndexes", li.collection)
cursorIdx, cursorDoc := bsoncore.AppendDocumentStart(nil)
if li.batchSize != nil {
cursorDoc = bsoncore.AppendInt32Element(cursorDoc, "batchSize", *li.batchSize)
}
if li.maxTimeMS != nil {
dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", *li.maxTimeMS)
}
cursorDoc, _ = bsoncore.AppendDocumentEnd(cursorDoc, cursorIdx)
dst = bsoncore.AppendDocumentElement(dst, "cursor", cursorDoc)
return dst, nil
}
// BatchSize specifies the number of documents to return in every batch.
func (li *ListIndexes) BatchSize(batchSize int32) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.batchSize = &batchSize
return li
}
// MaxTimeMS specifies the maximum amount of time to allow the query to run.
func (li *ListIndexes) MaxTimeMS(maxTimeMS int64) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.maxTimeMS = &maxTimeMS
return li
}
// Session sets the session for this operation.
func (li *ListIndexes) Session(session *session.Client) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.session = session
return li
}
// ClusterClock sets the cluster clock for this operation.
func (li *ListIndexes) ClusterClock(clock *session.ClusterClock) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.clock = clock
return li
}
// Collection sets the collection that this command will run against.
func (li *ListIndexes) Collection(collection string) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.collection = collection
return li
}
// CommandMonitor sets the monitor to use for APM events.
func (li *ListIndexes) CommandMonitor(monitor *event.CommandMonitor) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.monitor = monitor
return li
}
// Database sets the database to run this operation against.
func (li *ListIndexes) Database(database string) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.database = database
return li
}
// Deployment sets the deployment to use for this operation.
func (li *ListIndexes) Deployment(deployment driver.Deployment) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.deployment = deployment
return li
}
// ServerSelector sets the selector used to retrieve a server.
func (li *ListIndexes) ServerSelector(selector description.ServerSelector) *ListIndexes {
if li == nil {
li = new(ListIndexes)
}
li.selector = selector
return li
}

View File

@@ -0,0 +1,19 @@
version = 0
name = "ListIndexes"
documentation = "ListIndexes performs a listIndexes operation."
response.type = "batch cursor"
[properties]
legacy = "listIndexes"
[command]
name = "listIndexes"
parameter = "collection"
[request.batchSize]
type = "int32"
documentation = "BatchSize specifies the number of documents to return in every batch."
[request.maxTimeMS]
type = "int64"
documentation = "MaxTimeMS specifies the maximum amount of time to allow the query to run."

View File

@@ -0,0 +1,12 @@
package operation
//go:generate operationgen insert.toml operation insert.go
//go:generate operationgen find.toml operation find.go
//go:generate operationgen list_collections.toml operation list_collections.go
//go:generate operationgen createIndexes.toml operation createIndexes.go
//go:generate operationgen drop_collection.toml operation drop_collection.go
//go:generate operationgen distinct.toml operation distinct.go
//go:generate operationgen delete.toml operation delete.go
//go:generate operationgen drop_indexes.toml operation drop_indexes.go
//go:generate operationgen drop_database.toml operation drop_database.go
//go:generate operationgen commit_transaction.toml operation commit_transaction.go

View File

@@ -0,0 +1,295 @@
// Copyright (C) MongoDB, Inc. 2019-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
// NOTE: This file is maintained by hand because operationgen cannot generate it.
package operation
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/x/mongo/driver/session"
)
// Update performs an update operation.
type Update struct {
bypassDocumentValidation *bool
ordered *bool
updates []bsoncore.Document
session *session.Client
clock *session.ClusterClock
collection string
monitor *event.CommandMonitor
database string
deployment driver.Deployment
selector description.ServerSelector
writeConcern *writeconcern.WriteConcern
retry *driver.RetryMode
result UpdateResult
}
// Upsert contains the information for an upsert in an Update operation.
type Upsert struct {
Index int64
ID interface{} `bson:"_id"`
}
// UpdateResult contains information for the result of an Update operation.
type UpdateResult struct {
// Number of documents matched.
N int32
// Number of documents modified.
NModified int32
// Information about upserted documents.
Upserted []Upsert
}
func buildUpdateResult(response bsoncore.Document, srvr driver.Server) (UpdateResult, error) {
elements, err := response.Elements()
if err != nil {
return UpdateResult{}, err
}
ur := UpdateResult{}
for _, element := range elements {
switch element.Key() {
case "nModified":
var ok bool
ur.NModified, ok = element.Value().Int32OK()
if !ok {
err = fmt.Errorf("response field 'nModified' is type int32, but received BSON type %s", element.Value().Type)
}
case "n":
var ok bool
ur.N, ok = element.Value().Int32OK()
if !ok {
err = fmt.Errorf("response field 'n' is type int32, but received BSON type %s", element.Value().Type)
}
case "upserted":
arr, ok := element.Value().ArrayOK()
if !ok {
err = fmt.Errorf("response field 'upserted' is type array, but received BSON type %s", element.Value().Type)
break
}
var values []bsoncore.Value
values, err = arr.Values()
if err != nil {
break
}
for _, val := range values {
valDoc, ok := val.DocumentOK()
if !ok {
err = fmt.Errorf("upserted value is type document, but received BSON type %s", val.Type)
break
}
var upsert Upsert
if err = bson.Unmarshal(valDoc, &upsert); err != nil {
break
}
ur.Upserted = append(ur.Upserted, upsert)
}
}
}
return ur, nil
}
// NewUpdate constructs and returns a new Update.
func NewUpdate(updates ...bsoncore.Document) *Update {
return &Update{
updates: updates,
}
}
// Result returns the result of executing this operation.
func (u *Update) Result() UpdateResult { return u.result }
func (u *Update) processResponse(response bsoncore.Document, srvr driver.Server, desc description.Server) error {
var err error
u.result, err = buildUpdateResult(response, srvr)
return err
}
// Execute runs this operations and returns an error if the operaiton did not execute successfully.
func (u *Update) Execute(ctx context.Context) error {
if u.deployment == nil {
return errors.New("the Update operation must have a Deployment set before Execute can be called")
}
batches := &driver.Batches{
Identifier: "updates",
Documents: u.updates,
Ordered: u.ordered,
}
return driver.Operation{
CommandFn: u.command,
ProcessResponseFn: u.processResponse,
Batches: batches,
RetryMode: u.retry,
RetryType: driver.RetryWrite,
Client: u.session,
Clock: u.clock,
CommandMonitor: u.monitor,
Database: u.database,
Deployment: u.deployment,
Selector: u.selector,
WriteConcern: u.writeConcern,
}.Execute(ctx, nil)
}
func (u *Update) command(dst []byte, desc description.SelectedServer) ([]byte, error) {
dst = bsoncore.AppendStringElement(dst, "update", u.collection)
if u.bypassDocumentValidation != nil &&
(desc.WireVersion != nil && desc.WireVersion.Includes(4)) {
dst = bsoncore.AppendBooleanElement(dst, "bypassDocumentValidation", *u.bypassDocumentValidation)
}
if u.ordered != nil {
dst = bsoncore.AppendBooleanElement(dst, "ordered", *u.ordered)
}
return dst, nil
}
// BypassDocumentValidation allows the operation to opt-out of document level validation. Valid
// for server versions >= 3.2. For servers < 3.2, this setting is ignored.
func (u *Update) BypassDocumentValidation(bypassDocumentValidation bool) *Update {
if u == nil {
u = new(Update)
}
u.bypassDocumentValidation = &bypassDocumentValidation
return u
}
// Ordered sets ordered. If true, when a write fails, the operation will return the error, when
// false write failures do not stop execution of the operation.
func (u *Update) Ordered(ordered bool) *Update {
if u == nil {
u = new(Update)
}
u.ordered = &ordered
return u
}
// Updates specifies an array of update statements to perform when this operation is executed.
// Each update document must have the following structure: {q: <query>, u: <update>, multi: <boolean>, collation: Optional<Document>, arrayFitlers: Optional<Array>}.
func (u *Update) Updates(updates ...bsoncore.Document) *Update {
if u == nil {
u = new(Update)
}
u.updates = updates
return u
}
// Session sets the session for this operation.
func (u *Update) Session(session *session.Client) *Update {
if u == nil {
u = new(Update)
}
u.session = session
return u
}
// ClusterClock sets the cluster clock for this operation.
func (u *Update) ClusterClock(clock *session.ClusterClock) *Update {
if u == nil {
u = new(Update)
}
u.clock = clock
return u
}
// Collection sets the collection that this command will run against.
func (u *Update) Collection(collection string) *Update {
if u == nil {
u = new(Update)
}
u.collection = collection
return u
}
// CommandMonitor sets the monitor to use for APM events.
func (u *Update) CommandMonitor(monitor *event.CommandMonitor) *Update {
if u == nil {
u = new(Update)
}
u.monitor = monitor
return u
}
// Database sets the database to run this operation against.
func (u *Update) Database(database string) *Update {
if u == nil {
u = new(Update)
}
u.database = database
return u
}
// Deployment sets the deployment to use for this operation.
func (u *Update) Deployment(deployment driver.Deployment) *Update {
if u == nil {
u = new(Update)
}
u.deployment = deployment
return u
}
// ServerSelector sets the selector used to retrieve a server.
func (u *Update) ServerSelector(selector description.ServerSelector) *Update {
if u == nil {
u = new(Update)
}
u.selector = selector
return u
}
// WriteConcern sets the write concern for this operation.
func (u *Update) WriteConcern(writeConcern *writeconcern.WriteConcern) *Update {
if u == nil {
u = new(Update)
}
u.writeConcern = writeConcern
return u
}
// Retry enables retryable writes for this operation. Retries are not handled automatically,
// instead a boolean is returned from Execute and SelectAndExecute that indicates if the
// operation can be retried. Retrying is handled by calling RetryExecute.
func (u *Update) Retry(retry driver.RetryMode) *Update {
if u == nil {
u = new(Update)
}
u.retry = &retry
return u
}

View File

@@ -0,0 +1,49 @@
version = 0
name = "Update"
documentation = "Update performs an update operation."
[properties]
enabled = ["write concern"]
retryable = {mode = "once per command", type = "writes"}
batches = "updates"
[command]
name = "update"
parameter = "collection"
[request.updates]
type = "document"
slice = true
constructor = true
variadic = true
required = true
documentation = """
Updates specifies an array of update statements to perform when this operation is executed.
Each update document must have the following structure: {q: <query>, u: <update>, multi: <boolean>, collation: Optional<Document>, arrayFitlers: Optional<Array>}.\
"""
[request.ordered]
type = "boolean"
documentation = """
Ordered sets ordered. If true, when a write fails, the operation will return the error, when
false write failures do not stop execution of the operation.\
"""
[request.bypassDocumentValidation]
type = "boolean"
minWireVersion = 4
documentation = """
BypassDocumentValidation allows the operation to opt-out of document level validation. Valid
for server versions >= 3.2. For servers < 3.2, this setting is ignored.\
"""
[response]
name = "UpdateResult"
[response.field.n]
type = "int32"
documentation = "Number of documents matched."
[response.field.nModified]
type = "int32"
documentation = "Number of documents modified."