mongo-driver: go.mongodb.org/mongo-driver/x/mongo/driver Index | Files | Directories

package driver

import "go.mongodb.org/mongo-driver/x/mongo/driver"

Index

Package Files

batch_cursor.go batches.go driver.go errors.go legacy.go list_collections_batch_cursor.go operation.go operation_legacy.go

Variables

var (
    // UnknownTransactionCommitResult is an error label for unknown transaction commit results.
    UnknownTransactionCommitResult = "UnknownTransactionCommitResult"
    // TransientTransactionError is an error label for transient errors with transactions.
    TransientTransactionError = "TransientTransactionError"
    // NetworkError is an error label for network errors.
    NetworkError = "NetworkError"
    // ErrCursorNotFound is the cursor not found error for legacy find operations.
    ErrCursorNotFound = errors.New("cursor not found")
    // ErrUnacknowledgedWrite is returned from functions that have an unacknowledged
    // write concern.
    ErrUnacknowledgedWrite = errors.New("unacknowledged write")
    // ErrUnsupportedStorageEngine is returned when a retryable write is attempted against a server
    // that uses a storage engine that does not support retryable writes
    ErrUnsupportedStorageEngine = errors.New("this MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string")
)
var (
    // ErrNoDocCommandResponse occurs when the server indicated a response existed, but none was found.
    ErrNoDocCommandResponse = errors.New("command returned no documents")
    // ErrMultiDocCommandResponse occurs when the server sent multiple documents in response to a command.
    ErrMultiDocCommandResponse = errors.New("command returned multiple documents")
    // ErrReplyDocumentMismatch occurs when the number of documents returned in an OP_QUERY does not match the numberReturned field.
    ErrReplyDocumentMismatch = errors.New("number of documents returned does not match numberReturned field")
    // ErrNonPrimaryReadPref is returned when a read is attempted in a transaction with a non-primary read preference.
    ErrNonPrimaryReadPref = errors.New("read preference in a transaction must be primary")
)
var ErrDocumentTooLarge = errors.New("an inserted document is too large")

ErrDocumentTooLarge occurs when a document that is larger than the maximum size accepted by a server is passed to an insert command.

var (

    // ErrFilterType is returned when the filter for a legacy list collections operation is of the wrong type.
    ErrFilterType = errors.New("filter for list collections operation must be a string")
)

type BatchCursor Uses

type BatchCursor struct {
    // contains filtered or unexported fields
}

BatchCursor is a batch implementation of a cursor. It returns documents in entire batches instead of one at a time. An individual document cursor can be built on top of this batch cursor.

func NewBatchCursor Uses

func NewBatchCursor(cr CursorResponse, clientSession *session.Client, clock *session.ClusterClock, opts CursorOptions) (*BatchCursor, error)

NewBatchCursor creates a new BatchCursor from the provided parameters.

func NewEmptyBatchCursor Uses

func NewEmptyBatchCursor() *BatchCursor

NewEmptyBatchCursor returns a batch cursor that is empty.

func (*BatchCursor) Batch Uses

func (bc *BatchCursor) Batch() *bsoncore.DocumentSequence

Batch will return a DocumentSequence for the current batch of documents. The returned DocumentSequence is only valid until the next call to Next or Close.

func (*BatchCursor) Close Uses

func (bc *BatchCursor) Close(ctx context.Context) error

Close closes this batch cursor.

func (*BatchCursor) Err Uses

func (bc *BatchCursor) Err() error

Err returns the latest error encountered.

func (*BatchCursor) ID Uses

func (bc *BatchCursor) ID() int64

ID returns the cursor ID for this batch cursor.

func (*BatchCursor) KillCursor Uses

func (bc *BatchCursor) KillCursor(ctx context.Context) error

KillCursor kills cursor on server without closing batch cursor

func (*BatchCursor) Next Uses

func (bc *BatchCursor) Next(ctx context.Context) bool

