Documentation ¶
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:
- CouchDB: https://github.com/go-kivik/couchdb
- PouchDB: https://github.com/go-kivik/pouchdb (requires GopherJS)
- KivikMock: https://github.com/go-kivik/kivikmock
The Filesystem and Memory drivers are also available, but in early stages of development, and so many features do not yet work:
- Filesystem: https://github.com/go-kivik/fsdb
- MemroyDB: https://github.com/go-kivik/memorydb
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.
Working with JSON ¶
couchDB stores JSON, so Kivik translates Go data structures to and from JSON as necessary. The conversion between Go data types and JSON, and vice versa, is handled automatically according to the rules and behavior described in the documentationf or the standard library's `encoding/json` package (https://golang.org/pkg/encoding/json).
One would be well-advised to become familiar with using `json` struct field tags (https://golang.org/pkg/encoding/json/#Marshal) when working with JSON documents.
Using contexts ¶
Most Kivik methods take `context.Context` as their first argument. This allows the cancellation of blocking operations in the case that the result is no longer needed. A typical use case for a web application would be to cancel a Kivik request if the remote HTTP client ahs disconnected, rednering the results of the query irrelevant.
To learn more about Go's contexts, read the `context` package documentation (https://golang.org/pkg/context/) and read the Go blog post "Go Concurrency Patterns: Context" (https://blog.golang.org/context) for example code.
If in doubt, you can pass `context.TODO()` as the context variable. Example:
row := db.Get(context.TODO(), "some_doc_id")
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 StatusCode() method, or with a type assertion to `interface { StatusCode() int }`. Example:
if statusErr, ok := err.(interface{ StatusCode() int }); ok { status = statusErr.StatusCode() }
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 (https://docs.couchdb.org/en/stable/api/server/authn.html?highlight=cookie%20auth#cookie-authentication).
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 (https://pkg.go.dev/github.com/go-kivik/couchdb/v4).
Example (Connecting) ¶
With a client handle in hand, you can create a database handle with the DB() method to interact with a specific database.
package main import ( "fmt" kivik "github.com/dannyzhou2015/kivik/v4" ) func main() { 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 Register(name string, driver driver.Driver)
- func ScanAllDocs(r ResultSet, dest interface{}) error
- func ScanAllValues(r ResultSet, dest interface{}) error
- func StatusCode(err error) int
- type Attachment
- type Attachments
- type AttachmentsIterator
- type BulkGetReference
- type BulkResults
- 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) LastSeq() string
- func (c *Changes) Next() bool
- func (c *Changes) Pending() int64
- func (c *Changes) ScanDoc(dest interface{}) error
- func (c *Changes) Seq() string
- type Client
- func (c *Client) AllDBs(ctx context.Context, options ...Options) ([]string, error)
- func (c *Client) Authenticate(ctx context.Context, a interface{}) error
- func (c *Client) Close(ctx context.Context) error
- func (c *Client) ClusterSetup(ctx context.Context, action interface{}) error
- func (c *Client) ClusterStatus(ctx context.Context, options ...Options) (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 ...Options) error
- func (c *Client) DB(dbName string, options ...Options) *DB
- func (c *Client) DBExists(ctx context.Context, dbName string, options ...Options) (bool, error)
- func (c *Client) DBUpdates(ctx context.Context, options ...Options) (*DBUpdates, error)
- 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 ...Options) error
- func (c *Client) Driver() string
- func (c *Client) GetReplications(ctx context.Context, options ...Options) ([]*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 ...Options) (*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) (*Version, error)
- type ClusterConfig
- type ClusterMembership
- type Config
- type ConfigSection
- type DB
- func (db *DB) AllDocs(ctx context.Context, options ...Options) ResultSet
- func (db *DB) BulkDocs(ctx context.Context, docs []interface{}, options ...Options) (*BulkResults, error)
- func (db *DB) BulkGet(ctx context.Context, docs []BulkGetReference, options ...Options) ResultSet
- func (db *DB) Changes(ctx context.Context, options ...Options) (*Changes, error)
- func (db *DB) Client() *Client
- func (db *DB) Close(ctx context.Context) 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 ...Options) (targetRev string, err error)
- func (db *DB) CreateDoc(ctx context.Context, doc interface{}, options ...Options) (docID, rev string, err error)
- func (db *DB) CreateIndex(ctx context.Context, ddoc, name string, index interface{}, options ...Options) error
- func (db *DB) Delete(ctx context.Context, docID, rev string, options ...Options) (newRev string, err error)
- func (db *DB) DeleteAttachment(ctx context.Context, docID, rev, filename string, options ...Options) (newRev string, err error)
- func (db *DB) DeleteIndex(ctx context.Context, ddoc, name string, options ...Options) error
- func (db *DB) DesignDocs(ctx context.Context, options ...Options) ResultSet
- func (db *DB) Err() error
- func (db *DB) Explain(ctx context.Context, query interface{}, options ...Options) (*QueryPlan, error)
- func (db *DB) Find(ctx context.Context, query interface{}, options ...Options) ResultSet
- func (db *DB) Flush(ctx context.Context) error
- func (db *DB) Get(ctx context.Context, docID string, options ...Options) ResultSet
- func (db *DB) GetAttachment(ctx context.Context, docID, filename string, options ...Options) (*Attachment, error)
- func (db *DB) GetAttachmentMeta(ctx context.Context, docID, filename string, options ...Options) (*Attachment, error)
- func (db *DB) GetIndexes(ctx context.Context, options ...Options) ([]Index, error)
- func (db *DB) GetRev(ctx context.Context, docID string, options ...Options) (rev string, err error)
- func (db *DB) LocalDocs(ctx context.Context, options ...Options) ResultSet
- func (db *DB) Name() string
- 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 ...Options) (rev string, err error)
- func (db *DB) PutAttachment(ctx context.Context, docID string, att *Attachment, options ...Options) (newRev string, err error)
- func (db *DB) Query(ctx context.Context, ddoc, view string, options ...Options) 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 DBUpdates
- type Diffs
- type Error
- type Index
- type Members
- type Options
- 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 ReplicationInfo
- type ReplicationState
- type ResultMetadata
- type ResultSet
- type RevDiff
- type Security
- type Session
- type Version
Examples ¶
Constants ¶
const ( // KivikVersion is the version of the Kivik library. KivikVersion = "4.0.0-prerelease" // KivikVendor is the vendor string reported by this library. KivikVendor = "Kivik" )
const EndKeySuffix = string(rune(0xfff0))
EndKeySuffix is a high Unicode character (0xfff0) useful for appending to an endkey argument, when doing a ranged search, as described here: http://couchdb.readthedocs.io/en/latest/ddocs/views/collation.html#string-ranges
Example, to return all results with keys beginning with "foo":
rows, err := db.Query(context.TODO(), "ddoc", "view", map[string]interface{}{ "startkey": "foo", "endkey": "foo" + kivik.EndKeySuffix, })
const SessionCookieName = "AuthSession"
SessionCookieName is the name of the CouchDB session cookie.
const UserPrefix = "org.couchdb.user:"
UserPrefix is the mandatory CouchDB user prefix. See http://docs.couchdb.org/en/2.0.0/intro/security.html#org-couchdb-user
Variables ¶
This section is empty.
Functions ¶
func Register ¶
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 ¶
ScanAllDocs loops through remaining documents in the resultset, and scans them into dest. Dest is expected to be a pointer to a slice or an array, any other type will return 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 ¶
ScanAllValues works like ScanAllDocs, but scans the values rather than docs.
func StatusCode ¶
StatusCode 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, StatusCode 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.StatusCode(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 { StatusCode() (httpStatusCode int) }
Example ¶
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 kivik.StatusCode(row.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()) }
Output:
Types ¶
type Attachment ¶
type Attachment struct { // Filename is the name of the attachment. Filename string `json:"-"` // ContentType is the MIME type of the attachment contents. 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 the // GetAttachmentMeta function, 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 Stub is true, values >= 0 // indicate that the given number of bytes may be read from 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 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"` }
Attachment represents a file attachment on a CouchDB document.
func (*Attachment) MarshalJSON ¶
func (a *Attachment) MarshalJSON() ([]byte, error)
MarshalJSON satisfies the json.Marshaler interface.
func (*Attachment) UnmarshalJSON ¶
func (a *Attachment) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for an Attachment.
type Attachments ¶
type Attachments map[string]*Attachment
Attachments is a collection of one or more file attachments.
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 existed.
func (*Attachments) UnmarshalJSON ¶
func (a *Attachments) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for a collection of Attachments.
type AttachmentsIterator ¶
type AttachmentsIterator struct {
// contains filtered or unexported fields
}
AttachmentsIterator is an experimental way to read streamed attachments from a multi-part Get request.
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.
type BulkGetReference ¶
type BulkGetReference struct { ID string `json:"id"` Rev string `json:"rev,omitempty"` AttsSince string `json:"atts_since,omitempty"` }
BulkGetReference is a reference to a document given in a BulkGet query.
type BulkResults ¶
type BulkResults struct {
// contains filtered or unexported fields
}
BulkResults is an iterator over the results of a BulkDocs query.
func (*BulkResults) Close ¶
func (r *BulkResults) Close() error
Close closes the feed. Any unread updates will still be accessible via Next().
func (*BulkResults) Err ¶
func (r *BulkResults) Err() error
Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.
func (*BulkResults) ID ¶
func (r *BulkResults) ID() string
ID returns the document ID name for the current result.
func (*BulkResults) Next ¶
func (r *BulkResults) Next() bool
Next returns the next BulkResult from the feed. If an error occurs, it will be returned and the feed closed. io.EOF will be returned when there are no more results.
func (*BulkResults) Rev ¶
func (r *BulkResults) Rev() string
Rev returns the revision of the current curResult.
func (*BulkResults) UpdateErr ¶
func (r *BulkResults) UpdateErr() error
UpdateErr returns the error associated with the current result, or nil if none. Do not confuse this with Err, which returns an error for the iterator itself.
type Changes ¶
type Changes struct {
// contains filtered or unexported fields
}
Changes is an iterator over the database changes feed.
func (*Changes) Close ¶
Close closes the Changes feed, preventing further enumeration, and freeing any resources (such as the http request body) of the underlying query. If Next is called and there are no further results, Changes is closed automatically and it will suffice to check the result of Err. Close is idempotent and does not affect the result of Err.
func (*Changes) ETag ¶
ETag returns the unquoted ETag header, if any. Unlike LastSeq and Pending, because this value is returned in the response header (for standard CouchDB operation) anyway, it can be read immediately, before iteration even begins.
func (*Changes) Err ¶
Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.
func (*Changes) LastSeq ¶
LastSeq returns the last update sequence id present in the change set, if returned by the server. This value is only guaranteed to be set after all changes have been enumerated through by Next, thus should only be read after processing all changes in a change set. Calling Close before enumerating will render this value unreliable.
func (*Changes) Next ¶
Next prepares the next result value for reading. It returns true on success or false if there are no more results, due to an error or the changes feed having been closed. Err should be consulted to determine any error.
func (*Changes) Pending ¶
Pending returns the count of remaining items in the change feed. This value is only guaranteed to be set after all changes have been enumerated through by Next, thus should only be read after processing all changes in a change set. Calling Close before enumerating will render this value unreliable.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a client connection handle to a CouchDB-like server.
func New ¶
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.
package main import ( "fmt" kivik "github.com/dannyzhou2015/kivik/v4" ) func main() { client, err := kivik.New("couch", "http://example.com:5984/") if err != nil { panic(err) } fmt.Println("Connected to", client.DSN()) }
Output: Connected to http://example.com:5984/
func (*Client) Authenticate ¶
Authenticate authenticates the client with the passed authenticator, which is driver-specific. If the driver does not understand the authenticator, an error will be returned.
func (*Client) ClusterSetup ¶
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.
See http://docs.couchdb.org/en/stable/api/server/common.html#post--_cluster_setup
func (*Client) ClusterStatus ¶
ClusterStatus returns the current cluster status.
See http://docs.couchdb.org/en/stable/api/server/common.html#cluster-setup
func (*Client) Config ¶
Config returns the entire server config, for the specified node.
See http://docs.couchdb.org/en/stable/api/server/configuration.html#get--_node-node-name-_config
func (*Client) ConfigSection ¶
ConfigSection returns the requested section of the server config for the specified node.
See http://docs.couchdb.org/en/stable/api/server/configuration.html#node-node-name-config-section
func (*Client) ConfigValue ¶
ConfigValue returns a single config value for the specified node.
func (*Client) DB ¶
DB returns a handle to the requested database. Any options parameters passed are merged, with later values taking precidence. If any errors occur at this stage, they are deferred, or may be checked directly with Err()
func (*Client) DeleteConfigKey ¶
DeleteConfigKey deletes the configuration key and associated value from the specified node. It returns the old value.
func (*Client) GetReplications ¶
GetReplications returns a list of defined replications in the _replicator database. Options are in the same format as to 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. See https://docs.couchdb.org/en/latest/api/server/common.html#get--_membership
func (*Client) Ping ¶
Ping returns true if the database is online and available for requests, for instance by querying the /_up endpoint. If the underlying driver supports the Pinger interface, it will be used. Otherwise, a fallback is made to calling Version.
func (*Client) Replicate ¶
func (c *Client) Replicate(ctx context.Context, targetDSN, sourceDSN string, options ...Options) (*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.
type ClusterConfig ¶
type ClusterConfig struct { Replicas int `json:"n"` Shards int `json:"q"` ReadQuorum int `json:"r"` WriteQuorum int `json:"w"` }
ClusterConfig contains the cluster configuration for the database.
type ClusterMembership ¶
type ClusterMembership struct { AllNodes []string `json:"all_nodes"` ClusterNodes []string `json:"cluster_nodes"` }
ClusterMembership contains the list of known nodes, and cluster nodes, as returned by the /_membership endpoint. See https://docs.couchdb.org/en/latest/api/server/common.html#get--_membership
type Config ¶
type Config map[string]ConfigSection
Config represents all the config sections.
Note that the Config struct, and all of the config-related methods are considered experimental, and may change in the future.
type ConfigSection ¶
ConfigSection represents all key/value pairs for a section of configuration.
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB is a handle to a specific database.
Example (Delete) ¶
As with updating a document, deletion depends on the proper _rev parameter.
package main import ( "context" "fmt" kivik "github.com/dannyzhou2015/kivik/v4" ) var db = &kivik.DB{} func main() { newRev, err := db.Delete(context.TODO(), "cow", "2-9c65296036141e575d32ba9c034dd3ee") if err != nil { panic(err) } fmt.Printf("The tombstone document has revision %s\n", newRev) }
Output:
Example (Fetch) ¶
When fetching a document, the document will be unmarshaled from JSON into your structure by the row.ScanDoc method.
package main import ( "context" "fmt" kivik "github.com/dannyzhou2015/kivik/v4" ) var db = &kivik.DB{} func main() { 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) }
Output:
Example (MapReduce) ¶
package main import ( "context" kivik "github.com/dannyzhou2015/kivik/v4" ) var db = &kivik.DB{} func main() { opts := kivik.Options{ "group": true, } rows := db.Query(context.TODO(), "_design/foo", "_view/bar", opts) if err := rows.Err(); err != nil { panic(err) } for rows.Next() { /* ... */ } }
Output:
Example (Query) ¶
package main import ( "context" kivik "github.com/dannyzhou2015/kivik/v4" ) var db = &kivik.DB{} func main() { rows := db.Query(context.TODO(), "_design/foo", "_view/bar", kivik.Options{ "startkey": `"foo"`, // Quotes are necessary so the "endkey": `"foo` + kivik.EndKeySuffix + `"`, // key is a valid JSON object }) if err := rows.Err(); err != nil { panic(err) } for rows.Next() { var doc interface{} if err := rows.ScanDoc(&doc); err != nil { panic(err) } /* do something with doc */ } if rows.Err() != nil { panic(rows.Err()) } }
Output:
Example (Store) ¶
Storing a document is done with Put or Create, which correspond to `PUT /{db}/{doc}` and `POST /{db}` respectively. In most cases, you should use Put.
package main import ( "context" kivik "github.com/dannyzhou2015/kivik/v4" ) var db = &kivik.DB{} func main() { type Animal struct { ID string `json:"_id"` Rev string `json:"_rev,omitempty"` Feet int `json:"feet"` Greeting string `json:"greeting"` } cow := Animal{ID: "cow", Feet: 4, Greeting: "moo"} rev, err := db.Put(context.TODO(), "cow", cow) if err != nil { panic(err) } cow.Rev = rev }
Output:
Example (Update) ¶
Updating a document is the same as storing one, except that the `_rev` parameter must match that stored on the server.
package main import ( "context" kivik "github.com/dannyzhou2015/kivik/v4" ) var db = &kivik.DB{} var cow struct { Rev string Greeting string } func main() { 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 }
Output:
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).
package main import ( "context" kivik "github.com/dannyzhou2015/kivik/v4" ) var db = &kivik.DB{} func main() { _, 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) } }
Output:
func (*DB) BulkDocs ¶
func (db *DB) BulkDocs(ctx context.Context, docs []interface{}, options ...Options) (*BulkResults, 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 http://docs.couchdb.org/en/2.0.0/api/database/bulk-api.html#db-bulk-docs
As with Put, each individual document may be a JSON-marshable object, or a raw JSON string in a json.RawMessage, or io.Reader.
func (*DB) BulkGet ¶
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 http://docs.couchdb.org/en/stable/api/database/bulk-api.html#db-bulk-get
func (*DB) Changes ¶
Changes returns an iterator over the real-time changes feed. The feed remains open until explicitly closed, or an error is encountered. See http://couchdb.readthedocs.io/en/latest/api/database/changes.html#get--db-_changes
func (*DB) Close ¶
Close cleans up any resources used by the DB. The default CouchDB driver does not use this, the default PouchDB driver does.
func (*DB) Compact ¶
Compact begins compaction of the database. Check the CompactRunning field returned by Info() to see if the compaction has completed. See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-compact
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 ¶
CompactView compats the view indexes associated with the specified design document. See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-compact-design-doc
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 ...Options) (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 http://docs.couchdb.org/en/2.0.0/api/document/common.html#copy--db-docid
func (*DB) CreateDoc ¶
func (db *DB) CreateDoc(ctx context.Context, doc interface{}, options ...Options) (docID, rev string, err error)
CreateDoc creates a new doc with an auto-generated unique ID. The generated docID and new rev are returned.
func (*DB) CreateIndex ¶
func (db *DB) CreateIndex(ctx context.Context, ddoc, name string, index interface{}, options ...Options) 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 a valid index object, as described here: http://docs.couchdb.org/en/stable/api/database/find.html#db-index
func (*DB) Delete ¶
func (db *DB) Delete(ctx context.Context, docID, rev string, options ...Options) (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.
func (*DB) DeleteAttachment ¶
func (db *DB) DeleteAttachment(ctx context.Context, docID, rev, filename string, options ...Options) (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 ¶
DeleteIndex deletes the requested index.
func (*DB) DesignDocs ¶
DesignDocs returns a list of all documents in the database.
func (*DB) Err ¶
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 ever necessary if you need to directly check the error status, and intend to do nothing else with the DB object.
func (*DB) Explain ¶
func (db *DB) Explain(ctx context.Context, query interface{}, options ...Options) (*QueryPlan, error)
Explain returns the query plan for a given query. Explain takes the same arguments as Find.
func (*DB) Find ¶
Find executes a query using the new /_find interface. The query must be JSON-marshalable to a valid query. See https://docs.couchdb.org/en/stable/api/database/find.html
func (*DB) Flush ¶
Flush requests a flush of disk cache to disk or other permanent storage.
See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-ensure-full-commit
func (*DB) Get ¶
Get fetches the requested document. Any errors are deferred until the row.ScanDoc call.
func (*DB) GetAttachment ¶
func (db *DB) GetAttachment(ctx context.Context, docID, filename string, options ...Options) (*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 ...Options) (*Attachment, error)
GetAttachmentMeta returns meta data about an attachment. The attachment content returned will be empty.
func (*DB) GetIndexes ¶
GetIndexes returns the indexes defined on the current database.
func (*DB) GetRev ¶
GetRev returns the active rev of the specified document. GetRev accepts the same options as the Get method.
func (*DB) PartitionStats ¶
PartitionStats returns statistics about the named partition.
See https://docs.couchdb.org/en/stable/api/partitioned-dbs.html#db-partition-partition
func (*DB) Purge ¶
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 ...Options) (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:
- An object to be marshaled to JSON. The resulting JSON structure must conform to CouchDB standards.
- A json.RawMessage value containing a valid JSON document
- An io.Reader, from which a valid JSON document may be read.
func (*DB) PutAttachment ¶
func (db *DB) PutAttachment(ctx context.Context, docID string, att *Attachment, options ...Options) (newRev string, err error)
PutAttachment uploads the supplied content as an attachment to the specified document.
func (*DB) Query ¶
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.
func (*DB) RevsDiff ¶
RevsDiff 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 ID() to return the current document ID, and ScanValue to access the full JSON value, which should be of the JSON format:
{ "missing": ["rev1",...], "possible_ancestors": ["revA",...] }
See http://docs.couchdb.org/en/stable/api/database/misc.html#db-revs-diff
func (*DB) Security ¶
Security returns the database's security document. See http://couchdb.readthedocs.io/en/latest/api/database/security.html#get--db-_security
func (*DB) SetSecurity ¶
SetSecurity sets the database's security document. See http://couchdb.readthedocs.io/en/latest/api/database/security.html#put--db-_security
func (*DB) Stats ¶
Stats returns database statistics.
See https://docs.couchdb.org/en/stable/api/database/common.html#get--db
func (*DB) ViewCleanup ¶
ViewCleanup removes view index files that are no longer required as a result of changed views within design documents. See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-view-cleanup
type DBStats ¶
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 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 // http://docs.couchdb.org/en/2.1.1/api/database/common.html#get--db RawResponse jsoniter.RawMessage `json:"-"` }
DBStats contains database statistics..
type DBUpdates ¶
type DBUpdates struct {
// contains filtered or unexported fields
}
DBUpdates provides access to database updates.
func (*DBUpdates) Close ¶
Close closes the feed. Any unread updates will still be accessible via Next().
func (*DBUpdates) Err ¶
Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.
func (*DBUpdates) Next ¶
Next returns the next DBUpdate from the feed. This function will block until an event is received. If an error occurs, it will be returned and the feed closed. If the feed was closed normally, io.EOF will be returned when there are no more events in the buffer.
type Diffs ¶
Diffs is a collection of RevDiffs as returned by RevsDiff. The map key is the document ID.
type Error ¶
type Error struct { // HTTPStatus is the HTTP status code associated with this error. Normally // this is the actual HTTP status returned by the server, but in some cases // it may be generated by Kivik directly. Check the FromServer value if // the distinction matters to you. HTTPStatus int // Message is the error message. Message string // Err is the originating error, if any. Err error }
Error represents an error returned by Kivik.
This type definition is not guaranteed to remain stable, or even exported. When examining errors programatically, you should rely instead on the StatusCode() function in this package, rather than on directly observing the fields of this type.
func (*Error) Cause ¶
Cause satisfies the github.com/pkg/errors.causer interface by returning e.Err.
func (*Error) StatusCode ¶
StatusCode returns the HTTP status code associated with the error, or 500 (internal server error), if none.
type Index ¶
type Index struct { DesignDoc string `json:"ddoc,omitempty"` Name string `json:"name"` Type string `json:"type"` Definition interface{} `json:"def"` }
Index is a MonboDB-style index definition.
type Members ¶
type Members struct { Names []string `json:"names,omitempty"` Roles []string `json:"roles,omitempty"` }
Members represents the members of a database security document.
type Options ¶
type Options map[string]interface{}
Options is a collection of options. The keys and values are backend specific.
type PartitionStats ¶
type PartitionStats struct { DBName string DocCount int64 DeletedDocCount int64 Partition string ActiveSize int64 ExternalSize int64 RawResponse jsoniter.RawMessage }
PartitionStats contains partition statistics.
type PurgeResult ¶
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"` }
PurgeResult is the result of a purge request.
type QueryPlan ¶
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"` }
QueryPlan is the query execution plan for a query, as returned by the Explain function.
type Replication ¶
Replication represents a CouchDB replication process.
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
type ReplicationInfo ¶
type ReplicationInfo struct { DocWriteFailures int64 DocsRead int64 DocsWritten int64 Progress float64 }
ReplicationInfo represents a snapshot of the status of a replication.
type ReplicationState ¶
type ReplicationState string
ReplicationState represents a replication's state
const ( ReplicationNotStarted ReplicationState = "" ReplicationStarted ReplicationState = "triggered" ReplicationError ReplicationState = "error" ReplicationComplete ReplicationState = "completed" )
The possible values for the _replication_state field in _replicator documents plus a blank value for unstarted replications.
const ( ReplicationInitializing ReplicationState = "initializing" ReplicationRunning ReplicationState = "running" ReplicationPending ReplicationState = "pending" ReplicationCrashing ReplicationState = "crashing" ReplicationFailed ReplicationState = "failed" )
The additional possible values for the state field in the _scheduler docs.
type ResultMetadata ¶
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 official CouchDB documentation for // detailed usage instructions: // http://docs.couchdb.org/en/2.1.1/api/database/find.html#pagination Bookmark string }
ResultMetadata contains metadata about certain queries.
type ResultSet ¶
type ResultSet interface { // 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. Err should be consulted to distinguish between the two. Next() bool // Err returns the error, if any, that was encountered during iteration. // Err may be called after an explicit or implicit Close. Err() error // Close closes the Rows, preventing further enumeration, and freeing any // resources (such as the http request body) of the underlying query. If // Next is called and there are no further results, Rows is closed // automatically and it will suffice to check the result of Err. Close is // idempotent and does not affect the result of Err. Close() error // Finish will consume any remaining results in the result set, then close // the iterator, and return any available query metadata. Use this in // place of Close() if the result metadata is needed, otherwise Close() // may be more efficient, as Close() does not read any more data from the // network. Finish() (ResultMetadata, error) // ScanValue copies the data from the result value into the value pointed // at by dest. Think of this as a json.Unmarshal into dest. // // If the dest argument has type *[]byte, Scan stores a copy of the input // data. The copy is owned by the caller and can be modified and held // indefinitely. // // The copy can be avoided by using an argument of type *json.RawMessage // instead. After a ScanValue into a json.RawMessage, the slice is only // valid until the next call to Next or Close. // // For all other types, refer to the documentation for json.Unmarshal for // type conversion rules. ScanValue(dest interface{}) error // ScanDoc works the same as ScanValue, but on the doc field of the result. // It will return an error if the query does not include documents. ScanDoc(dest interface{}) error // ScanKey works the same as ScanValue, but on the key field of the result. // For simple keys, which are just strings, the Key() method may be easier // to use. ScanKey(dest interface{}) error // ID returns the ID of the most recent result. ID() string // Rev returns the document revision, when known. Not all resultsets (such // as those from views) include revision IDs, so this will be blank in such // cases. Rev() string // Key returns the Key of the most recent result as a raw JSON string. For // compound keys, the ScanKey() method may be more convenient. Key() string // QueryIndex returns the 0-based index of the query. For standard queries, // this is always 0. When multiple queries are passed to the view, this will // represent the query currently being iterated QueryIndex() int // EOQ returns true if the iterator has reached the end of a query in a // multi-query query. When EOQ is true, the row data will not have been // updated. It is common to simply `continue` in case of EOQ, unless you // care about the per-query metadata, such as offset, total rows, etc. EOQ() bool // Attachments returns an attachments iterator. At present, it is only set // by the Get() method when doing a multi-part get from CouchDB (which is // the default where supported). This may be extended to other cases in // the future. Attachments() *AttachmentsIterator }
ResultSet is an iterator over a multi-value query result set.
Call 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.
Calling ScanDoc, ScanKey, ScanValue, ID, or Key before calling Next will operate on the first item in the resultset, then close the iterator immediately. This is for convenience in cases where only a single item is expected, so the extra effort of iterating is otherwise wasted.
type RevDiff ¶
type RevDiff struct { Missing []string `json:"missing,omitempty"` PossibleAncestors []string `json:"possible_ancestors,omitempty"` }
RevDiff represents a rev diff for a single document, as returned by the RevsDiff method.
type 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 jsoniter.RawMessage }
Session represents an authentication session.
type Version ¶
type Version 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. // // For the format of this document, see // http://docs.couchdb.org/en/2.0.0/api/server/common.html#get RawResponse jsoniter.RawMessage }
Version represents a server version response.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package driver defines interfaces to be implemented by database drivers as used by package kivik.
|
Package driver defines interfaces to be implemented by database drivers as used by package kivik. |
Package errors provides convenience functions for Kivik drivers to report meaningful errors.
|
Package errors provides convenience functions for Kivik drivers to report meaningful errors. |
internal
|
|
mock
Package mock provides minimal mocks for kivik driver interfaces.
|
Package mock provides minimal mocks for kivik driver interfaces. |
registry
Package registry handles driver registrations.
|
Package registry handles driver registrations. |