...

Package kivik

import "github.com/go-kivik/kivik/v4"
Overview
Index
Examples
Subdirectories

Overview ▾

Package kivik provides a generic interface to CouchDB or CouchDB-like databases.

The kivik package must be used in conjunction with a database driver. The officially supported drivers are:

The Filesystem and Memory drivers are also available, but in early stages of development, and so many features do not yet work:

The kivik driver system is modeled after the standard library's `sql` and `sql/driver` packages, although the client API is completely different due to the different database models implemented by SQL and NoSQL databases such as CouchDB.

The most methods, including those on Client and DB are safe to call concurrently, unless otherwise noted.

Working with JSON

CouchDB stores JSON, so Kivik translates Go data structures to and from JSON as necessary. The conversion from Go data types to JSON, and vice versa, is handled automatically according to the rules and behavior described in the documentation for the standard library's encoding/json package.

Options

Most client and database methods take optional arguments of the type Option. Multiple options may be passed, and latter options take precedence over earlier ones, in case of a conflict.

Params and Param can be used to set options that are generally converted to URL query parameters. Different backend drivers may also provide their own unique options with driver-specific effects. Consult your driver's documentation for specifics.

Error Handling

Kivik returns errors that embed an HTTP status code. In most cases, this is the HTTP status code returned by the server. The embedded HTTP status code may be accessed easily using the HTTPStatus() method, or with a type assertion to `interface { HTTPStatus() int }`. Example:

if statusErr, ok := err.(interface{ HTTPStatus() int }); ok {
	status = statusErr.HTTPStatus()
}

Any error that does not conform to this interface will be assumed to represent a http.StatusInternalServerError status code.

Authentication

For common usage, authentication should be as simple as including the authentication credentials in the connection DSN. For example:

client, err := kivik.New("couch", "http://admin:abc123@localhost:5984/")

This will connect to `localhost` on port 5984, using the username `admin` and the password `abc123`. When connecting to CouchDB (as in the above example), this will use cookie auth.

Depending on which driver you use, there may be other ways to authenticate, as well. At the moment, the CouchDB driver is the only official driver which offers additional authentication methods. Please refer to the CouchDB package documentation for details.

Example (Connecting)

With a client handle in hand, you can create a database handle with the DB() method to interact with a specific database.

Code:

client, err := kivik.New("couch", "http://example.com:5984/")
if err != nil {
    panic(err)
}
db := client.DB("_users")
fmt.Println("Database handle for " + db.Name())

Output:

Database handle for _users

Index ▾

Constants
func HTTPStatus(err error) int
func Register(name string, driver driver.Driver)
func ScanAllDocs(r *ResultSet, dest interface{}) error
func ScanAllValues(r *ResultSet, dest interface{}) error
type Attachment
    func (a *Attachment) MarshalJSON() ([]byte, error)
    func (a *Attachment) UnmarshalJSON(data []byte) error
type Attachments
    func (a *Attachments) Delete(filename string)
    func (a *Attachments) Get(filename string) *Attachment
    func (a *Attachments) Set(filename string, att *Attachment)
    func (a *Attachments) UnmarshalJSON(data []byte) error
type AttachmentsIterator
    func (i *AttachmentsIterator) Close() error
    func (i *AttachmentsIterator) Iterator() func(yield func(*Attachment, error) bool)
    func (i *AttachmentsIterator) Next() (*Attachment, error)
type BulkGetReference
type BulkResult
type Change
    func (c *Change) ScanDoc(dest interface{}) error
type Changes
    func (c *Changes) Changes() []string
    func (c *Changes) Close() error
    func (c *Changes) Deleted() bool
    func (c *Changes) ETag() string
    func (c *Changes) Err() error
    func (c *Changes) ID() string
    func (c *Changes) Iterator() func(yield func(*Change, error) bool)
    func (c *Changes) Metadata() (*ChangesMetadata, error)
    func (c *Changes) Next() bool
    func (c *Changes) ScanDoc(dest interface{}) error
    func (c *Changes) Seq() string
type ChangesMetadata
type Client
    func New(driverName, dataSourceName string, options ...Option) (*Client, error)
    func (c *Client) AllDBs(ctx context.Context, options ...Option) ([]string, error)
    func (c *Client) AllDBsStats(ctx context.Context, options ...Option) ([]*DBStats, error)
    func (c *Client) Close() error
    func (c *Client) ClusterSetup(ctx context.Context, action interface{}) error
    func (c *Client) ClusterStatus(ctx context.Context, options ...Option) (string, error)
    func (c *Client) Config(ctx context.Context, node string) (Config, error)
    func (c *Client) ConfigSection(ctx context.Context, node, section string) (ConfigSection, error)
    func (c *Client) ConfigValue(ctx context.Context, node, section, key string) (string, error)
    func (c *Client) CreateDB(ctx context.Context, dbName string, options ...Option) error
    func (c *Client) DB(dbName string, options ...Option) *DB
    func (c *Client) DBExists(ctx context.Context, dbName string, options ...Option) (bool, error)
    func (c *Client) DBUpdates(ctx context.Context, options ...Option) *DBUpdates
    func (c *Client) DBsStats(ctx context.Context, dbnames []string) ([]*DBStats, error)
    func (c *Client) DSN() string
    func (c *Client) DeleteConfigKey(ctx context.Context, node, section, key string) (string, error)
    func (c *Client) DestroyDB(ctx context.Context, dbName string, options ...Option) error
    func (c *Client) Driver() string
    func (c *Client) GetReplications(ctx context.Context, options ...Option) ([]*Replication, error)
    func (c *Client) Membership(ctx context.Context) (*ClusterMembership, error)
    func (c *Client) Ping(ctx context.Context) (bool, error)
    func (c *Client) Replicate(ctx context.Context, targetDSN, sourceDSN string, options ...Option) (*Replication, error)
    func (c *Client) Session(ctx context.Context) (*Session, error)
    func (c *Client) SetConfigValue(ctx context.Context, node, section, key, value string) (string, error)
    func (c *Client) Version(ctx context.Context) (*ServerVersion, error)
type ClusterConfig
type ClusterMembership
type Config
type ConfigSection
type DB
    func (db *DB) AllDocs(ctx context.Context, options ...Option) *ResultSet
    func (db *DB) BulkDocs(ctx context.Context, docs []interface{}, options ...Option) ([]BulkResult, error)
    func (db *DB) BulkGet(ctx context.Context, docs []BulkGetReference, options ...Option) *ResultSet
    func (db *DB) Changes(ctx context.Context, options ...Option) *Changes
    func (db *DB) Client() *Client
    func (db *DB) Close() error
    func (db *DB) Compact(ctx context.Context) error
    func (db *DB) CompactView(ctx context.Context, ddocID string) error
    func (db *DB) Copy(ctx context.Context, targetID, sourceID string, options ...Option) (targetRev string, err error)
    func (db *DB) CreateDoc(ctx context.Context, doc interface{}, options ...Option) (docID, rev string, err error)
    func (db *DB) CreateIndex(ctx context.Context, ddoc, name string, index interface{}, options ...Option) error
    func (db *DB) Delete(ctx context.Context, docID, rev string, options ...Option) (newRev string, err error)
    func (db *DB) DeleteAttachment(ctx context.Context, docID, rev, filename string, options ...Option) (newRev string, err error)
    func (db *DB) DeleteIndex(ctx context.Context, ddoc, name string, options ...Option) error
    func (db *DB) DesignDocs(ctx context.Context, options ...Option) *ResultSet
    func (db *DB) Err() error
    func (db *DB) Explain(ctx context.Context, query interface{}, options ...Option) (*QueryPlan, error)
    func (db *DB) Find(ctx context.Context, query interface{}, options ...Option) *ResultSet
    func (db *DB) Flush(ctx context.Context) error
    func (db *DB) Get(ctx context.Context, docID string, options ...Option) *Document
    func (db *DB) GetAttachment(ctx context.Context, docID, filename string, options ...Option) (*Attachment, error)
    func (db *DB) GetAttachmentMeta(ctx context.Context, docID, filename string, options ...Option) (*Attachment, error)
    func (db *DB) GetIndexes(ctx context.Context, options ...Option) ([]Index, error)
    func (db *DB) GetRev(ctx context.Context, docID string, options ...Option) (rev string, err error)
    func (db *DB) LocalDocs(ctx context.Context, options ...Option) *ResultSet
    func (db *DB) Name() string
    func (db *DB) OpenRevs(ctx context.Context, docID string, revs []string, options ...Option) *ResultSet
    func (db *DB) PartitionStats(ctx context.Context, name string) (*PartitionStats, error)
    func (db *DB) Purge(ctx context.Context, docRevMap map[string][]string) (*PurgeResult, error)
    func (db *DB) Put(ctx context.Context, docID string, doc interface{}, options ...Option) (rev string, err error)
    func (db *DB) PutAttachment(ctx context.Context, docID string, att *Attachment, options ...Option) (newRev string, err error)
    func (db *DB) Query(ctx context.Context, ddoc, view string, options ...Option) *ResultSet
    func (db *DB) RevsDiff(ctx context.Context, revMap interface{}) *ResultSet
    func (db *DB) Security(ctx context.Context) (*Security, error)
    func (db *DB) SetSecurity(ctx context.Context, security *Security) error
    func (db *DB) Stats(ctx context.Context) (*DBStats, error)
    func (db *DB) ViewCleanup(ctx context.Context) error