Next indicates if there is another batch available. Returning false does not necessarily indicate that the cursor is closed. This method will return false when an empty batch is returned.

If Next returns true, there is a valid batch of documents available. If Next returns false, there is not a valid batch of documents available.

func (*BatchCursor) PostBatchResumeToken Uses

func (bc *BatchCursor) PostBatchResumeToken() bsoncore.Document

PostBatchResumeToken returns the latest seen post batch resume token.

func (*BatchCursor) Server Uses

func (bc *BatchCursor) Server() Server

Server returns the server for this cursor.

type Batches Uses

type Batches struct {
    Identifier string
    Documents  []bsoncore.Document
    Current    []bsoncore.Document
    Ordered    *bool
}

Batches contains the necessary information to batch split an operation. This is only used for write oeprations.

func (*Batches) AdvanceBatch Uses

func (b *Batches) AdvanceBatch(maxCount, targetBatchSize int) error

AdvanceBatch splits the next batch using maxCount and targetBatchSize. This method will do nothing if the current batch has not been cleared. We do this so that when this is called during execute we can call it without first needing to check if we already have a batch, which makes the code simpler and makes retrying easier.

func (*Batches) ClearBatch Uses

func (b *Batches) ClearBatch()

ClearBatch clears the Current batch. This must be called before AdvanceBatch will advance to the next batch.

func (*Batches) Valid Uses

func (b *Batches) Valid() bool

Valid returns true if Batches contains both an identifier and the length of Documents is greater than zero.

type Compressor Uses

type Compressor interface {
    CompressWireMessage(src, dst []byte) ([]byte, error)
}

Compressor is an interface used to compress wire messages. If a Connection supports compression it should implement this interface as well. The CompressWireMessage method will be called during the execution of an operation if the wire message is allowed to be compressed.

type Connection Uses

type Connection interface {
    WriteWireMessage(context.Context, []byte) error
    ReadWireMessage(ctx context.Context, dst []byte) ([]byte, error)
    Description() description.Server
    Close() error
    ID() string
    Address() address.Address
}

Connection represents a connection to a MongoDB server.

type CursorOptions Uses

type CursorOptions struct {
    BatchSize      int32
    MaxTimeMS      int64
    Limit          int32
    CommandMonitor *event.CommandMonitor
}

CursorOptions are extra options that are required to construct a BatchCursor.

type CursorResponse Uses

type CursorResponse struct {
    Server     Server
    Desc       description.Server
    FirstBatch *bsoncore.DocumentSequence
    Database   string
    Collection string
    ID         int64
    // contains filtered or unexported fields
}

CursorResponse represents the response from a command the results in a cursor. A BatchCursor can be constructed from a CursorResponse.

func NewCursorResponse Uses

func NewCursorResponse(response bsoncore.Document, server Server, desc description.Server) (CursorResponse, error)

NewCursorResponse constructs a cursor response from the given response and server. This method can be used within the ProcessResponse method for an operation.

type Deployment Uses

type Deployment interface {
    SelectServer(context.Context, description.ServerSelector) (Server, error)
    SupportsRetryWrites() bool
    Kind() description.TopologyKind
}

Deployment is implemented by types that can select a server from a deployment.

type Error Uses

type Error struct {
    Code    int32
    Message string
    Labels  []string
    Name    string
}

Error is a command execution error from the database.

func (Error) Error Uses

func (e Error) Error() string

Error implements the error interface.

func (Error) HasErrorLabel Uses

func (e Error) HasErrorLabel(label string) bool

HasErrorLabel returns true if the error contains the specified label.

func (Error) NamespaceNotFound Uses

func (e Error) NamespaceNotFound() bool

NamespaceNotFound returns true if this errors is a NamespaceNotFound error.

func (Error) NetworkError Uses

func (e Error) NetworkError() bool

NetworkError returns true if the error is a network error.

func (Error) NodeIsRecovering Uses

