couchdb

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2020 License: MIT Imports: 15 Imported by: 10

README

What's this?

go-couchdb is yet another CouchDB client written in Go. It was written because all the other ones didn't provide functionality that I need.

The API is not fully baked at this time and may change.

This project contains three Go packages:

package couchdb GoDoc

import "github.com/fjl/go-couchdb"

This wraps the CouchDB HTTP API.

package couchapp GoDoc

import "github.com/fjl/go-couchdb/couchapp"

This provides functionality similar to the original couchapp tool, namely compiling a filesystem directory into a JSON object and storing the object as a CouchDB design document.

package couchdaemon GoDoc

import "github.com/fjl/go-couchdb/couchdaemon"

This package contains some functions that help you write Go programs that run as a daemon started by CouchDB, e.g. fetching values from the CouchDB config.

Tests

You can run the unit tests with go test.

Build Status

Documentation

Overview

Package couchdb implements wrappers for the CouchDB HTTP API.

Unless otherwise noted, all functions in this package can be called from more than one goroutine at the same time.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Conflict

func Conflict(err error) bool

Conflict checks whether the given error is a DatabaseError with StatusCode == 409.

func ErrorStatus

func ErrorStatus(err error, statusCode int) bool

ErrorStatus checks whether the given error is a DatabaseError with a matching statusCode.

func NotFound

func NotFound(err error) bool

NotFound checks whether the given errors is a DatabaseError with StatusCode == 404. This is useful for conditional creation of databases and documents.

func Unauthorized

func Unauthorized(err error) bool

Unauthorized checks whether the given error is a DatabaseError with StatusCode == 401.

Types

type Attachment

type Attachment struct {
	Name string    // Filename
	Type string    // MIME type of the Body
	MD5  []byte    // MD5 checksum of the Body
	Body io.Reader // The body itself
}

Attachment represents document attachments.

type Auth

type Auth interface {
	// AddAuth should add authentication information (e.g. headers)
	// to the given HTTP request.
	AddAuth(*http.Request)
}

Auth is implemented by HTTP authentication mechanisms.

func BasicAuth

func BasicAuth(username, password string) Auth

BasicAuth returns an Auth that performs HTTP Basic Authentication.

func ProxyAuth

func ProxyAuth(username string, roles []string, secret string) Auth

ProxyAuth returns an Auth that performs CouchDB proxy authentication. Please consult the CouchDB documentation for more information on proxy authentication:

http://docs.couchdb.org/en/latest/api/server/authn.html?highlight=proxy#proxy-authentication

type ChangesFeed

type ChangesFeed struct {
	// DB is the database. Since all events in a _changes feed
	// belong to the same database, this field is always equivalent to the
	// database from the DB.Changes call that created the feed object
	DB *DB `json:"-"`

	// ID is the document ID of the current event.
	ID string `json:"id"`

	// Deleted is true when the event represents a deleted document.
	Deleted bool `json:"deleted"`

	// Seq is the database update sequence number of the current event.
	// This is usually a string, but may also be a number for couchdb 0.x servers.
	//
	// For poll-style feeds (feed modes "normal", "longpoll"), this is set to the
	// last_seq value sent by CouchDB after all feed rows have been read.
	Seq interface{} `json:"seq"`

	// Pending is the count of remaining items in the feed. This is set for poll-style
	// feeds (feed modes "normal", "longpoll") after the last element has been
	// processed.
	Pending int64 `json:"pending"`

	// Changes is the list of the document's leaf revisions.
	Changes []struct {
		Rev string `json:"rev"`
	} `json:"changes"`

	// The document. This is populated only if the feed option
	// "include_docs" is true.
	Doc json.RawMessage `json:"doc"`
	// contains filtered or unexported fields
}

ChangesFeed is an iterator for the _changes feed of a database. On each call to the Next method, the event fields are updated for the current event. Next is designed to be used in a for loop:

    feed, err := client.Changes("db", nil)
    ...
    for feed.Next() {
	       fmt.Printf("changed: %s", feed.ID)
    }
    err = feed.Err()
    ...

func (*ChangesFeed) ChangesRevs

func (f *ChangesFeed) ChangesRevs() []string

ChangesRevs returns the rev list of the current result row.