type DBStats
type DBUpdate
type DBUpdates
    func (f *DBUpdates) Close() error
    func (f *DBUpdates) DBName() string
    func (f *DBUpdates) Err() error
    func (f *DBUpdates) Iterator() func(yield func(*DBUpdate, error) bool)
    func (f *DBUpdates) LastSeq() (string, error)
    func (f *DBUpdates) Next() bool
    func (f *DBUpdates) Seq() string
    func (f *DBUpdates) Type() string
type Diffs
type Document
    func (r *Document) Attachments() (*AttachmentsIterator, error)
    func (r *Document) Close() error
    func (r *Document) Err() error
    func (r *Document) Rev() (string, error)
    func (r *Document) ScanDoc(i interface{}) error
type Index
type Members
type Option
    func Duration(key string, dur time.Duration) Option
    func IncludeDocs() Option
    func Param(key string, value interface{}) Option
    func Params(p map[string]interface{}) Option
    func ReplicateCallback(callback func(ReplicationEvent)) Option
    func ReplicateCopySecurity() Option
    func Rev(rev string) Option
type PartitionStats
type PurgeResult
type QueryPlan
type Replication
    func (r *Replication) Delete(ctx context.Context) error
    func (r *Replication) DocWriteFailures() int64
    func (r *Replication) DocsRead() int64
    func (r *Replication) DocsWritten() int64
    func (r *Replication) EndTime() time.Time
    func (r *Replication) Err() error
    func (r *Replication) IsActive() bool
    func (r *Replication) Progress() float64
    func (r *Replication) ReplicationID() string
    func (r *Replication) StartTime() time.Time
    func (r *Replication) State() ReplicationState
    func (r *Replication) Update(ctx context.Context) error
type ReplicationEvent
type ReplicationInfo
type ReplicationResult
    func Replicate(ctx context.Context, target, source *DB, options ...Option) (*ReplicationResult, error)
type ReplicationState
type ResultMetadata
type ResultSet
    func (r *ResultSet) Attachments() (*AttachmentsIterator, error)
    func (r *ResultSet) Close() error
    func (r *ResultSet) Err() error
    func (r *ResultSet) ID() (string, error)
    func (r *ResultSet) Iterator() func(yield func(*Row, error) bool)
    func (r *ResultSet) Key() (string, error)
    func (r *ResultSet) Metadata() (*ResultMetadata, error)
    func (r *ResultSet) Next() bool
    func (r *ResultSet) NextIterator() func(yield func() bool)
    func (r *ResultSet) NextResultSet() bool
    func (r *ResultSet) Rev() (string, error)
    func (r *ResultSet) ScanDoc(dest interface{}) error
    func (r *ResultSet) ScanKey(dest interface{}) error
    func (r *ResultSet) ScanValue(dest interface{}) error
type RevDiff
type Row
    func (r *Row) ID() (string, error)
    func (r *Row) Key() (json.RawMessage, error)
    func (r *Row) Rev() (string, error)
    func (r *Row) ScanDoc(dest interface{}) error
    func (r *Row) ScanKey(dest interface{}) error
    func (r *Row) ScanValue(dest interface{}) error
type Security
type ServerVersion
type Session

Package files

attachments.go bulk.go changes.go cluster.go config.go constants.go db.go doc.go document.go errors.go find.go iterator.go kivik.go options.go replicate.go replication.go resultset.go security.go session.go updates.go

Constants

const (
    // ErrClientClosed is returned by any client operations after [Client.Close]
    // has been called.
    ErrClientClosed = internal.CompositeError("503 client closed")
    // ErrDatabaseClosed is returned by any database operations after [DB.Close]
    // has been called.
    ErrDatabaseClosed = internal.CompositeError("503 database closed")
)

EndKeySuffix is a high Unicode character (0xfff0) useful for appending to an endkey argument, when doing a ranged search, as described here.

For example, to return all results with keys beginning with "foo":

rows, err := db.Query(context.TODO(), "ddoc", "view", kivik.Params(map[string]interface{}{
    "startkey": "foo",
    "endkey":   "foo" + kivik.EndKeySuffix,
}))
const EndKeySuffix = string(rune(0xfff0))

SessionCookieName is the name of the CouchDB session cookie.

const SessionCookieName = "AuthSession"

UserPrefix is the mandatory CouchDB user prefix.

const UserPrefix = "org.couchdb.user:"
const (
    // Version is the version of the Kivik library.
    Version = "4.3.2"
)

func HTTPStatus

func HTTPStatus(err error) int

HTTPStatus returns the HTTP status code embedded in the error, or 500 (internal server error), if there was no specified status code. If err is nil, HTTPStatus returns 0. This provides a convenient way to determine the precise nature of a Kivik-returned error.

For example, to panic for all but NotFound errors:

err := db.Get(context.TODO(), "docID").ScanDoc(&doc)
if kivik.HTTPStatus(err) == http.StatusNotFound {
    return
}
if err != nil {
    panic(err)
}

This method uses the statusCoder interface, which is not exported by this package, but is considered part of the stable public API. Driver implementations are expected to return errors which conform to this interface.

type statusCoder interface {
    HTTPStatus() int
}

Example

Code:

client, err := kivik.New("couch", "http://example.com:5984/")
if err != nil {
    panic(err)
}
row := client.DB("foo").Get(context.Background(), "my_doc_id")
switch err := row.Err(); kivik.HTTPStatus(err) {
case http.StatusNotFound:
    return
case http.StatusUnauthorized:
    panic("Authentication required")
case http.StatusForbidden:
    panic("You are not authorized")
default:
    panic("Unexpected error: " + err.Error())
}

func Register

func Register(name string, driver driver.Driver)

Register makes a database driver available by the provided name. If Register is called twice with the same name or if driver is nil, it panics.

func ScanAllDocs

func ScanAllDocs(r *ResultSet, dest interface{}) error

ScanAllDocs loops through the remaining documents in the resultset, and scans them into dest which must be a pointer to a slice or an array. Passing any other type will result in an error. If dest is an array, scanning will stop once the array is filled. The iterator is closed by this method. It is possible that an error will be returned, and that one or more documents were successfully scanned.

func ScanAllValues

func ScanAllValues(r *ResultSet, dest interface{}) error

ScanAllValues works like ScanAllDocs, but scans the values rather than docs.

type Attachment

Attachment represents a file attachment on a CouchDB document.

type Attachment struct {
    // Filename is the name of the attachment.
    Filename string `json:"-"`

    // ContentType is the Content-Type type of the attachment.
    ContentType string `json:"content_type"`

    // Stub will be true if the data structure only represents file metadata,
    // and contains no actual content. Stub will be true when returned by
    // [DB.GetAttachmentMeta], or when included in a document without the
    // 'include_docs' option.
    Stub bool `json:"stub"`

    // Follows will be true when reading attachments in multipart/related
    // format.
    Follows bool `json:"follows"`

    // Content represents the attachment's content.
    //
    // Kivik will always return a non-nil Content, even for 0-byte attachments
    // or when Stub is true. It is the caller's responsibility to close
    // Content.
    Content io.ReadCloser `json:"-"`

    // Size records the uncompressed size of the attachment. The value -1
    // indicates that the length is unknown. Unless [Attachment.Stub] is true,
    // values >= 0 indicate that the given number of bytes may be read from
    // [Attachment.Content].
    Size int64 `json:"length"`

    // Used compression codec, if any. Will be the empty string if the
    // attachment is uncompressed.
    ContentEncoding string `json:"encoding"`

    // EncodedLength records the compressed attachment size in bytes. Only
    // meaningful when [Attachment.ContentEncoding] is defined.
    EncodedLength int64 `json:"encoded_length"`

    // RevPos is the revision number when attachment was added.
    RevPos int64 `json:"revpos"`

    // Digest is the content hash digest.
    Digest string `json:"digest"`
}

func (*Attachment) MarshalJSON

func (a *Attachment) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the encoding/json.Marshaler interface.

func (*Attachment) UnmarshalJSON

func (a *Attachment) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the encoding/json.Unmarshaler interface.

type Attachments

Attachments is a collection of one or more file attachments.

type Attachments map[string]*Attachment

func (*Attachments) Delete

func (a *Attachments) Delete(filename string)

Delete removes the specified file from the collection.

func (*Attachments) Get

func (a *Attachments) Get(filename string) *Attachment

Get fetches the requested attachment, or returns nil if it does not exist.

func (*Attachments) Set

func (a *Attachments) Set(filename string, att *Attachment)

Set sets the attachment associated with filename in the collection, replacing it if it already exists.

func (*Attachments) UnmarshalJSON

func (a *Attachments) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the encoding/json.Unmarshaler interface.

type AttachmentsIterator

AttachmentsIterator allows reading streamed attachments from a multi-part DB.Get request.

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

func (*AttachmentsIterator) Close

func (i *AttachmentsIterator) Close() error

Close closes the AttachmentsIterator. It is automatically called when AttachmentsIterator.Next returns io.EOF.

func (*AttachmentsIterator) Iterator

func (i *AttachmentsIterator) Iterator() func(yield func(*Attachment, error) bool)

Iterator returns a function that can be used to iterate over the attachments. This function works with Go 1.23's range functions, and is an alternative to using AttachmentsIterator.Next directly.

func (*AttachmentsIterator) Next

func (i *AttachmentsIterator) Next() (*Attachment, error)

Next returns the next attachment in the stream. io.EOF will be returned when there are no more attachments.

The returned attachment is only valid until the next call to [Next], or a call to [Close].

type BulkGetReference

BulkGetReference is a reference to a document given to pass to DB.BulkGet.

type BulkGetReference struct {
    ID        string `json:"id"`
    Rev       string `json:"rev,omitempty"`
    AttsSince string `json:"atts_since,omitempty"`
}

type BulkResult

BulkResult is the result of a single BulkDoc update.

type BulkResult struct {
    ID    string `json:"id"`
    Rev   string `json:"rev"`
    Error error
}

type Change

Change represents a single change in the changes feed, as returned by Changes.Iterator.

!!NOTICE!! This struct is considered experimental, and may change without notice.

type Change struct {
    // ID is the document ID to which the change relates.
    ID string `json:"id"`
    // Seq is the update sequence for the changes feed.
    Seq string `json:"seq"`
    // Deleted is set to true for the changes feed, if the document has been
    // deleted.
    Deleted bool `json:"deleted"`
    // Changes represents a list of document leaf revisions for the /_changes
    // endpoint.
    Changes []string `json:"-"`
    // contains filtered or unexported fields
}

func (*Change) ScanDoc

func (c *Change) ScanDoc(dest interface{}) error

ScanDoc copies the data from the result into dest. See Row.ScanValue for additional details.

type Changes

Changes is an iterator over the database changes feed.

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

func (*Changes) Changes

func (c *Changes) Changes() []string

Changes returns a list of changed revs.

func (*Changes) Close

func (c *Changes) Close() error

Close closes the iterator, preventing further enumeration, and freeing any resources (such as the http request body) of the underlying feed. If Changes.Next is called and there are no further results, the iterator is closed automatically and it will suffice to check the result of Changes.Err. Close is idempotent and does not affect the result of Changes.Err.

func (*Changes) Deleted

func (c *Changes) Deleted() bool

Deleted returns true if the change relates to a deleted document.

func (*Changes) ETag

func (c *Changes) ETag() string

ETag returns the unquoted ETag header, if any.

func (*Changes) Err

func (c *Changes) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Changes.Close.

func (*Changes) ID

func (c *Changes) ID() string

ID returns the ID of the current result.

func (*Changes) Iterator

func (c *Changes) Iterator() func(yield func(*Change, error) bool)

Iterator returns a function that can be used to iterate over the changes feed. This function works with Go 1.23's range functions, and is an alternative to using Changes.Next directly.

!!NOTICE!! This function is considered experimental, and may change without notice.

func (*Changes) Metadata

func (c *Changes) Metadata() (*ChangesMetadata, error)

Metadata returns the result metadata for the changes feed. It must be called after Changes.Next returns false or Changes.Iterator has been completely and successfully iterated. Otherwise it will return an error.

func (*Changes) Next

func (c *Changes) Next() bool

Next prepares the next iterator result value for reading. It returns true on success, or false if there is no next result or an error occurs while preparing it. Changes.Err should be consulted to distinguish between the two.

func (*Changes) ScanDoc

func (c *Changes) ScanDoc(dest interface{}) error

ScanDoc copies the data from the result into dest. See ResultSet.ScanValue for additional details.

func (*Changes) Seq

func (c *Changes) Seq() string

Seq returns the Seq of the current result.

type ChangesMetadata

ChangesMetadata contains metadata about a changes feed.

type ChangesMetadata struct {
    // LastSeq is the last update sequence id present in the change set, if
    // returned by the server.
    LastSeq string
    // Pending is the count of remaining items in the change feed.
    Pending int64
}

type Client

Client is a client connection handle to a CouchDB-like server.

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

func New

func New(driverName, dataSourceName string, options ...Option) (*Client, error)

New creates a new client object specified by its database driver name and a driver-specific data source name.

The use of options is driver-specific, so consult with the documentation for your driver for supported options.

Example

New is used to create a client handle. `driver` specifies the name of the registered database driver and `dataSourceName` specifies the database-specific connection information, such as a URL.

Code:

client, err := kivik.New("driver", "http://example.com:5984/")
if err != nil {
    panic(err)
}
fmt.Println("Connected to", client.DSN())

Output:

Connected to http://example.com:5984/

func (*Client) AllDBs

func (c *Client) AllDBs(ctx context.Context, options ...Option) ([]string, error)

AllDBs returns a list of all databases.

func (*Client) AllDBsStats

func (c *Client) AllDBsStats(ctx context.Context, options ...Option) ([]*DBStats, error)

AllDBsStats returns database statistics for all databases. If the driver does not natively support this operation, it will be emulated by effectively calling Client.AllDBs followed by [DB.DBsStats].

See the CouchDB documentation for accepted options.

func (*Client) Close

func (c *Client) Close() error

Close cleans up any resources used by the client. Close is safe to call concurrently with other operations and will block until all other operations finish. After calling Close, any other client operations will return ErrClientClosed.

func (*Client) ClusterSetup

func (c *Client) ClusterSetup(ctx context.Context, action interface{}) error

ClusterSetup performs the requested cluster action. action should be an object understood by the driver. For the CouchDB driver, this means an object which is marshalable to a JSON object of the expected format.

func (*Client) ClusterStatus

func (c *Client) ClusterStatus(ctx context.Context, options ...Option) (string, error)

ClusterStatus returns the current cluster status.

func (*Client) Config

func (c *Client) Config(ctx context.Context, node string) (Config, error)

Config returns the entire server config, for the specified node.

func (*Client) ConfigSection

func (c *Client) ConfigSection(ctx context.Context, node, section string) (ConfigSection, error)

ConfigSection returns the requested server [config section] for the specified node.

func (*Client) ConfigValue

func (c *Client) ConfigValue(ctx context.Context, node, section, key string) (string, error)

ConfigValue returns a single config value for the specified node.

func (*Client) CreateDB

func (c *Client) CreateDB(ctx context.Context, dbName string, options ...Option) error

CreateDB creates a DB of the requested name.

func (*Client) DB

func (c *Client) DB(dbName string, options ...Option) *DB

DB returns a handle to the requested database. Any errors encountered during initiation of the DB object is deferred until the first method call, or may be checked directly with DB.Err.

func (*Client) DBExists

func (c *Client) DBExists(ctx context.Context, dbName string, options ...Option) (bool, error)

DBExists returns true if the specified database exists.

func (*Client) DBUpdates

func (c *Client) DBUpdates(ctx context.Context, options ...Option) *DBUpdates

DBUpdates begins polling for database updates. Canceling the context will close the iterator. The iterator will also close automatically if there are no more updates, when an error occurs, or when the DBUpdates.Close method is called. The DBUpdates.Err method should be consulted to determine if there was an error during iteration.

For historical reasons, the CouchDB driver's implementation of this function defaults to feed=continuous and since=now. To use the default CouchDB behavior, set feed to either the empty string or "normal", and since to the empty string. In kivik/v5, the default behavior will be to use feed=normal as CouchDB does by default.

func (*Client) DBsStats

func (c *Client) DBsStats(ctx context.Context, dbnames []string) ([]*DBStats, error)

DBsStats returns database statistics about one or more databases.

func (*Client) DSN

func (c *Client) DSN() string

DSN returns the data source name used to connect this client.

func (*Client) DeleteConfigKey

func (c *Client) DeleteConfigKey(ctx context.Context, node, section, key string) (string, error)

DeleteConfigKey deletes the configuration key and associated value from the specified node. It returns the old value.

func (*Client) DestroyDB

func (c *Client) DestroyDB(ctx context.Context, dbName string, options ...Option) error

DestroyDB deletes the requested DB.

func (*Client) Driver

func (c *Client) Driver() string

Driver returns the name of the driver string used to connect this client.

func (*Client) GetReplications

func (c *Client) GetReplications(ctx context.Context, options ...Option) ([]*Replication, error)

GetReplications returns a list of defined replications in the _replicator database. Options are in the same format as to DB.AllDocs, except that "conflicts" and "update_seq" are ignored.

func (*Client) Membership

func (c *Client) Membership(ctx context.Context) (*ClusterMembership, error)

Membership returns a list of known CouchDB nodes in the cluster.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) (bool, error)

Ping returns true if the database is online and available for requests.

func (*Client) Replicate

func (c *Client) Replicate(ctx context.Context, targetDSN, sourceDSN string, options ...Option) (*Replication, error)

Replicate initiates a replication from source to target.

To use an object for either "source" or "target", pass the desired object in options. This will override targetDSN and sourceDSN function parameters.

func (*Client) Session

func (c *Client) Session(ctx context.Context) (*Session, error)

Session returns information about the currently authenticated user.

func (*Client) SetConfigValue

func (c *Client) SetConfigValue(ctx context.Context, node, section, key, value string) (string, error)

SetConfigValue sets the server's config value on the specified node, creating the key if it doesn't exist. It returns the old value.

func (*Client) Version

func (c *Client) Version(ctx context.Context) (*ServerVersion, error)

Version returns version and vendor info about the backend.

type ClusterConfig

ClusterConfig contains the cluster configuration for the database.

type ClusterConfig struct {
    Replicas    int `json:"n"`
    Shards      int `json:"q"`
    ReadQuorum  int `json:"r"`
    WriteQuorum int `json:"w"`
}

type ClusterMembership

ClusterMembership contains the list of known nodes, and cluster nodes, as returned by Client.Membership.

type ClusterMembership struct {
    AllNodes     []string `json:"all_nodes"`
    ClusterNodes []string `json:"cluster_nodes"`
}

type Config

Config represents all the config sections.

type Config map[string]ConfigSection

type ConfigSection

ConfigSection represents all key/value pairs for a section of configuration.

type ConfigSection map[string]string

type DB

DB is a handle to a specific database.

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

func (*DB) AllDocs

func (db *DB) AllDocs(ctx context.Context, options ...Option) *ResultSet

AllDocs returns a list of all documents in the database.

func (*DB) BulkDocs

func (db *DB) BulkDocs(ctx context.Context, docs []interface{}, options ...Option) ([]BulkResult, error)

BulkDocs allows you to create and update multiple documents at the same time within a single request. This function returns an iterator over the results of the bulk operation.

See the CouchDB documentation.

As with DB.Put, each individual document may be a JSON-marshable object, or a raw JSON string in a encoding/json.RawMessage, or io.Reader.

func (*DB) BulkGet

func (db *DB) BulkGet(ctx context.Context, docs []BulkGetReference, options ...Option) *ResultSet

BulkGet can be called to query several documents in bulk. It is well suited for fetching a specific revision of documents, as replicators do for example, or for getting revision history.

See the CouchDB documentation.

func (*DB) Changes

func (db *DB) Changes(ctx context.Context, options ...Option) *Changes

Changes returns an iterator over the real-time changes feed. The feed remains open until explicitly closed, or an error is encountered.

func (*DB) Client

func (db *DB) Client() *Client

Client returns the client used to connect to the database.

func (*DB) Close

func (db *DB) Close() error

Close cleans up any resources used by the DB. Close is safe to call concurrently with other DB operations and will block until all other DB operations finish. After calling Close, any other DB operations will return ErrDatabaseClosed.

func (*DB) Compact

func (db *DB) Compact(ctx context.Context) error

Compact begins compaction of the database. Check the CompactRunning field returned by DB.Stats to see if the compaction has completed.

See the CouchDB documentation.

This method may return immediately, or may wait for the compaction to complete before returning, depending on the backend implementation. In particular, CouchDB triggers the compaction and returns immediately, whereas PouchDB waits until compaction has completed, before returning.

func (*DB) CompactView

func (db *DB) CompactView(ctx context.Context, ddocID string) error

CompactView compats the view indexes associated with the specified design document.

See the CouchDB documentation.

This method may return immediately, or may wait for the compaction to complete before returning, depending on the backend implementation. In particular, CouchDB triggers the compaction and returns immediately, whereas PouchDB waits until compaction has completed, before returning.

func (*DB) Copy

func (db *DB) Copy(ctx context.Context, targetID, sourceID string, options ...Option) (targetRev string, err error)

Copy copies the source document to a new document with an ID of targetID. If the database backend does not support COPY directly, the operation will be emulated with a Get followed by Put. The target will be an exact copy of the source, with only the ID and revision changed.

See the CouchDB documentation:

func (*DB) CreateDoc

func (db *DB) CreateDoc(ctx context.Context, doc interface{}, options ...Option) (docID, rev string, err error)

CreateDoc creates a new doc with an auto-generated unique ID. The generated docID and new rev are returned.

Example

Storing a document is done with Put or CreateDoc, which correspond to `PUT /{db}/{doc}` and `POST /{db}` respectively. In most cases, you should use Put.

Code:

type Animal struct {
    ID       string `json:"_id"`
    Rev      string `json:"_rev,omitempty"`
    Feet     int    `json:"feet"`
    Greeting string `json:"greeting"`
}

cow := Animal{Feet: 4, Greeting: "moo"}
docID, rev, err := db.CreateDoc(context.TODO(), cow)
if err != nil {
    panic(err)
}
cow.ID = docID
cow.Rev = rev

func (*DB) CreateIndex

func (db *DB) CreateIndex(ctx context.Context, ddoc, name string, index interface{}, options ...Option) error

CreateIndex creates an index if it doesn't already exist. ddoc and name may be empty, in which case they will be auto-generated. index must be marshalable to a valid index object, as described in the CouchDB documentation.

func (*DB) Delete

func (db *DB) Delete(ctx context.Context, docID, rev string, options ...Option) (newRev string, err error)

Delete marks the specified document as deleted. The revision may be provided via options, which takes priority over the rev argument.

Example

As with updating a document, deletion depends on the proper _rev parameter.

Code:

newRev, err := db.Delete(context.TODO(), "cow", "2-9c65296036141e575d32ba9c034dd3ee")
if err != nil {
    panic(err)
}
fmt.Printf("The tombstone document has revision %s\n", newRev)

func (*DB) DeleteAttachment

func (db *DB) DeleteAttachment(ctx context.Context, docID, rev, filename string, options ...Option) (newRev string, err error)

DeleteAttachment deletes an attachment from a document, returning the document's new revision. The revision may be provided via options, which takes priority over the rev argument.

func (*DB) DeleteIndex

func (db *DB) DeleteIndex(ctx context.Context, ddoc, name string, options ...Option) error

DeleteIndex deletes the requested index.

func (*DB) DesignDocs

func (db *DB) DesignDocs(ctx context.Context, options ...Option) *ResultSet

DesignDocs returns a list of all documents in the database.

func (*DB) Err

func (db *DB) Err() error

Err returns the error, if any, that occurred while connecting to or creating the database. This error will be deferred until the next call, normally, so using this method is only necessary if you need to directly check the error, and intend to do nothing else with the DB object.

func (*DB) Explain

func (db *DB) Explain(ctx context.Context, query interface{}, options ...Option) (*QueryPlan, error)

Explain returns the query plan for a given query. Explain takes the same arguments as DB.Find.

func (*DB) Find

func (db *DB) Find(ctx context.Context, query interface{}, options ...Option) *ResultSet

Find executes a query using the _find interface. The query must be a string, []byte, or encoding/json.RawMessage value, or JSON-marshalable to a valid valid query. The options are merged with the query, and will overwrite any values in the query.

This arguments this method accepts will change in Kivik 5.x, to be more consistent with the rest of the Kivik API. See issue #1014 for details.

func (*DB) Flush

func (db *DB) Flush(ctx context.Context) error

Flush requests a flush of disk cache to disk or other permanent storage.

See the CouchDB documentation.

func (*DB) Get

func (db *DB) Get(ctx context.Context, docID string, options ...Option) *Document

Get fetches the requested document. Any errors are deferred until the first call to ResultSet.ScanDoc or any other result set method.

Example

When fetching a document, the document will be unmarshaled from JSON into your structure by the row.ScanDoc method.

Code:

type Animal struct {
    ID       string `json:"_id"`
    Rev      string `json:"_rev,omitempty"`
    Feet     int    `json:"feet"`
    Greeting string `json:"greeting"`
}

var cow Animal
err := db.Get(context.TODO(), "cow").ScanDoc(&cow)
if err != nil {
    panic(err)
}
fmt.Printf("The cow says '%s'\n", cow.Greeting)

func (*DB) GetAttachment

func (db *DB) GetAttachment(ctx context.Context, docID, filename string, options ...Option) (*Attachment, error)

GetAttachment returns a file attachment associated with the document.

func (*DB) GetAttachmentMeta

func (db *DB) GetAttachmentMeta(ctx context.Context, docID, filename string, options ...Option) (*Attachment, error)

GetAttachmentMeta returns meta data about an attachment. The attachment content returned will be empty.

func (*DB) GetIndexes

func (db *DB) GetIndexes(ctx context.Context, options ...Option) ([]Index, error)

GetIndexes returns the indexes defined on the current database.

func (*DB) GetRev

func (db *DB) GetRev(ctx context.Context, docID string, options ...Option) (rev string, err error)

GetRev returns the active rev of the specified document. GetRev accepts the same options as DB.Get.

func (*DB) LocalDocs

func (db *DB) LocalDocs(ctx context.Context, options ...Option) *ResultSet

LocalDocs returns a list of all documents in the database.

func (*DB) Name

func (db *DB) Name() string

Name returns the database name as passed when creating the DB connection.

func (*DB) OpenRevs

func (db *DB) OpenRevs(ctx context.Context, docID string, revs []string, options ...Option) *ResultSet

OpenRevs returns documents of specified leaf revisions. Additionally, it accepts a revs value of "all" to return all leaf revisions.

This function is experimental, and may change without notice.

func (*DB) PartitionStats

func (db *DB) PartitionStats(ctx context.Context, name string) (*PartitionStats, error)

PartitionStats returns statistics about the named partition.

See the CouchDB documentation.

func (*DB) Purge

func (db *DB) Purge(ctx context.Context, docRevMap map[string][]string) (*PurgeResult, error)

Purge permanently removes the reference to deleted documents from the database. Normal deletion only marks the document with the key/value pair `_deleted=true`, to ensure proper replication of deleted documents. By using Purge, the document can be completely removed. But note that this operation is not replication safe, so great care must be taken when using Purge, and this should only be used as a last resort.

Purge expects as input a map with document ID as key, and slice of revisions as value.

func (*DB) Put

func (db *DB) Put(ctx context.Context, docID string, doc interface{}, options ...Option) (rev string, err error)

Put creates a new doc or updates an existing one, with the specified docID. If the document already exists, the current revision must be included in doc, with JSON key '_rev', otherwise a conflict will occur. The new rev is returned.

doc may be one of:

Example

Updating a document is the same as storing one, except that the `_rev` parameter must match that stored on the server.

Code:

cow.Rev = "1-6e609020e0371257432797b4319c5829" // Must be set
cow.Greeting = "Moo!"
newRev, err := db.Put(context.TODO(), "cow", cow)
if err != nil {
    panic(err)
}
cow.Rev = newRev

Example (UpdateView)

Design documents are treated identically to normal documents by both CouchDB and Kivik. The only difference is the document ID. Store your document normally, formatted with your views (or other functions).

Code:

_, err := db.Put(context.TODO(), "_design/foo", map[string]interface{}{
    "_id": "_design/foo",
    "views": map[string]interface{}{
        "foo_view": map[string]interface{}{
            "map": "function(doc) { emit(doc._id) }",
        },
    },
})
if err != nil {
    panic(err)
}

func (*DB) PutAttachment

func (db *DB) PutAttachment(ctx context.Context, docID string, att *Attachment, options ...Option) (newRev string, err error)

PutAttachment uploads the supplied content as an attachment to the specified document.

func (*DB) Query

func (db *DB) Query(ctx context.Context, ddoc, view string, options ...Option) *ResultSet

Query executes the specified view function from the specified design document. ddoc and view may or may not be be prefixed with '_design/' and '_view/' respectively.

See views in the CouchDB documentation.

If supported by the backend and database (i.e. CouchDB 2.2+), you may pass multiple queries to a single view by passing an option called `queries` with a multi-query object as a value.

See multiple queries in the CouchDB documentation.

Example

Code:

rs := db.Query(context.TODO(), "_design/foo", "_view/bar", kivik.Params(map[string]interface{}{
    "startkey": `foo`,
    "endkey":   `foo` + kivik.EndKeySuffix,
}))
defer rs.Close()
for rs.Next() {
    var doc interface{}
    if err := rs.ScanDoc(&doc); err != nil {
        panic(err)
    }
    /* do something with doc */
}
if rs.Err() != nil {
    panic(rs.Err())
}

Example (CompoundKey)

Code:

rs := db.Query(context.TODO(), "_design/foo", "_view/bar", kivik.Params(map[string]interface{}{
    "startkey": []string{"foo", "bar"},
    "endkey":   []string{"foo", "bar" + kivik.EndKeySuffix},
}))
defer rs.Close()
for rs.Next() {
    var doc interface{}
    if err := rs.ScanDoc(&doc); err != nil {
        panic(err)
    }
    /* do something with doc */
}
if rs.Err() != nil {
    panic(rs.Err())
}

Example (LiteralJSONKeys)

Code:

rs := db.Query(context.TODO(), "_design/foo", "_view/bar", kivik.Param(
    "startkey", json.RawMessage(`{"foo":true}`),
))
defer rs.Close()
for rs.Next() {
    var doc interface{}
    if err := rs.ScanDoc(&doc); err != nil {
        panic(err)
    }
    /* do something with doc */
}
if rs.Err() != nil {
    panic(rs.Err())
}

Example (MapReduce)

Code:

opts := kivik.Param("group", true)
rows := db.Query(context.TODO(), "_design/foo", "_view/bar", opts)
if err := rows.Err(); err != nil {
    panic(err)
}
for rows.Next() {
    /* ... */
}

Example (Multiple)

Code:

rs := db.Query(context.TODO(), "_design/foo", "_view/bar", kivik.Param(
    "queries", []interface{}{
        map[string]interface{}{
            "startkey":     []string{"foo", "bar"},
            "endkey":       []string{"foo", "bar" + kivik.EndKeySuffix},
            "include_docs": true,
        },
        map[string]interface{}{
            "startkey":     []string{"baz", "bar"},
            "endkey":       []string{"baz", "bar" + kivik.EndKeySuffix},
            "include_docs": true,
        },
    }))
defer rs.Close()
var rsIndex int
for rs.NextResultSet() {
    rsIndex++
    for rs.Next() {
        var doc interface{}
        if err := rs.ScanDoc(&doc); err != nil {
            panic(err)
        }
        /* do something with doc */
    }
}

func (*DB) RevsDiff

func (db *DB) RevsDiff(ctx context.Context, revMap interface{}) *ResultSet

RevsDiff returns the subset of document/revision IDs that do not correspond to revisions stored in the database. This is used by the replication protocol, and is normally never needed otherwise. revMap must marshal to the expected format.

Use ResultSet.ID to return the current document ID, and ResultSet.ScanValue to access the full JSON value. The [RevsDiff] type matches this format and is provided as a convenience for unmarshaling.

{
    "missing": ["rev1",...],
    "possible_ancestors": ["revA",...]
}

func (*DB) Security

func (db *DB) Security(ctx context.Context) (*Security, error)

Security returns the database's security document.

See the CouchDB documentation.

func (*DB) SetSecurity

func (db *DB) SetSecurity(ctx context.Context, security *Security) error

SetSecurity sets the database's security document.

See the CouchDB documentation.

func (*DB) Stats

func (db *DB) Stats(ctx context.Context) (*DBStats, error)

Stats returns database statistics. See the CouchDB documentation.

func (*DB) ViewCleanup

func (db *DB) ViewCleanup(ctx context.Context) error

ViewCleanup removes view index files that are no longer required as a result of changed views within design documents.

See the CouchDB documentation.

type DBStats

DBStats contains database statistics..

type DBStats struct {
    // Name is the name of the database.
    Name string `json:"db_name"`
    // CompactRunning is true if the database is currently being compacted.
    CompactRunning bool `json:"compact_running"`
    // DocCount is the number of documents are currently stored in the database.
    DocCount int64 `json:"doc_count"`
    // DeletedCount is a count of documents which have been deleted from the
    // database.
    DeletedCount int64 `json:"doc_del_count"`
    // UpdateSeq is the current update sequence for the database.
    UpdateSeq string `json:"update_seq"`
    // DiskSize is the number of bytes used on-disk to store the database.
    DiskSize int64 `json:"disk_size"`
    // ActiveSize is the number of bytes used on-disk to store active documents.
    // If this number is lower than [DBStats.DiskSize], then compaction would
    // free disk space.
    ActiveSize int64 `json:"data_size"`
    // ExternalSize is the size of the documents in the database, as represented
    // as JSON, before compression.
    ExternalSize int64 `json:"-"`
    // Cluster reports the cluster replication configuration variables.
    Cluster *ClusterConfig `json:"cluster,omitempty"`
    // RawResponse is the raw response body returned by the server, useful if
    // you need additional backend-specific information.
    //
    // For the format of this document, see the [CouchDB documentation].
    //
    // [CouchDB documentation]: http://docs.couchdb.org/en/2.1.1/api/database/common.html#get--db
    RawResponse json.RawMessage `json:"-"`
}

type DBUpdate

DBUpdate represents a database update as returned by DBUpdates.Iterator.

!!NOTICE!! This struct is considered experimental, and may change without notice.

type DBUpdate struct {
    DBName string `json:"db_name"`
    Type   string `json:"type"`
    Seq    string `json:"seq"`
}

type DBUpdates

DBUpdates is an iterator for database updates.

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

func (*DBUpdates) Close

func (f *DBUpdates) Close() error

Close closes the iterator, preventing further enumeration, and freeing any resources (such as the http request body) of the underlying feed. If DBUpdates.Next is called and there are no further results, the iterator is closed automatically and it will suffice to check the result of DBUpdates.Err. Close is idempotent and does not affect the result of DBUpdates.Err.

func (*DBUpdates) DBName

func (f *DBUpdates) DBName() string

DBName returns the database name for the current update.

func (*DBUpdates) Err

func (f *DBUpdates) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit DBUpdates.Close.

func (*DBUpdates) Iterator

func (f *DBUpdates) Iterator() func(yield func(*DBUpdate, error) bool)

Iterator returns a function that can be used to iterate over the DB updates feed. This function works with Go 1.23's range functions, and is an alternative to using DBUpdates.Next directly.

!!NOTICE!! This function is considered experimental, and may change without notice.

func (*DBUpdates) LastSeq

func (f *DBUpdates) LastSeq() (string, error)

LastSeq returns the last sequence ID reported, or in the case no results were returned due to `since` being set to `now`, or some other value that excludes all results, the current sequence ID. It must be called after DBUpdates.Next returns false or DBUpdates.Iterator has been completely and successfully iterated. Otherwise it will return an error.

func (*DBUpdates) Next

func (f *DBUpdates) Next() bool

Next prepares the next iterator result value for reading. It returns true on success, or false if there is no next result or an error occurs while preparing it. DBUpdates.Err should be consulted to distinguish between the two.

func (*DBUpdates) Seq

func (f *DBUpdates) Seq() string

Seq returns the update sequence of the current update.

func (*DBUpdates) Type

func (f *DBUpdates) Type() string

Type returns the type of the current update.

type Diffs

Diffs is a collection of RevDiff values as returned by DB.RevsDiff. The map key is the document ID.

type Diffs map[string]RevDiff

type Document

Document is a single document result returned by DB.Get.

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

func (*Document) Attachments

func (r *Document) Attachments() (*AttachmentsIterator, error)

Attachments returns an attachments iterator if the document includes attachments and they are not inline.

func (*Document) Close

func (r *Document) Close() error

Close closes the document resources.

func (*Document) Err

func (r *Document) Err() error

Err returns the error, if any, that was encountered fetching the document.

func (*Document) Rev

func (r *Document) Rev() (string, error)

Rev returns the document revision.

func (*Document) ScanDoc

func (r *Document) ScanDoc(i interface{}) error

ScanDoc unmarshals the document into i.

type Index

Index is a MonboDB-style index definition.

type Index struct {
    DesignDoc  string      `json:"ddoc,omitempty"`
    Name       string      `json:"name"`
    Type       string      `json:"type"`
    Definition interface{} `json:"def"`
}

type Members

Members represents the members of a database security document.

type Members struct {
    Names []string `json:"names,omitempty"`
    Roles []string `json:"roles,omitempty"`
}

type Option

Option is a Kivik or driver option.

Most methods/endpoints take query parameters which are passed as part of the query URL, as documented in the official CouchDB documentation. You can use Params or Param to set arbitrary query parameters. Backend drivers may provide their own special-purpose options as well.

type Option interface {
    // Apply applies the option to target, if target is of the expected type.
    // Unexpected/recognized target types should be ignored.
    Apply(target interface{})
}

func Duration

func Duration(key string, dur time.Duration) Option

Duration is a convenience function for setting query parameters from time.Duration values. The duration will be converted to milliseconds when passed as a query parameter.

For example, Duration("heartbeat", 15 * time.Second) will result in appending ?heartbeat=15000 to the query.

func IncludeDocs

func IncludeDocs() Option

IncludeDocs instructs the query to include documents. A less verbose alternative to Param("include_docs", true).

func Param

func Param(key string, value interface{}) Option

Param sets a single key/value pair as a query parameter.

func Params

func Params(p map[string]interface{}) Option

Params allows passing a collection of key/value pairs as query parameter options.

func ReplicateCallback

func ReplicateCallback(callback func(ReplicationEvent)) Option

ReplicateCallback sets a callback function to be called on every replication event that takes place.

func ReplicateCopySecurity

func ReplicateCopySecurity() Option

ReplicateCopySecurity will read the security object from source, and copy it to the target, before the replication. Use with caution! The security object is not versioned, and it will be unconditionally overwritten on the target!

func Rev

func Rev(rev string) Option

Rev is a convenience function to set the revision. A less verbose alternative to Param("rev", rev).

type PartitionStats

PartitionStats contains partition statistics.

type PartitionStats struct {
    DBName          string
    DocCount        int64
    DeletedDocCount int64
    Partition       string
    ActiveSize      int64
    ExternalSize    int64
    RawResponse     json.RawMessage
}

type PurgeResult

PurgeResult is the result of a purge request.

type PurgeResult struct {
    // Seq is the purge sequence number.
    Seq int64 `json:"purge_seq"`
    // Purged is a map of document ids to revisions, indicated the
    // document/revision pairs that were successfully purged.
    Purged map[string][]string `json:"purged"`
}

type QueryPlan

QueryPlan is the query execution plan for a query, as returned by DB.Explain.

type QueryPlan struct {
    DBName   string                 `json:"dbname"`
    Index    map[string]interface{} `json:"index"`
    Selector map[string]interface{} `json:"selector"`
    Options  map[string]interface{} `json:"opts"`
    Limit    int64                  `json:"limit"`
    Skip     int64                  `json:"skip"`

    // Fields is the list of fields to be returned in the result set, or
    // an empty list if all fields are to be returned.
    Fields []interface{}          `json:"fields"`
    Range  map[string]interface{} `json:"range"`
}

type Replication

Replication represents a CouchDB replication process.

type Replication struct {
    Source string
    Target string
    // contains filtered or unexported fields
}

func (*Replication) Delete

func (r *Replication) Delete(ctx context.Context) error

Delete deletes a replication. If it is currently running, it will be cancelled.

func (*Replication) DocWriteFailures

func (r *Replication) DocWriteFailures() int64

DocWriteFailures returns the number of doc write failures, if known.

func (*Replication) DocsRead

func (r *Replication) DocsRead() int64

DocsRead returns the number of documents read, if known.

func (*Replication) DocsWritten

func (r *Replication) DocsWritten() int64

DocsWritten returns the number of documents written, if known.

func (*Replication) EndTime

func (r *Replication) EndTime() time.Time

EndTime returns the replication end time, once the replication has terminated.

func (*Replication) Err

func (r *Replication) Err() error

Err returns the error, if any, that caused the replication to abort.

func (*Replication) IsActive

func (r *Replication) IsActive() bool

IsActive returns true if the replication has not yet completed or errored.

func (*Replication) Progress

func (r *Replication) Progress() float64

Progress returns the current replication progress, if known.

func (*Replication) ReplicationID

func (r *Replication) ReplicationID() string

ReplicationID returns the _replication_id field of the replicator document.

func (*Replication) StartTime

func (r *Replication) StartTime() time.Time

StartTime returns the replication start time, once the replication has been triggered.

func (*Replication) State

func (r *Replication) State() ReplicationState

State returns the current replication state

func (*Replication) Update

func (r *Replication) Update(ctx context.Context) error

Update requests a replication state update from the server. If there is an error retrieving the update, it is returned and the replication state is unaltered.

type ReplicationEvent

ReplicationEvent is an event emitted by the Replicate function, which represents a single read or write event, and its status.

type ReplicationEvent struct {
    // Type is the event type. Options are:
    //
    // - "security" -- Relates to the _security document.
    // - "changes"  -- Relates to the changes feed.
    // - "change"   -- Relates to a single change.
    // - "revsdiff" -- Relates to reading the revs diff.
    // - "document" -- Relates to a specific document.
    Type string
    // Read is true if the event relates to a read operation.
    Read bool
    // DocID is the relevant document ID, if any.
    DocID string
    // Error is the error associated with the event, if any.
    Error error
    // Changes is the list of changed revs, for a "change" event.
    Changes []string
}

type ReplicationInfo

ReplicationInfo represents a snapshot of the status of a replication.

type ReplicationInfo struct {
    DocWriteFailures int64
    DocsRead         int64
    DocsWritten      int64
    Progress         float64
}

type ReplicationResult

ReplicationResult represents the result of a replication.

type ReplicationResult struct {
    DocWriteFailures int       `json:"doc_write_failures"`
    DocsRead         int       `json:"docs_read"`
    DocsWritten      int       `json:"docs_written"`
    EndTime          time.Time `json:"end_time"`
    MissingChecked   int       `json:"missing_checked"`
    MissingFound     int       `json:"missing_found"`
    StartTime        time.Time `json:"start_time"`
}

func Replicate

func Replicate(ctx context.Context, target, source *DB, options ...Option) (*ReplicationResult, error)

Replicate performs a replication from source to target, using a limited version of the CouchDB replication protocol.

This function supports the ReplicateCopySecurity and ReplicateCallback options. Additionally, the following standard options are passed along to the source when querying the changes feed, for server-side filtering, where supported:

filter (string)           - The name of a filter function.
doc_ids (array of string) - Array of document IDs to be synchronized.

type ReplicationState

ReplicationState represents a replication's state

type ReplicationState string

The possible values for the _replication_state field in _replicator documents plus a blank value for unstarted replications.

const (
    ReplicationNotStarted ReplicationState = ""
    ReplicationStarted    ReplicationState = "triggered"
    ReplicationError      ReplicationState = "error"
    ReplicationComplete   ReplicationState = "completed"
)

The additional possible values for the state field in the _scheduler docs.

const (
    ReplicationInitializing ReplicationState = "initializing"
    ReplicationRunning      ReplicationState = "running"
    ReplicationPending      ReplicationState = "pending"
    ReplicationCrashing     ReplicationState = "crashing"
    ReplicationFailed       ReplicationState = "failed"
)

type ResultMetadata

ResultMetadata contains metadata about certain queries.

type ResultMetadata struct {
    // Offset is the starting offset where the result set started.
    Offset int64

    // TotalRows is the total number of rows in the view which would have been
    // returned if no limiting were used.
    TotalRows int64

    // UpdateSeq is the sequence id of the underlying database the view
    // reflects, if requested in the query.
    UpdateSeq string

    // Warning is a warning generated by the query, if any.
    Warning string

    // Bookmark is the paging bookmark, if one was provided with the result
    // set. This is intended for use with the Mango /_find interface, with
    // CouchDB 2.1.1 and later. Consult the [CouchDB documentation] for
    // detailed usage instructions.
    //
    // [CouchDB documentation]: http://docs.couchdb.org/en/2.1.1/api/database/find.html#pagination
    Bookmark string
}

type ResultSet

ResultSet is an iterator over a multi-value query result set.

Call ResultSet.Next to advance the iterator to the next item in the result set.

The Scan* methods are expected to be called only once per iteration, as they may consume data from the network, rendering them unusable a second time.

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

func (*ResultSet) Attachments

func (r *ResultSet) Attachments() (*AttachmentsIterator, error)

Attachments returns an attachments iterator if the document includes attachments.

func (*ResultSet) Close

func (r *ResultSet) Close() error

Close closes the result set, preventing further iteration, and freeing any resources (such as the HTTP request body) of the underlying query. Close is idempotent and does not affect the result of ResultSet.Err. Close is safe to call concurrently with other ResultSet operations and will block until all other ResultSet operations finish.

func (*ResultSet) Err

func (r *ResultSet) Err() error

Err returns the error, if any, that was encountered during iteration. ResultSet.Err may be called after an explicit or implicit call to ResultSet.Close.

func (*ResultSet) ID

func (r *ResultSet) ID() (string, error)

ID returns the ID of the most recent result.

func (*ResultSet) Iterator

func (r *ResultSet) Iterator() func(yield func(*Row, error) bool)

Iterator returns a function that can be used to iterate over all rows in the result set(s). This function is the analogue to ResultSet.Next for Go 1.23's new range functions. When the iterator returns an error, it means that iteration has failed. For row-specific errors, check the value of [Row.Err].

If your ResultSet contains multiple result sets, this iterator will iterate over all of them, without distinction. If you need to iterate over each result set individually, use ResultSet.NextIterator.

!!NOTICE!! This function is considered experimental, and may change without notice.

func (*ResultSet) Key

func (r *ResultSet) Key() (string, error)

Key returns the Key of the most recent result as a raw JSON string. For compound keys, ResultSet.ScanKey may be more convenient.

func (*ResultSet) Metadata

func (r *ResultSet) Metadata() (*ResultMetadata, error)

Metadata returns the result metadata for the current query. It must be called after ResultSet.Next returns false or [ResultSetIterator] has been completely and successfully iterated. Otherwise it will return an error.

func (*ResultSet) Next

func (r *ResultSet) Next() bool

Next prepares the next result value for reading. It returns true on success or false if there are no more results or an error occurs while preparing it. ResultSet.Err should be consulted to distinguish between the two.

When Next returns false, and there are no more results/result sets to be read, the ResultSet.Close is called implicitly, negating the need to call it explicitly.

func (*ResultSet) NextIterator

func (r *ResultSet) NextIterator() func(yield func() bool)

NextIterator returns a function that can be used to iterate over the multiple result sets in a ResultSet. This function is the analogue to ResultSet.NextResultSet for Go 1.23's. For queries that return multiple resultsets, you may call this function once for each result set.

!!NOTICE!! This function is considered experimental, and may change without notice.

func (*ResultSet) NextResultSet

func (r *ResultSet) NextResultSet() bool

NextResultSet prepares the next result set for reading. It returns false if there is no further result set or if there is an error advancing to it. ResultSet.Err should be consulted to distinguish between the two cases.

After calling NextResultSet, ResultSet.Next must be called to advance to the first result in the resultset before scanning.

func (*ResultSet) Rev

func (r *ResultSet) Rev() (string, error)

Rev returns the document revision, when known. Not all result sets (such as those from views) include revision IDs, so this will return an empty string in such cases.

func (*ResultSet) ScanDoc

func (r *ResultSet) ScanDoc(dest interface{}) error

ScanDoc works the same as ResultSet.ScanValue, but on the doc field of the result. It will return an error if the query does not include documents.

If the row returned an error, it will be returned rather than unmarshaling the doc, as error rows do not include docs.

func (*ResultSet) ScanKey

func (r *ResultSet) ScanKey(dest interface{}) error

ScanKey works the same as ResultSet.ScanValue, but on the key field of the result. For simple keys, which are just strings, ResultSet.Key may be easier to use.

Unlike ResultSet.ScanValue and ResultSet.ScanDoc, this may successfully scan the key, and also return an error, if the row itself represents an error.

func (*ResultSet) ScanValue

func (r *ResultSet) ScanValue(dest interface{}) error

ScanValue copies the data from the result value into dest, which must be a pointer. This acts as a wrapper around encoding/json.Unmarshal.

If the row returned an error, it will be returned rather than unmarshaling the value, as error rows do not include values.

Refer to the documentation for encoding/json.Unmarshal for unmarshaling details.

type RevDiff

RevDiff represents a rev diff for a single document, as returned by the DB.RevsDiff method.

type RevDiff struct {
    Missing           []string `json:"missing,omitempty"`
    PossibleAncestors []string `json:"possible_ancestors,omitempty"`
}

type Row

Row represents a single row in a result set, as returned by ResultSet.Iterator and ResultSet.NextIterator.

!!NOTICE!! This struct is considered experimental, and may change without notice.

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

func (*Row) ID

func (r *Row) ID() (string, error)

ID returns the document ID of the row, if present in the result.

func (*Row) Key

func (r *Row) Key() (json.RawMessage, error)

Key returns the raw, JSON-encoded key of the row, if present in the result.

func (*Row) Rev

func (r *Row) Rev() (string, error)

Rev returns the view key of the row, if present in the result.

func (*Row) ScanDoc

func (r *Row) ScanDoc(dest interface{}) error

ScanDoc works the same as Row.ScanValue, but on the doc field of the result. It will return an error if the query does not include documents.

If the row returned an error, it will be returned rather than unmarshaling the doc, as error rows do not include docs.

func (*Row) ScanKey

func (r *Row) ScanKey(dest interface{}) error

ScanKey works the same as Row.ScanValue, but on the key field of the result. For simple keys, which are just strings, Row.Key may be easier to use.

Unlike Row.ScanValue and Row.ScanDoc, this may successfully scan the key, and also return an error, if the row itself represents an error.

func (*Row) ScanValue

func (r *Row) ScanValue(dest interface{}) error

ScanValue copies the data from the result value into dest, which must be a pointer. This acts as a wrapper around encoding/json.Unmarshal.

Refer to the documentation for encoding/json.Unmarshal for unmarshaling details.

If the row returned an error, it will be returned rather than unmarshaling the doc, as error rows do not include values.

type Security

Security represents a database security document.

type Security struct {
    Admins  Members `json:"admins,omitempty"`
    Members Members `json:"members,omitempty"`

    // Database permissions for Cloudant users and/or API keys. This field is
    // only used or populated by IBM Cloudant. See the [Cloudant documentation]
    // for details.
    //
    // [Cloudant documentation]: https://cloud.ibm.com/apidocs/cloudant#getsecurity
    Cloudant map[string][]string `json:"cloudant,omitempty"`

    // Manage permissions using the `_users` database only. This field is only
    // used or populated by IBM Cloudant. See the [Cloudant documentation] for
    // details.
    //
    // [Cloudant documentation]: https://cloud.ibm.com/apidocs/cloudant#getsecurity
    CouchdbAuthOnly *bool `json:"couchdb_auth_only,omitempty"`
}

type ServerVersion

ServerVersion represents a server version response.

type ServerVersion struct {
    // Version is the version number reported by the server or backend.
    Version string
    // Vendor is the vendor string reported by the server or backend.
    Vendor string
    // Features is a list of enabled, optional features.  This was added in
    // CouchDB 2.1.0, and can be expected to be empty for older versions.
    Features []string
    // RawResponse is the raw response body returned by the server, useful if
    // you need additional backend-specific information.  Refer to the
    // [CouchDB documentation] for format details.
    //
    // [CouchDB documentation]: http://docs.couchdb.org/en/2.0.0/api/server/common.html#get
    RawResponse json.RawMessage
}

type Session

Session represents an authentication session.

type Session struct {
    // Name is the name of the authenticated user.
    Name string
    // Roles is a list of roles the user belongs to.
    Roles []string
    // AuthenticationMethod is the authentication method that was used for this
    // session.
    AuthenticationMethod string
    // AuthenticationDB is the user database against which authentication was
    // performed.
    AuthenticationDB string
    // AuthenticationHandlers is a list of authentication handlers configured on
    // the server.
    AuthenticationHandlers []string
    // RawResponse is the raw JSON response sent by the server, useful for
    // custom backends which may provide additional fields.
    RawResponse json.RawMessage
}

Subdirectories

Name Synopsis
..
cmd
kivik Package main provides the kivik CLI tool.
cmd Package cmd provides the CLI interface to CouchDB.
config Package config handles the CLI tool configuration.
errors Package errors defines the errors the kivik CLI tool may produce.
input Package input provides input configuration.
log Package log handles logging.
output Package output handles program output.
friendly Package friendly produces friendly-formatted output.
gotmpl Package gotmpl handles go template output.
json Package json produces JSON output.
raw Package raw produces raw output.
yaml Package yaml produces YAML output.
couchdb Package couchdb is a driver for connecting with a CouchDB server over HTTP.
chttp Package chttp provides a minimal HTTP driver backend for communicating with CouchDB servers.
test Package test manages the integration tests for the CouchDB driver.
driver Package driver defines interfaces to be implemented by database drivers as used by package kivik.
int
errors Package errors provides some internal error types and utilities.
mock Package mock provides minimal mocks for kivik driver interfaces.
kiviktest Package kiviktest provides integration tests for kivik.
client Package client provides integration tests for the kivik client.
db Package db provides integration tests for the kivik db.
kt Package kt provides common utilities for Kivik tests.
mockdb Package mockdb provides a full Kivik driver implementation, for mocking in tests.
gen Package main generates the bulk of the mockdb driver.
pouchdb Package pouchdb provides a [PouchDB] driver for [Kivik].
bindings Package bindings provides minimal GopherJS bindings around the PouchDB library.
poucherr Package poucherr exists only for the purpose of testing the PouchDB binding's handling of PouchDB-specific error messages.
test Package test provides PouchDB integration tests.
script Package main prints out the version constant, for use in automatically creating releases when the version is updated.
x Package x serves as home for experimental features and incomplete drivers.
collate Package collate provides (near) CouchDB-compatible collation functions.
fsdb Package fs provides an experimental filesystem-backed Kivik driver.
cdb Package cdb provides the core CouchDB types.
decode Package decode assists in document decoding.
filesystem Package filesystem provides an abstraction around a filesystem
test Package test configures the integration test suite.
kivikd Package kivikd provides a kivik daemon.
auth Package auth manages authorization and authentication for kivikd.
basic Package basic provides HTTP Basic Auth services.
cookie Package cookie provides standard CouchDB cookie auth as described at http://docs.couchdb.org/en/2.0.0/api/server/authn.html#cookie-authentication
authdb Package authdb provides a standard interface to an authentication user store to be used by AuthHandlers.
authgroup Package authgroup groups two or more authentication backends together, trying one, then falling through to the others.
confadmin Package confadmin provides an authentication service for admins configured in server configuration.
couchauth Package couchauth provides auth services to a remote CouchDB server.
usersdb Package usersdb provides auth facilities from a CouchDB _users database.
conf Package conf manages configuration for kivikd.
cookies Package cookies provides cookies utilities.
couchserver Package couchserver aims to provide a CouchDB-compatible HTTP server interface to a kivik.Client.
logger Package logger defines the logger used by kivikd.
test Package test configures the integration test suite for kivikd.
mango Package mango provides a Mango query language parser and evaluator.
memorydb Package memorydb provides a memory-backed Kivik driver, intended for testing.
test
proxydb Package proxydb allows using an arbitrary Kivik client as a Kivik driver.
server Package server provides a CouchDB server via HTTP.
auth Package auth provides authentication and authorization for the server.
config Package config manages server configuration.