func (e Error) NodeIsRecovering() bool

NodeIsRecovering returns true if this error is a node is recovering error.

func (Error) NodeIsShuttingDown Uses

func (e Error) NodeIsShuttingDown() bool

NodeIsShuttingDown returns true if this error is a node is shutting down error.

func (Error) NotMaster Uses

func (e Error) NotMaster() bool

NotMaster returns true if this error is a not master error.

func (Error) Retryable Uses

func (e Error) Retryable() bool

Retryable returns true if the error is retryable

func (Error) UnsupportedStorageEngine Uses

func (e Error) UnsupportedStorageEngine() bool

UnsupportedStorageEngine returns whether e came as a result of an unsupported storage engine

type ErrorProcessor Uses

type ErrorProcessor interface {
    ProcessError(error)
}

ErrorProcessor implementations can handle processing errors, which may modify their internal state. If this type is implemented by a Server, then Operation.Execute will call it's ProcessError method after it decodes a wire message.

type Expirable Uses

type Expirable interface {
    Expire() error
    Alive() bool
}

Expirable represents an expirable object.

type Handshaker Uses

type Handshaker interface {
    Handshake(context.Context, address.Address, Connection) (description.Server, error)
}

Handshaker is the interface implemented by types that can perform a MongoDB handshake over a provided driver.Connection. This is used during connection initialization. Implementations must be goroutine safe.

type HandshakerFunc Uses

type HandshakerFunc func(context.Context, address.Address, Connection) (description.Server, error)

HandshakerFunc is an adapter to allow the use of ordinary functions as connection handshakers.

func (HandshakerFunc) Handshake Uses

func (hf HandshakerFunc) Handshake(ctx context.Context, addr address.Address, conn Connection) (description.Server, error)

Handshake implements the Handshaker interface.

type InvalidOperationError Uses

type InvalidOperationError struct{ MissingField string }

InvalidOperationError is returned from Validate and indicates that a required field is missing from an instance of Operation.

func (InvalidOperationError) Error Uses

func (err InvalidOperationError) Error() string

type LegacyOperationKind Uses

type LegacyOperationKind uint

LegacyOperationKind indicates if an operation is a legacy find, getMore, or killCursors. This is used in Operation.Execute, which will create legacy OP_QUERY, OP_GET_MORE, or OP_KILL_CURSORS instead of sending them as a command.

const (
    LegacyNone LegacyOperationKind = iota
    LegacyFind
    LegacyGetMore
    LegacyKillCursors
    LegacyListCollections
    LegacyListIndexes
)

These constants represent the three different kinds of legacy operations.

type ListCollectionsBatchCursor Uses

type ListCollectionsBatchCursor struct {
    // contains filtered or unexported fields
}

ListCollectionsBatchCursor is a special batch cursor returned from ListCollections that properly handles current and legacy ListCollections operations.

func NewLegacyListCollectionsBatchCursor Uses

func NewLegacyListCollectionsBatchCursor(bc *BatchCursor) (*ListCollectionsBatchCursor, error)

NewLegacyListCollectionsBatchCursor creates a new legacy ListCollectionsCursor.

func NewListCollectionsBatchCursor Uses

func NewListCollectionsBatchCursor(bc *BatchCursor) (*ListCollectionsBatchCursor, error)

NewListCollectionsBatchCursor creates a new non-legacy ListCollectionsCursor.

func (*ListCollectionsBatchCursor) Batch Uses

func (lcbc *ListCollectionsBatchCursor) Batch() *bsoncore.DocumentSequence

Batch will return a DocumentSequence for the current batch of documents. The returned DocumentSequence is only valid until the next call to Next or Close.

func (*ListCollectionsBatchCursor) Close Uses

func (lcbc *ListCollectionsBatchCursor) Close(ctx context.Context) error

Close closes this batch cursor.

func (*ListCollectionsBatchCursor) Err Uses

func (lcbc *ListCollectionsBatchCursor) Err() error

Err returns the latest error encountered.

func (*ListCollectionsBatchCursor) ID Uses

func (lcbc *ListCollectionsBatchCursor) ID() int64

ID returns the cursor ID for this batch cursor.

func (*ListCollectionsBatchCursor) Next Uses

func (lcbc *ListCollectionsBatchCursor) Next(ctx context.Context) bool

Next indicates if there is another batch available. Returning false does not necessarily indicate that the cursor is closed. This method will return false when an empty batch is returned.

If Next returns true, there is a valid batch of documents available. If Next returns false, there is not a valid batch of documents available.

func (*ListCollectionsBatchCursor) Server Uses

func (lcbc *ListCollectionsBatchCursor) Server() Server

Server returns a pointer to the cursor's server.

type LocalAddresser Uses

type LocalAddresser interface {
    LocalAddress() address.Address
}

LocalAddresser is a type that is able to supply its local address

type Operation Uses

type Operation struct {
    // CommandFn is used to create the command that will be wrapped in a wire message and sent to
    // the server. This function should only add the elements of the command and not start or end
    // the enclosing BSON document. Per the command API, the first element must be the name of the
    // command to run. This field is required.
    CommandFn func(dst []byte, desc description.SelectedServer) ([]byte, error)

    // Database is the database that the command will be run against. This field is required.
    Database string

    // Deployment is the MongoDB Deployment to use. While most of the time this will be multiple
    // servers, commands that need to run against a single, preselected server can use the
    // SingleServerDeployment type. Commands that need to run on a preselected connection can use
    // the SingleConnectionDeployment type.
    Deployment Deployment

    // ProcessResponseFn is called after a response to the command is returned. The server is
    // provided for types like Cursor that are required to run subsequent commands using the same
    // server.
    ProcessResponseFn func(response bsoncore.Document, srvr Server, desc description.Server) error

    // Selector is the server selector that's used during both initial server selection and
    // subsequent selection for retries. Depending on the Deployment implementation, the
    // SelectServer method may not actually be called.
    Selector description.ServerSelector

    // ReadPreference is the read preference that will be attached to the command. If this field is
    // not specified a default read preference of primary will be used.
    ReadPreference *readpref.ReadPref

    // ReadConcern is the read concern used when running read commands. This field should not be set
    // for write operations. If this field is set, it will be encoded onto the commands sent to the
    // server.
    ReadConcern *readconcern.ReadConcern

    // MinimumReadConcernWireVersion specifies the minimum wire version to add the read concern to
    // the command being executed.
    MinimumReadConcernWireVersion int32

    // WriteConcern is the write concern used when running write commands. This field should not be
    // set for read operations. If this field is set, it will be encoded onto the commands sent to
    // the server.
    WriteConcern *writeconcern.WriteConcern

    // MinimumWriteConcernWireVersion specifies the minimum wire version to add the write concern to
    // the command being executed.
    MinimumWriteConcernWireVersion int32

    // Client is the session used with this operation. This can be either an implicit or explicit
    // session. If the server selected does not support sessions and Client is specified the
    // behavior depends on the session type. If the session is implicit, the session fields will not
    // be encoded onto the command. If the session is explicit, an error will be returned. The
    // caller is responsible for ensuring that this field is nil if the Deployment does not support
    // sessions.
    Client *session.Client

    // Clock is a cluster clock, different from the one contained within a session.Client. This
    // allows updating cluster times for a global cluster clock while allowing individual session's
    // cluster clocks to be only updated as far as the last command that's been run.
    Clock *session.ClusterClock

    // RetryMode specifies how to retry. There are three modes that enable retry: RetryOnce,
    // RetryOncePerCommand, and RetryContext. For more information about what these modes do, please
    // refer to their definitions. Both RetryMode and Type must be set for retryability to be enabled.
    RetryMode *RetryMode

    // Type specifies the kind of operation this is. There is only one mode that enables retry: Write.
    // For more information about what this mode does, please refer to it's definition. Both Type and
    // RetryMode must be set for retryability to be enabled.
    Type Type

    // Batches contains the documents that are split when executing a write command that potentially
    // has more documents than can fit in a single command. This should only be specified for
    // commands that are batch compatible. For more information, please refer to the definition of
    // Batches.
    Batches *Batches

    // Legacy sets the legacy type for this operation. There are only 3 types that require legacy
    // support: find, getMore, and killCursors. For more information about LegacyOperationKind,
    // please refer to it's definition.
    Legacy LegacyOperationKind

    // CommandMonitor specifies the monitor to use for APM events. If this field is not set,
    // no events will be reported.
    CommandMonitor *event.CommandMonitor
}

Operation is used to execute an operation. It contains all of the common code required to select a server, transform an operation into a command, write the command to a connection from the selected server, read a response from that connection, process the response, and potentially retry.

The required fields are Database, CommandFn, and Deployment. All other fields are optional.

While an Operation can be constructed manually, drivergen should be used to generate an implementation of an operation instead. This will ensure that there are helpers for constructing the operation and that this type isn't configured incorrectly.

func (Operation) Execute Uses

func (op Operation) Execute(ctx context.Context, scratch []byte) error

Execute runs this operation. The scratch parameter will be used and overwritten (potentially many times), this should mainly be used to enable pooling of byte slices.

func (Operation) Validate Uses

func (op Operation) Validate() error

Validate validates this operation, ensuring the fields are set properly.

type QueryFailureError Uses

type QueryFailureError struct {
    Message  string
    Response bsoncore.Document
}

QueryFailureError is an error representing a command failure as a document.

func (QueryFailureError) Error Uses

func (e QueryFailureError) Error() string

Error implements the error interface.

type ResponseError Uses

type ResponseError struct {
    Message string
    Wrapped error
}

ResponseError is an error parsing the response to a command.

func NewCommandResponseError Uses

func NewCommandResponseError(msg string, err error) ResponseError

NewCommandResponseError creates a CommandResponseError.

func (ResponseError) Error Uses

func (e ResponseError) Error() string

Error implements the error interface.

type RetryMode Uses

type RetryMode uint

RetryMode specifies the way that retries are handled for retryable operations.

const (
    // RetryNone disables retrying.
    RetryNone RetryMode = iota
    // RetryOnce will enable retrying the entire operation once.
    RetryOnce
    // RetryOncePerCommand will enable retrying each command associated with an operation. For
    // example, if an insert is batch split into 4 commands then each of those commands is eligible
    // for one retry.
    RetryOncePerCommand
    // RetryContext will enable retrying until the context.Context's deadline is exceeded or it is
    // cancelled.
    RetryContext
)

These are the modes available for retrying.

func (RetryMode) Enabled Uses

func (rm RetryMode) Enabled() bool

Enabled returns if this RetryMode enables retrying.

type Server Uses

type Server interface {
    Connection(context.Context) (Connection, error)
}

Server represents a MongoDB server. Implementations should pool connections and handle the retrieving and returning of connections.

type SingleConnectionDeployment Uses

type SingleConnectionDeployment struct{ C Connection }

SingleConnectionDeployment is an implementation of Deployment that always returns the same Connection.

func (SingleConnectionDeployment) Connection Uses

func (ssd SingleConnectionDeployment) Connection(context.Context) (Connection, error)

Connection implements the Server interface. It always returns the embedded connection.

This method returns a Connection with a no-op Close method. This ensures that a SingleConnectionDeployment can be used across multiple operation executions.

func (SingleConnectionDeployment) Kind Uses

func (ssd SingleConnectionDeployment) Kind() description.TopologyKind

Kind implements the Deployment interface. It always returns description.Single.

func (SingleConnectionDeployment) SelectServer Uses

func (ssd SingleConnectionDeployment) SelectServer(context.Context, description.ServerSelector) (Server, error)

SelectServer implements the Deployment interface. This method does not use the description.SelectedServer provided and instead returns itself. The Connections returned from the Connection method have a no-op Close method.

func (SingleConnectionDeployment) SupportsRetryWrites Uses

func (ssd SingleConnectionDeployment) SupportsRetryWrites() bool

SupportsRetryWrites implements the Deployment interface. It always returns Type(0), because a single connection does not support retryability.

type SingleServerDeployment Uses

type SingleServerDeployment struct{ Server }

SingleServerDeployment is an implementation of Deployment that always returns a single server.

func (SingleServerDeployment) Kind Uses

func (SingleServerDeployment) Kind() description.TopologyKind

Kind implements the Deployment interface. It always returns description.Single.

func (SingleServerDeployment) SelectServer Uses

func (ssd SingleServerDeployment) SelectServer(context.Context, description.ServerSelector) (Server, error)

SelectServer implements the Deployment interface. This method does not use the description.SelectedServer provided and instead returns the embedded Server.

func (SingleServerDeployment) SupportsRetryWrites Uses

func (SingleServerDeployment) SupportsRetryWrites() bool

SupportsRetryWrites implements the Deployment interface. It always returns Type(0), because a single server does not support retryability.

type Type Uses

type Type uint

Type specifies whether an operation is a read, write, or unknown.

const (
    Write Type
    Read
)

THese are the availables types of Type.

type WriteCommandError Uses

type WriteCommandError struct {
    WriteConcernError *WriteConcernError
    WriteErrors       WriteErrors
}

WriteCommandError is an error for a write command.

func (WriteCommandError) Error Uses

func (wce WriteCommandError) Error() string

func (WriteCommandError) Retryable Uses

func (wce WriteCommandError) Retryable() bool

Retryable returns true if the error is retryable

func (WriteCommandError) UnsupportedStorageEngine Uses

func (wce WriteCommandError) UnsupportedStorageEngine() bool

UnsupportedStorageEngine returns whether or not the WriteCommandError comes from a retryable write being attempted against a server that has a storage engine where they are not supported

type WriteConcernError Uses

type WriteConcernError struct {
    Name    string
    Code    int64
    Message string
    Details bsoncore.Document
}

WriteConcernError is a write concern failure that occurred as a result of a write operation.

func (WriteConcernError) Error Uses

func (wce WriteConcernError) Error() string

func (WriteConcernError) NodeIsRecovering Uses

func (wce WriteConcernError) NodeIsRecovering() bool

NodeIsRecovering returns true if this error is a node is recovering error.

func (WriteConcernError) NodeIsShuttingDown Uses

func (wce WriteConcernError) NodeIsShuttingDown() bool

NodeIsShuttingDown returns true if this error is a node is shutting down error.

func (WriteConcernError) NotMaster Uses

func (wce WriteConcernError) NotMaster() bool

NotMaster returns true if this error is a not master error.

func (WriteConcernError) Retryable Uses

func (wce WriteConcernError) Retryable() bool

Retryable returns true if the error is retryable

type WriteError Uses

type WriteError struct {
    Index   int64
    Code    int64
    Message string
}

WriteError is a non-write concern failure that occurred as a result of a write operation.

func (WriteError) Error Uses

func (we WriteError) Error() string

type WriteErrors Uses

type WriteErrors []WriteError

WriteErrors is a group of non-write concern failures that occurred as a result of a write operation.

func (WriteErrors) Error Uses

func (we WriteErrors) Error() string

Directories

PathSynopsis
address
authPackage auth is not for public use.
connstring
description
dns
drivergen
drivertest
integration
operation
session
topologyPackage topology contains types that handles the discovery, monitoring, and selection of servers.
uuid
wiremessage

Package driver imports 22 packages (graph) and is imported by 6 packages. Updated 2019-08-13. Refresh now. Tools for package owners.