func (*ChangesFeed) Close

func (f *ChangesFeed) Close() error

Close terminates the connection of the feed. If Next returns false, the feed has already been closed.

func (*ChangesFeed) Err

func (f *ChangesFeed) Err() error

Err returns the last error that occurred during iteration.

func (*ChangesFeed) Next

func (f *ChangesFeed) Next() bool

Next decodes the next event. It returns false when the feeds end has been reached or an error has occurred.

type Client

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

Client represents a remote CouchDB server.

func NewClient

func NewClient(rawurl string, rt http.RoundTripper) (*Client, error)

NewClient creates a new client object.

If rawurl contains credentials, the client will authenticate using HTTP Basic Authentication. If rawurl has a query string, it is ignored.

The second argument can be nil to use http.Transport, which should be good enough in most cases.

func (*Client) AllDBs

func (c *Client) AllDBs() (names []string, err error)

AllDBs returns the names of all existing databases.

func (*Client) CreateDB

func (c *Client) CreateDB(name string) (*DB, error)

CreateDB creates a new database. The request will fail with status "412 Precondition Failed" if the database already exists. A valid DB object is returned in all cases, even if the request fails.

func (*Client) DB

func (c *Client) DB(name string) *DB

DB creates a database object. The database inherits the authentication and http.RoundTripper of the client. The database's actual existence is not verified.

func (*Client) DBUpdates

func (c *Client) DBUpdates(options Options) (*DBUpdatesFeed, error)

DBUpdates opens the _db_updates feed. For the possible options, please see the CouchDB documentation. Pleas note that the "feed" option is currently always set to "continuous".

http://docs.couchdb.org/en/latest/api/server/common.html#db-updates

func (*Client) DeleteDB

func (c *Client) DeleteDB(name string) error

DeleteDB deletes an existing database.

func (*Client) EnsureDB

func (c *Client) EnsureDB(name string) (*DB, error)

EnsureDB ensures that a database with the given name exists.

func (*Client) Ping

func (c *Client) Ping() error

Ping can be used to check whether a server is alive. It sends an HTTP HEAD request to the server's URL.

func (*Client) SetAuth

func (c *Client) SetAuth(a Auth)

SetAuth sets the authentication mechanism used by the client. Use SetAuth(nil) to unset any mechanism that might be in use. In order to verify the credentials against the server, issue any request after the call the SetAuth.

func (*Client) URL

func (c *Client) URL() string

URL returns the URL prefix of the server. The url will not contain a trailing '/'.

type DB

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

DB represents a remote CouchDB database.

func (*DB) AllDocs

func (db *DB) AllDocs(result interface{}, opts Options) error

AllDocs invokes the _all_docs view of a database.

The output of the query is unmarshalled into the given result. The format of the result depends on the options. Please refer to the CouchDB HTTP API documentation for all the possible options that can be set.

http://docs.couchdb.org/en/latest/api/database/bulk-api.html#db-all-docs

func (*DB) Attachment

func (db *DB) Attachment(docid, name, rev string) (*Attachment, error)

Attachment retrieves an attachment. The rev argument can be left empty to retrieve the latest revision. The caller is responsible for closing the attachment's Body if the returned error is nil.

func (*DB) AttachmentMeta

func (db *DB) AttachmentMeta(docid, name, rev string) (*Attachment, error)

AttachmentMeta requests attachment metadata. The rev argument can be left empty to retrieve the latest revision. The returned attachment's Body is always nil.

func (*DB) Changes

func (db *DB) Changes(options Options) (*ChangesFeed, error)

Changes opens the _changes feed of a database. This feed receives an event whenever a document is created, updated or deleted.

The implementation supports both poll-style and continuous feeds. The default feed mode is "normal", which retrieves changes up to some point and then closes the feed. If you want a never-ending feed, set the "feed" option to "continuous":

feed, err := client.Changes("db", couchdb.Options{"feed": "continuous"})

There are many other options that allow you to customize what the feed returns. For information on all of them, see the official CouchDB documentation:

http://docs.couchdb.org/en/latest/api/database/changes.html#db-changes

func (*DB) Delete

func (db *DB) Delete(id, rev string) (newrev string, err error)

Delete marks a document revision as deleted.

func (*DB) DeleteAttachment

func (db *DB) DeleteAttachment(docid, name, rev string) (newrev string, err error)

DeleteAttachment removes an attachment.

func (*DB) Get

func (db *DB) Get(id string, doc interface{}, opts Options) error

Get retrieves a document from the given database. The document is unmarshalled into the given object. Some fields (like _conflicts) will only be returned if the options require it. Please refer to the CouchDB HTTP API documentation for more information.

http://docs.couchdb.org/en/latest/api/document/common.html?highlight=doc#get--db-docid

func (*DB) Name

func (db *DB) Name() string

Name returns the name of a database.

func (*DB) Put

func (db *DB) Put(id string, doc interface{}, rev string) (newrev string, err error)

Put stores a document into the given database.

func (*DB) PutAttachment

func (db *DB) PutAttachment(docid string, att *Attachment, rev string) (newrev string, err error)

PutAttachment creates or updates an attachment. To create an attachment on a non-existing document, pass an empty rev.

func (*DB) PutSecurity

func (db *DB) PutSecurity(secobj *Security) error

PutSecurity sets the database security object.

func (*DB) Rev

func (db *DB) Rev(id string) (string, error)

Rev fetches the current revision of a document. It is faster than an equivalent Get request because no body has to be parsed.

func (*DB) Security

func (db *DB) Security() (*Security, error)

Security retrieves the security object of a database.

func (*DB) View

func (db *DB) View(ddoc, view string, result interface{}, opts Options) error

View invokes a view. The ddoc parameter must be the full name of the design document containing the view definition, including the _design/ prefix.

The output of the query is unmarshalled into the given result. The format of the result depends on the options. Please refer to the CouchDB HTTP API documentation for all the possible options that can be set.

http://docs.couchdb.org/en/latest/api/ddoc/views.html

type DBUpdatesFeed

type DBUpdatesFeed struct {
	Event string      `json:"type"`    // "created" | "updated" | "deleted"
	DB    string      `json:"db_name"` // Event database name
	Seq   interface{} `json:"seq"`     // DB update sequence of the event.
	OK    bool        `json:"ok"`      // Event operation status (deprecated)
	// contains filtered or unexported fields
}

DBUpdatesFeed is an iterator for the _db_updates feed. This feed receives an event whenever any database is created, updated or deleted. On each call to the Next method, the event fields are updated for the current event.

    feed, err := client.DbUpdates(nil)
    ...
    for feed.Next() {
	       fmt.Printf("changed: %s %s", feed.Event, feed.Db)
    }
    err = feed.Err()
    ...

func (*DBUpdatesFeed) Close

func (f *DBUpdatesFeed) Close() error

Close terminates the connection of a feed.

func (*DBUpdatesFeed) Err

func (f *DBUpdatesFeed) Err() error

Err returns the last error that occurred during iteration.

func (*DBUpdatesFeed) Next

func (f *DBUpdatesFeed) Next() bool

Next decodes the next event in a _db_updates feed. It returns false when the feeds end has been reached or an error has occurred.

type Error

type Error struct {
	Method     string // HTTP method of the request
	URL        string // HTTP URL of the request
	StatusCode int    // HTTP status code of the response

	// These two fields will be empty for HEAD requests.
	ErrorCode string // Error reason provided by CouchDB
	Reason    string // Error message provided by CouchDB
}

Error represents API-level errors, reported by CouchDB as

{"error": <ErrorCode>, "reason": <Reason>}

func (*Error) Error

func (e *Error) Error() string

type Members

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

Members represents member lists in database security objects.

type Options

type Options map[string]interface{}

Options represents CouchDB query string parameters.

type Security

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

Security represents database security objects.

Directories

Path Synopsis
cmd
couchapp
The couchapp tool deploys a directory as a CouchDB design document.
The couchapp tool deploys a directory as a CouchDB design document.
couchfeed
The couchfeed tool logs CouchDB feeds.
The couchfeed tool logs CouchDB feeds.
Package couchapp implements a mapping from files to CouchDB documents.
Package couchapp implements a mapping from files to CouchDB documents.
Package couchdaemon provides utilities for processes running as a CouchDB os_daemon.
Package couchdaemon provides utilities for processes running as a CouchDB os_daemon.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL