sofa

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2020 License: MIT Imports: 22 Imported by: 0

README

sofa

Simply connect to CouchDB database servers using Go.

Documentation

View the full documentation which includes examples.

Limitations

Large parts of the CouchDB API are covered but not all functionality is currently implemented. Pull requests for any missing functionality would be welcomed!

Contributing

Contributions of all sizes are welcomed. Simply make a pull request and I will be happy to discuss. If you don't have time to write the code please consider at least creating an issue so that I can ensure the issue gets sorted eventually.

Running tests

The basic tests can be run using a simple go test '-run=^Test' (this ensures that the examples are skipped because they require a CouchDB connection). To run a more complete set of tests which access a real database you will need a temporary CouchDB instance. The simplest way to create this is using docker:

docker run -d --name couchdb1 -p 5984:5984 couchdb:1

To run all the tests you will also need a version 2 server:

docker run -d --name couchdb2 -p 5985:5984 couchdb:2

You can then set SOFA_TEST_HOST_1 and SOFA_TEST_HOST_2 to set the connection to each server:

SOFA_TEST_HOST_1=http://127.0.0.1:5984 SOFA_TEST_HOST_2=http://127.0.0.1:5985 go test -v

If you have chosen to only start a single version then only include the appropriate environment variable to ensure tests for the other version are not run.

Documentation

Overview

Example (CreateDatabase)

ExampleCreateDatabase

package main

import (
	"fmt"
	"time"

	"github.com/kuniseichi/sofa"
)

func main() {
	// Make the connection with no authentication
	conn, err := sofa.NewConnection("http://localhost:5984", 10*time.Second, sofa.NullAuthenticator())
	if err != nil {
		panic(err)
	}

	// Create a new database
	db, err := conn.CreateDatabase("example_db")
	if err != nil {
		panic(err)
	}

	// Show the DB details
	fmt.Println(db.Name())

	md, err := db.Metadata()
	if err != nil {
		panic(err)
	}

	fmt.Println(md.DocCount)
	fmt.Println(md.DelCount)
}
Output:

example_db
0
0
Example (CreateDocument)

ExampleCreateDocument creates a

package main

import (
	"fmt"
	"time"

	"github.com/kuniseichi/sofa"
)

type Fruit struct {
	sofa.DocumentMetadata
	Name string `json:"name"`
	Type string `json:"type"`
}

// ExampleCreateDocument creates a
func main() {
	conn, err := sofa.NewConnection("http://localhost:5984", 10*time.Second, sofa.NullAuthenticator())
	if err != nil {
		panic(err)
	}

	// Open the previously-created database
	db := conn.Database("example_db")

	// Create a document to save
	doc := &Fruit{
		DocumentMetadata: sofa.DocumentMetadata{
			ID: "fruit1",
		},
		Name: "apple",
		Type: "fruit",
	}

	// Create the document on the CouchDB server
	rev, err := db.Put(doc)
	if err != nil {
		panic(err)
	}

	// Retrieve the document which was created
	getDoc := &Fruit{}
	getRev, err := db.Get(getDoc, "fruit1", "")
	if err != nil {
		panic(err)
	}

	// Is the document we put there the same revision we got back?
	if getRev != rev {
		panic("someone changed the document while this was running")
	}

	// Show the struct which was returned from the DB
	fmt.Printf("Name: %s\n", getDoc.Name)
	fmt.Printf("Type: %s\n", getDoc.Type)
}
Output:

Name: apple
Type: fruit
Example (CreateUser)
package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/kuniseichi/sofa"
)

func main() {
	conn, err := sofa.NewConnection("http://localhost:5984", 10*time.Second, sofa.NullAuthenticator())
	if err != nil {
		panic(err)
	}

	user := sofa.UserDocument{
		Name:     "Couchy McCouchface",
		Password: "example",
		Roles:    []string{"boat"},
		TheType:  "user",
	}

	rev, err := conn.CreateUser(&user)
	if err != nil {
		panic(err)
	}

	// Show the revision which has been created
	fmt.Println(strings.Split(rev, "-")[0])

	// Retrieve the document which was created
	realUser, err := conn.User("Couchy McCouchface", rev)
	if err != nil {
		panic(err)
	}

	// Show the whole retrieved user
	// fmt.Printf("%+v\n", realUser)

	// Modify the roles for the user
	realUser.Roles = []string{"issue_creator"}

	// Save the modified user
	updateRev, err := conn.UpdateUser(&realUser)
	if err != nil {
		panic(err)
	}

	// Ensure the document has the latest revision so the delete works
	realUser.DocumentMetadata.Rev = updateRev

	// Delete the user
	delrev, err := conn.DeleteUser(&realUser)
	if err != nil {
		panic(err)
	}

	fmt.Println(strings.Split(delrev, "-")[0])
}
Output:

1
3
Example (DeleteDatabase)

ExampleDeleteDatabase

package main

import (
	"fmt"
	"time"

	"github.com/kuniseichi/sofa"
)

func main() {
	// Make the connection with no authentication
	conn, err := sofa.NewConnection("http://localhost:5984", 10*time.Second, sofa.NullAuthenticator())
	if err != nil {
		panic(err)
	}

	// Cleanup the database again
	if err := conn.DeleteDatabase("example_db"); err != nil {
		panic(err)
	}

	// Get the current list of databases and show that example_db has been removed
	dbs, err := conn.ListDatabases()
	if err != nil {
		panic(err)
	}
	fmt.Println(dbs)
}
Output:

[]

Index

Examples

Constants

View Source
const (
	// FeedPolling represents a "normal" feed in CouchDB which regulargly polls
	// the server for updates.
	FeedPolling changesFeedType = "normal"
	// FeedLongPolling represents the type of feed which uses long-polling to reduce
	// polling frequency & therefore requests to the server.
	FeedLongPolling changesFeedType = "longpoll"
	// FeedContinuous represents the type of feed which holds open a connection to
	// the server and receives a stream of events.
	FeedContinuous changesFeedType = "continuous"
	// FeedEventSource represents the CouchDB feed type of "eventsource". This type is not
	// yet implemented in this library.
	FeedEventSource changesFeedType = "eventsource"
)

Variables

This section is empty.

Functions

func ErrorStatus

func ErrorStatus(err error, statusCode int) bool

ErrorStatus checks returns true if the provided error is a ResponseError with a status code which matches the one provided.

func ToBoolean

func ToBoolean(b BooleanParameter) bool

ToBoolean converts a sofa.BooleanParameter value into a standard bool.

Types

type Attachment

type Attachment struct {
	ContentType   string  `json:"content_type,omitempty"`
	Data          string  `json:"data,omitempty"`
	Digest        string  `json:"digest,omitempty"`
	EncodedLength float64 `json:"encoded_length,omitempty"`
	Encoding      string  `json:"encoding,omitempty"`
	Length        int64   `json:"length,omitempty"`
	RevPos        float64 `json:"revpos,omitempty"`
	Stub          bool    `json:"stub,omitempty"`
	Follows       bool    `json:"follows,omitempty"`
}

Attachment represents files or other data which is attached to documents in the Database.

type Authenticator

type Authenticator interface {
	// Authenticate adds authentication to an existing http.Request.
	Authenticate(req *http.Request)

	// Client returns a client with the correct authentication setup to contact the CouchDB server.
	Client() (*http.Client, error)

	// Setup uses the provided connection to setup any authentication information which requires accessing
	// the CouchDB server.
	Setup(*Connection) error

	// Verify sets whether verififcation of server HTTPS certs will be performed by clients created
	// by this authenticator. The default for all authenticators should be to perform the verification
	// unless this method is called with the argument 'false' to specifically disable it.
	Verify(bool)
}

Authenticator is an interface for anything which can supply authentication to a CouchDB server. The Authenticator is given access to every request made & also allowed to perform an initial setup on the connection.

func BasicAuthenticator

func BasicAuthenticator(user, pass string) Authenticator

BasicAuthenticator returns an implementation of the Authenticator interface which does HTTP basic authentication. If you are not using SSL then this will result in credentials being sent in plain text.

func ClientCertAuthenticator

func ClientCertAuthenticator(certPath, keyPath, caPath string) (Authenticator, error)

ClientCertAuthenticator provides an Authenticator which uses a client SSL certificate to authenticate to the couchdb server

func ClientCertAuthenticatorPassword added in v0.3.1

func ClientCertAuthenticatorPassword(certPath, keyPath, caPath, password string) (Authenticator, error)

ClientCertAuthenticatorPassword provides an Authenticator which uses a client SSL certificate to authenticate to the couchdb server. This version allows the user to specify the password `the key is encrypted with.

func CookieAuthenticator

func CookieAuthenticator() Authenticator

CookieAuthenticator returns an implementation of the Authenticator interface which supports authentication

func NullAuthenticator

func NullAuthenticator() Authenticator

NullAuthenticator is an Authenticator which does no work - it implements the interface but does not supply any authentication information to the CouchDB server.

func ProxyAuthenticator

func ProxyAuthenticator(username string, roles []string, secret string) Authenticator

ProxyAuthenticator returns an implementation of the Authenticator interface which supports the proxy authentication method described in the CouchDB documentation. This should not be used against a production server as the proxy would be expected to set the headers in that case.

type BooleanParameter

type BooleanParameter string

BooleanParameter is a special type of boolean created to have a zero value where it is not included in URL parameter output. This is useful for taking the default values of a parameter.

const (
	// Empty is the zero value for the BooleanParameter type. It is the default
	// type and values of this type are not included in the URL parameters.
	Empty BooleanParameter = ""
	// True is the BooleanParameter equivalent of true. It will always be
	// included in a query string.
	True BooleanParameter = "true"
	// False is the BooleanParameter equivalent of true. It will always be
	// included in a query string.
	False BooleanParameter = "false"
)

func FromBoolean

func FromBoolean(b bool) BooleanParameter

FromBoolean converts a standard bool value into a sofa.BooleanParameter for use in documents to allow not including unset booleans.

func (BooleanParameter) String added in v0.3.1

func (b BooleanParameter) String() string

type ChangesFeed

type ChangesFeed interface {
	Next(ChangesFeedParams) (ChangesFeedUpdate, error)
}

ChangesFeed is an interface which is implemented by all types of changes feed which are available on the server.

type ChangesFeedChange

type ChangesFeedChange struct {
	Changes []struct {
		Rev string `json:"rev"`
	} `json:"changes"`
	Deleted bool   `json:"deleted"`
	ID      string `json:"id"`
	Seq     int64  `json:"seq"`
}

ChangesFeedChange is a single change to a document in the database. One of more of these will be included in updates where any changes were actually made.

type ChangesFeedParams

type ChangesFeedParams struct {
	DocumentIDs            []string         `url:"doc_ids,omitempty"`
	Conflicts              BooleanParameter `url:"conflicts,omitempty"`
	Descending             BooleanParameter `url:"descending,omitempty"`
	Feed                   string           `url:"feed,omitempty"`
	Filter                 string           `url:"filter,omitempty"`
	Heartbeat              int64            `url:"heartbeat,omitempty"`
	IncludeDocs            BooleanParameter `url:"include_docs,omitempty"`
	Attachments            BooleanParameter `url:"attachments,omitempty"`
	AttachmentEncodingInfo BooleanParameter `url:"att_encoding_info,omitempty"`
	LastEventID            int64            `url:"last-event-id,omitempty"`
	Limit                  int64            `url:"limit,omitempty"`
	Since                  int64            `url:"since,omitempty"`
	Style                  string           `url:"style,omitempty"`
	Timeout                int64            `url:"timeout,omitempty"`
	View                   string           `url:"view,omitempty"`
}

ChangesFeedParams includes all parameters which can be provided to control the output of a changes feed from a database.

func (ChangesFeedParams) Values added in v0.3.1

func (params ChangesFeedParams) Values() (url.Values, error)

Values converts a ChangesFeedParams to a url.Values by performing pre-conversion of any values which require special handling by conversion to JSON before being passed to CouchDB.

type ChangesFeedUpdate

type ChangesFeedUpdate struct {
	LastSeq int64               `json:"last_seq"`
	Pending int64               `json:"pending"`
	Results []ChangesFeedChange `json:"results"`
}

ChangesFeedUpdate is a single update from a changes feed.

type Connection

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

Connection is a connection to a CouchDB server. It provides all of the unversioned methods which are identical between CouchDB versions.

func (*Connection) AllClusterStatistics added in v0.3.1

func (con *Connection) AllClusterStatistics() (Statistics2, error)

AllClusterStatistics gets all of the available statistics from the server.

func (*Connection) ClusterStatistic added in v0.3.1

func (con *Connection) ClusterStatistic(category, name string) (Statistics2, error)

ClusterStatistic loads a single specific statistic from the server by category & name.

func (*Connection) CreateDatabase

func (con *Connection) CreateDatabase(name string) (*Database, error)

CreateDatabase creates a new database on the CouchDB server and returns a pointer to a Database initialised with the new values.

func (*Connection) CreateUser added in v0.3.1

func (con *Connection) CreateUser(user *UserDocument) (string, error)

CreateUser creates a new document in the _users database.

func (*Connection) Database

func (con *Connection) Database(name string) *Database

Database creates a new Database object. No validation or contact with the couchdb server is performed in this method so it is possible to create Database objects for databases which do not exist

func (*Connection) Databases

func (con *Connection) Databases() (databases []*Database, err error)

Databases returns a Database object for every database on the server, excluding CouchDB internal databases as there are special methods for accessing them.

func (*Connection) Delete

func (con *Connection) Delete(path string, opts Options) (resp *http.Response, err error)

Delete sends a DELETE request to the provided path on the CouchDB server.

func (*Connection) DeleteDatabase

func (con *Connection) DeleteDatabase(name string) error

DeleteDatabase removes the specified database from the CouchDB server.

func (*Connection) DeleteReplication

func (con *Connection) DeleteReplication(repl *Replication) (string, error)

DeleteReplication removes a replication from the replicator database and cancels it.

func (*Connection) DeleteUser added in v0.3.1

func (con *Connection) DeleteUser(user *UserDocument) (string, error)

DeleteUser deletes an existing user from the _users database.

func (*Connection) EnsureDatabase

func (con *Connection) EnsureDatabase(name string) (*Database, error)

EnsureDatabase creates a new Database object & then requests the metadata to ensure that the Database actually exists on the server. The Database is returned with the metadata already available.

func (*Connection) Get

func (con *Connection) Get(path string, opts Options) (resp *http.Response, err error)

Get sends a GET request to the provided path on the CouchDB server.

func (*Connection) Head

func (con *Connection) Head(path string, opts Options) (resp *http.Response, err error)

Head sends a HEAD request to the provided path on the CouchDB server.

func (*Connection) ListDatabases

func (con *Connection) ListDatabases() (databases []string, err error)

ListDatabases returns the list of all database names on the server. Internal couchdb databases _replicator and _users are excluded as they are always present & accessed using special methods

func (*Connection) Patch

func (con *Connection) Patch(path string, opts Options, body io.Reader) (resp *http.Response, err error)

Patch sends a PATCH request to the provided path on the CouchDB server. The contents of the provided io.Reader is sent as the body of the request.

func (*Connection) Ping

func (con *Connection) Ping() error

Ping tests basic connection to CouchDB by making a HEAD request for one of the databases

func (*Connection) Post

func (con *Connection) Post(path string, opts Options, body io.Reader) (resp *http.Response, err error)

Post sends a POST request to the provided path on the CouchDB server. The contents of the provided io.Reader is sent as the body of the request.

func (*Connection) Put

func (con *Connection) Put(path string, opts Options, body io.Reader) (resp *http.Response, err error)

Put sends a PUT request to the provided path on the CouchDB server. The contents of the provided io.Reader is sent as the body of the request.

func (*Connection) PutReplication added in v0.3.1

func (con *Connection) PutReplication(repl *Replication) (string, error)

PutReplication saves a replication to the CouchDB server _replicator database.

func (*Connection) Replication

func (con *Connection) Replication(id, rev string) (Replication, error)

Replication gets a particular Replication from the server by ID. A revision can also be specified to retrieve a particular revision of the document.

func (*Connection) Replications

func (con *Connection) Replications() ([]Replication, error)

Replications returns the full list of replications currently active on the server.

func (*Connection) Request

func (con *Connection) Request(method, path string, opts Options, body io.Reader) (resp *http.Response, err error)

Request performs a request and returns the http.Response which results from that request. Request also checks the response status and returns a ResponseError if an error HTTP statuscode is received.

func (*Connection) URL

func (con *Connection) URL(path string) url.URL

URL returns the URL of the server with a path appended.

func (*Connection) UpdateUser added in v0.3.1

func (con *Connection) UpdateUser(user *UserDocument) (string, error)

UpdateUser modifies details of a user document.

func (*Connection) User

func (con *Connection) User(name string, rev string) (UserDocument, error)

User gets a particular UserDocument from the server by name. A revision can also be specified to retrieve a particular revision of the document (or an empty string supplied to fetch the current version). This makes the assumption that the user exists in the 'org.couchdb.user' namespace but I am unaware of any situation where that is not true. If the user doesn't exist in this namespace it should be possible to retrieve them with UserByID.

func (*Connection) UserByID added in v0.3.1

func (con *Connection) UserByID(id string, rev string) (UserDocument, error)

UserByID gets a CouchDB user by the ID of ther user document rather than their name.

func (*Connection) Users

func (con *Connection) Users() ([]UserDocument, error)

Users gets a list of all users currently active on this CouchDB server

type ContinuousChangesFeed

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

ContinuousChangesFeed maintains a connection to the database and receives continuous updates as they arrive.

func (*ContinuousChangesFeed) Next

Next gets the next available item from the changes feed. This will block until an item becomes available.

type CouchDB1Connection added in v0.3.1

type CouchDB1Connection struct {
	*Connection
}

CouchDB1Connection is a connection specifically for a version 1 server.

func NewConnection

func NewConnection(serverURL string, timeout time.Duration, auth Authenticator) (*CouchDB1Connection, error)

NewConnection creates a new CouchDB1Connection which can be used to interact with a single CouchDB server. Any query parameters passed in the serverUrl are discarded before creating the connection.

func (*CouchDB1Connection) AllStatistics added in v0.3.1

func (con *CouchDB1Connection) AllStatistics() (Statistics1, error)

AllStatistics gets all of the available statistics from the server.

func (*CouchDB1Connection) FutonURL added in v0.3.1

func (con *CouchDB1Connection) FutonURL(path string) url.URL

FutonURL attempts to correctly convert any CouchDB path into a URL to be used to access the same documents through the Futon web GUI.

func (*CouchDB1Connection) ServerInfo added in v0.3.1

func (con *CouchDB1Connection) ServerInfo() (ServerDetails1, error)

ServerInfo gets the information about this CouchDB instance returned when accessing the root page

func (*CouchDB1Connection) Statistic added in v0.3.1

func (con *CouchDB1Connection) Statistic(category, name string) (Statistics1, error)

Statistic loads a single specific statistic from the server by category & name.

type CouchDB2Connection added in v0.3.1

type CouchDB2Connection struct {
	*Connection
}

CouchDB2Connection is a connection specifically for a version 2 server.

func NewConnection2 added in v0.3.1

func NewConnection2(serverURL string, timeout time.Duration, auth Authenticator) (*CouchDB2Connection, error)

NewConnection2 creates a new CouchDB2Connection which can be used to interact with a single CouchDB server. Any query parameters passed in the serverUrl are discarded before creating the connection.

func (*CouchDB2Connection) AllStatistics added in v0.3.1

func (con *CouchDB2Connection) AllStatistics() (Statistics2, error)

AllStatistics gets all of the available statistics from the server.

func (*CouchDB2Connection) FauxtonURL added in v0.3.1

func (con *CouchDB2Connection) FauxtonURL(path string) url.URL

FauxtonURL attempts to correctly convert any CouchDB path into a URL to be used to access the same documents through the Fauxton web GUI.

func (*CouchDB2Connection) ServerInfo added in v0.3.1

func (con *CouchDB2Connection) ServerInfo() (ServerDetails2, error)

ServerInfo gets the information about this CouchDB instance returned when accessing the root page

func (*CouchDB2Connection) Statistic added in v0.3.1

func (con *CouchDB2Connection) Statistic(category, name string) (Statistics2, error)

Statistic loads a single specific statistic from the server by category & name.

type Database

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

Database represents a CouchDB database & provides methods to access documents in the database.

func (*Database) AllDocuments

func (d *Database) AllDocuments() (DocumentList, error)

AllDocuments gets all documents from a database. All document content is included for each row.

func (*Database) CompactView

func (d *Database) CompactView(name string) error

CompactView compacts the stored data for a view, meaning that the view uses less space on the disk.

func (*Database) ContinuousChangesFeed

func (d *Database) ContinuousChangesFeed(params ChangesFeedParams) ContinuousChangesFeed

ContinuousChangesFeed gets a changes feed with a continuous connection to the database. New changes are then pushed over the existing connection as they arrive.

func (*Database) Delete

func (d *Database) Delete(document Document) (string, error)

Delete removed a document from the Database.

func (*Database) DeleteAttachment added in v0.3.1

func (db *Database) DeleteAttachment(docid, name, rev string) (string, error)

DeleteAttachment removes an attachment from a document in CouchDB.

func (*Database) DocumentPath

func (d *Database) DocumentPath(id string) string

DocumentPath returns the path to a document in this database

func (*Database) Documents

func (d *Database) Documents(ids ...string) (DocumentList, error)

Documents gets a set of Documents from a database. All of the IDs requested will be downloaded & all document content is included for each row.

func (*Database) Get

func (d *Database) Get(document Document, id, rev string) (string, error)

Get retrieves a single document from the database and unmarshals it into the provided interface.

func (*Database) GetAttachment added in v0.3.1

func (db *Database) GetAttachment(docid, name, rev string) ([]byte, error)

GetAttachment gets the current attachment and returns

func (*Database) ListDocuments

func (d *Database) ListDocuments() (DocumentList, error)

ListDocuments gets all rows from the Database but does not include the content of the documents.

func (*Database) Metadata

func (d *Database) Metadata() (DatabaseMetadata, error)

Metadata downloads the Metadata for the Database and saves it to the Database object. If there is already metadata stored then that will be returned without contacting the server.

func (*Database) Name

func (d *Database) Name() string

Name returns the name of the Database.

func (*Database) NamedView

func (d *Database) NamedView(design, name string) NamedView

NamedView creates a new NamedView for this database. This can then be used to access the current results of the permanent view on the design document.

func (*Database) Path

func (d *Database) Path() string

Path returns the path for this database. The value (as with the other *Path functions) is in the correct for to be passed to Connection.URL()

func (*Database) PollingChangesFeed

func (d *Database) PollingChangesFeed(long bool) PollingChangesFeed

PollingChangesFeed gets a changes feed which will poll the server for changes to documents.

func (*Database) Put

func (d *Database) Put(document Document) (string, error)

Put marshals the provided document into JSON and the sends it to the CouchDB server with a PUT request. This allows modification of the document on the server.

func (*Database) PutAttachment added in v0.3.1

func (db *Database) PutAttachment(docid, name string, doc io.Reader, rev string) (string, error)

PutAttachment replaces the content of the attachment with new content read from an io.Reader or creates it if it does not exist. If the provided rev is not the most recent then an error will be returned from CouchDB.

func (*Database) TemporaryView

func (d *Database) TemporaryView(mapFunc string) TemporaryView

TemporaryView creates a temporary view for this database. Only the map function is required but other parameters canbe added to the resulting TemporaryView if required.

func (*Database) ViewCleanup

func (d *Database) ViewCleanup() error

ViewCleanup cleans old data from the database. From the CouchDB API documentation: "Old view output remains on disk until you explicitly run cleanup."

func (*Database) ViewPath

func (d *Database) ViewPath(view string) string

ViewPath returns the path to a view in this database

type DatabaseMetadata

type DatabaseMetadata struct {
	CompactRunning     bool   `json:"compact_running"`
	Name               string `json:"db_name"`
	DocCount           int    `json:"doc_count"`
	DelCount           int    `json:"doc_del_count"`
	InstanceStartTime  string `json:"instance_start_time"`
	DataSize           int    `json:"data_size"`
	DiskSize           int    `json:"disk_size"`
	DiskFormatVersion  int    `json:"disk_format_version"`
	PurgeSeq           string `json:"purge_seq"`
	UpdateSeq          string `json:"update_seq"`
	CommittedUpdateSeq int    `json:"committed_update_seq"`
}

DatabaseMetadata contains information about the database in CouchDB.

type DetailedStatistic added in v0.3.1

type DetailedStatistic struct {
	Desc  string `json:"desc"`
	Type  string `json:"type"`
	Value struct {
		ArithmeticMean    float64     `json:"arithmetic_mean"`
		GeometricMean     float64     `json:"geometric_mean"`
		HarmonicMean      float64     `json:"harmonic_mean"`
		Histogram         [][]float64 `json:"histogram"`
		Kurtosis          float64     `json:"kurtosis"`
		Max               float64     `json:"max"`
		Median            float64     `json:"median"`
		Min               float64     `json:"min"`
		N                 float64     `json:"n"`
		Percentile        [][]float64 `json:"percentile"`
		Skewness          float64     `json:"skewness"`
		StandardDeviation float64     `json:"standard_deviation"`
		Variance          float64     `json:"variance"`
	} `json:"value"`
}

DetailedStatistic is the type used by CouchDB 2 to represent a statistic with included statistical data such as the mean, max, min, median, kurtosis etc.

type Document

type Document interface {
	Metadata() DocumentMetadata
}

Document is the interface which represents a CouchDB document. Contains methods to retrieve the metadata and the database containing this document.

type DocumentList

type DocumentList struct {
	TotalRows float64 `json:"total_rows"`
	Offset    float64 `json:"offset"`
	Rows      []Row   `json:"rows"`
}

DocumentList is the CouchDB reprentation of a list of Documents where each document is contained within a Row along with some metadata. Depending on the view & the request paramaters used the documents may or may not be included in the row.

func (*DocumentList) MapDocuments

func (dl *DocumentList) MapDocuments() ([]map[string]interface{}, error)

MapDocuments returns a list containing the document from each row in this DocumentList Unmarshalled into a map[string]interface{}.

func (*DocumentList) RawDocuments

func (dl *DocumentList) RawDocuments() []json.RawMessage

RawDocuments returns the Document from each Row of this DocumentList as a json.RawMessage which can then be Unmarshalled into the correct type.

func (*DocumentList) Size

func (dl *DocumentList) Size() int

Size returns the number of documents currently stored in this DocumentList.

func (*DocumentList) UnmarshalDocuments

func (dl *DocumentList) UnmarshalDocuments(docs interface{}) error

UnmarshalDocuments is a convenience function which unmarshalls just the list of Documents from this. Due to a Marshal/Unmarhal cycle this method may be slow. Sometimes slow is fine though.

type DocumentMetadata

type DocumentMetadata struct {
	ID  string `json:"_id,omitempty"`
	Rev string `json:"_rev,omitempty"`
}

DocumentMetadata is the minimum amount of content which all documents have. It is the identity and revision of the document.

func (DocumentMetadata) Metadata

func (md DocumentMetadata) Metadata() DocumentMetadata

Metadata provides a default implementation of the Document interface which is used when a DocumentMetadata is embedded in another struct.

type GenericDocument

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

GenericDocument implements the Document API and can be used to represent any type of document. For all but simple cases it is better to implement this yourself ona struct for easier access to the unmarshalled data.

func (*GenericDocument) MarshalJSON

func (gen *GenericDocument) MarshalJSON() ([]byte, error)

MarshalJSON provides an implementation of json.Marshaler by marshaling the stored map document into JSON data.

func (*GenericDocument) Metadata

func (gen *GenericDocument) Metadata() DocumentMetadata

Metadata gets the DocumentMetadata for this Document

func (*GenericDocument) UnmarshalJSON

func (gen *GenericDocument) UnmarshalJSON(data []byte) error

UnmarshalJSON provides an implementation of json.Unmarshaler by unmarshaling the provides data into the stored map.

type InterfaceListParameter added in v0.3.1

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

InterfaceListParameter is a type used to pass a []interface{} to CouchDB with the correct JSON representation.

func NewInterfaceListParameter added in v0.3.1

func NewInterfaceListParameter(ifaces []interface{}) *InterfaceListParameter

NewInterfaceListParameter generates an InterfaceListParameter from a []interface{}. This is required before passing to CouchDB because it needs to be converted to JSON in a custom way for CouchDB to understand it correctly.

func (InterfaceListParameter) MarshalJSON added in v0.3.1

func (i InterfaceListParameter) MarshalJSON() ([]byte, error)

MarshalJSON simply marshals the internal value.

type InterfaceParameter added in v0.3.1

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

InterfaceParameter is a wrapper for an empty interface which ensures that it is correctly formatted when passed as a query parameter to CouchDB. The reason for this is that strings passed are usually required not to be quoted but in these fields which can also take JSON objects of other types the quotes seem required

func NewInterfaceParameter added in v0.3.1

func NewInterfaceParameter(iface interface{}) *InterfaceParameter

NewInterfaceParameter returns a pointer to an InterfaceParameter wrapping the provided value. All new InterfaceParameters must be created through this function.

func (InterfaceParameter) EncodeValues added in v0.3.1

func (i InterfaceParameter) EncodeValues(key string, v *url.Values) error

EncodeValues implements the Encoder interface provided by github.com/google/go-querystring to perform a custom marshal when converted to a query string.

func (InterfaceParameter) MarshalJSON added in v0.3.1

func (i InterfaceParameter) MarshalJSON() ([]byte, error)

MarshalJSON simply marshals the internal value, to ensure these objects are always included using the JSON-formatted representation of just the inner value.

type NamedView

type NamedView struct {
	DesignDoc string
	Name      string
	// contains filtered or unexported fields
}

NamedView represents a view stored on a design document in the database. It must be accessed with both the name of the design document and the name of the view.

func (NamedView) Execute

func (v NamedView) Execute(params ViewParams) (DocumentList, error)

Execute implements View for NamedView.

func (NamedView) FullPath

func (v NamedView) FullPath() string

FullPath gets the path of the NamedView relative to the server root.

func (NamedView) Path

func (v NamedView) Path() string

Path gets the path of the NamedView relative to the database root.

type Options

type Options interface {
	Encode() string
}

Options is a slightly modified version of url.Options which provides query options with JSON encoding of values.

type PollingChangesFeed

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

PollingChangesFeed can be used for either type of changes feed which polls the database for information ("normal" and "longpoll").

func (PollingChangesFeed) Next

Next polls for the next update from the database. This may block until a timeout is reached if there are no updates available.

type Replication

type Replication struct {
	DocumentMetadata

	CreateTarget bool `json:"create_target,omitempty"`
	Continuous   bool `json:"continuous,omitempty"`

	Connections     float64 `json:"connection_timeout,omitempty"`
	Retries         float64 `json:"retries_per_request,omitempty"`
	HTTPConnections float64 `json:"http_connections,omitempty"`

	Target string `json:"target,omitempty"`
	Source string `json:"source,omitempty"`

	Owner          string `json:"owner,omitempty"`
	AdditionalType string `json:"additionalType,omitempty"`

	ReplicationState       string                 `json:"_replication_state,omitempty"`
	ReplicationStateReason string                 `json:"_replication_state_reason,omitempty"`
	ReplicationStateTime   string                 `json:"_replication_state_time,omitempty"`
	ReplicationID          string                 `json:"_replication_id,omitempty"`
	ReplicationStats       map[string]interface{} `json:"_replication_stats,omitempty"`

	UserContext map[string]interface{} `json:"user_ctx,omitempty"`
	QueryParams map[string]interface{} `json:"query_params,omitempty"`
}

Replication represents a single document in the CouchDB '_replicator' database. Each one of these documents represents a replication between two databases. The full API documentation is located at: http://docs.couchdb.org/en/2.0.0/replication/replicator.html

func NewReplication added in v0.3.1

func NewReplication(id, source, target string) Replication

NewReplication creates a new Replication instance with the source and target defined.

type ResponseError

type ResponseError struct {
	Method     string
	StatusCode int
	URL        string

	Err    string
	Reason string
}

ResponseError represents an error response from CouchDB. The method & URL of the request are included as well as the HTTP status code. If the request was not a HEAD request then the values from the JSON error returned by CouchDB will be included.

func (ResponseError) Error

func (e ResponseError) Error() string

Error provodes a detailed representation of the response error including as much information as there is available

type Row

type Row struct {
	ID       string          `json:"id,omitempty"`
	Key      interface{}     `json:"key,omitempty"`
	Value    interface{}     `json:"value,omitempty"`
	Document json.RawMessage `json:"doc,omitempty"`
}

Row represents a row in a CouchDB DocumentList. These are mainly returned by views but may also be sent to the server as part of the bulk documents API.

func (Row) HasDocument

func (r Row) HasDocument() bool

HasDocument checks the current Row for the presence of the Document attached to it.

type ServerDetails1 added in v0.3.1

type ServerDetails1 struct {
	CouchDB string                 `json:"couchdb"`
	UUID    string                 `json:"uuid"`
	Version string                 `json:"version"`
	Vendor  map[string]interface{} `json:"vendor"`
}

ServerDetails1 represents the details returned from a CouchDB version 1 server when requesting the root page.

type ServerDetails2 added in v0.3.1

type ServerDetails2 struct {
	CouchDB  string                 `json:"couchdb"`
	Features []string               `json:"features"`
	Version  string                 `json:"version"`
	Vendor   map[string]interface{} `json:"vendor"`
}

ServerDetails2 represents the details returned from a CouchDB version 2 server when requesting the root page.

type ServerResponse

type ServerResponse struct {
	RawResponse *http.Response
	ResultBody  *struct {
		OK  bool   `json:"ok"`
		ID  string `json:"id"`
		Rev string `json:"rev"`
	}
}

ServerResponse is a parsed CouchDB response which also contains a RawResponse field containing a pointer to the unaltered http.Response.

func (*ServerResponse) HasBody

func (resp *ServerResponse) HasBody() bool

HasBody returns true if the response from the server has a body (will return false for HEAD requests).

type SimpleStatistic added in v0.3.1

type SimpleStatistic struct {
	Desc  string  `json:"desc"`
	Type  string  `json:"type"`
	Value float64 `json:"value"`
}

SimpleStatistic is the type used by CouchDB 2 to represent a statistic which does not have detailed statistical data associated with it meaning that it is just a single value.

type Statistic1 added in v0.3.1

type Statistic1 struct {
	Current     *float64 `json:"current"`
	Description string   `json:"description"`
	Max         *float64 `json:"max"`
	Mean        *float64 `json:"mean"`
	Min         *float64 `json:"min"`
	Stddev      *float64 `json:"stddev"`
	Sum         *float64 `json:"sum"`
}

Statistic1 represents the format which each statistic returned from CouchDB version 1 has.

type Statistics1 added in v0.3.1

type Statistics1 struct {
	CouchDB struct {
		AuthCacheHits   *Statistic1 `json:"auth_cache_hits,omitempty"`
		AuthCacheMisses *Statistic1 `json:"auth_cache_misses,omitempty"`
		DatabaseReads   *Statistic1 `json:"database_reads,omitempty"`
		DatabaseWrites  *Statistic1 `json:"database_writes,omitempty"`
		OpenDatabases   *Statistic1 `json:"open_databases,omitempty"`
		OpenOsFiles     *Statistic1 `json:"open_os_files,omitempty"`
		RequestTime     *Statistic1 `json:"request_time,omitempty"`
	} `json:"couchdb,omitempty"`
	HTTPD struct {
		BulkRequests             *Statistic1 `json:"bulk_requests,omitempty"`
		ClientsRequestingChanges *Statistic1 `json:"clients_requesting_changes,omitempty"`
		Requests                 *Statistic1 `json:"requests,omitempty"`
		TemporaryViewReads       *Statistic1 `json:"temporary_view_reads,omitempty"`
		ViewReads                *Statistic1 `json:"view_reads,omitempty"`
	} `json:"httpd,omitempty"`
	HTTPDRequestMethods struct {
		Copy   *Statistic1 `json:"COPY,omitempty"`
		Delete *Statistic1 `json:"DELETE,omitempty"`
		Get    *Statistic1 `json:"GET,omitempty"`
		Head   *Statistic1 `json:"HEAD,omitempty"`
		Post   *Statistic1 `json:"POST,omitempty"`
		Put    *Statistic1 `json:"PUT,omitempty"`
	} `json:"httpd_request_methods,omitempty"`
	HTTPDStatusCodes struct {
		Two00   *Statistic1 `json:"200,omitempty"`
		Two01   *Statistic1 `json:"201,omitempty"`
		Two02   *Statistic1 `json:"202,omitempty"`
		Three01 *Statistic1 `json:"301,omitempty"`
		Three04 *Statistic1 `json:"304,omitempty"`
		Four00  *Statistic1 `json:"400,omitempty"`
		Four01  *Statistic1 `json:"401,omitempty"`
		Four03  *Statistic1 `json:"403,omitempty"`
		Four04  *Statistic1 `json:"404,omitempty"`
		Four05  *Statistic1 `json:"405,omitempty"`
		Four09  *Statistic1 `json:"409,omitempty"`
		Four12  *Statistic1 `json:"412,omitempty"`
		Five00  *Statistic1 `json:"500,omitempty"`
	} `json:"httpd_status_codes,omitempty"`
}

Statistics1 represents all of the statistics available from the CouchDB version 1 server. This is the format returned when all statistics are being accessed.

type Statistics2 added in v0.3.1

type Statistics2 struct {
	CouchLog struct {
		Level struct {
			Alert     SimpleStatistic `json:"alert"`
			Critical  SimpleStatistic `json:"critical"`
			Debug     SimpleStatistic `json:"debug"`
			Emergency SimpleStatistic `json:"emergency"`
			Error     SimpleStatistic `json:"error"`
			Info      SimpleStatistic `json:"info"`
			Notice    SimpleStatistic `json:"notice"`
			Warning   SimpleStatistic `json:"warning"`
		} `json:"level"`
	} `json:"couch_log"`
	CouchReplicator struct {
		ChangesManagerDeaths SimpleStatistic `json:"changes_manager_deaths"`
		ChangesQueueDeaths   SimpleStatistic `json:"changes_queue_deaths"`
		ChangesReadFailures  SimpleStatistic `json:"changes_read_failures"`
		ChangesReaderDeaths  SimpleStatistic `json:"changes_reader_deaths"`
		Checkpoints          struct {
			Failure SimpleStatistic `json:"failure"`
			Success SimpleStatistic `json:"success"`
		} `json:"checkpoints"`
		ClusterIsStable SimpleStatistic `json:"cluster_is_stable"`
		Connection      struct {
			Acquires      SimpleStatistic `json:"acquires"`
			Closes        SimpleStatistic `json:"closes"`
			Creates       SimpleStatistic `json:"creates"`
			OwnerCrashes  SimpleStatistic `json:"owner_crashes"`
			Releases      SimpleStatistic `json:"releases"`
			WorkerCrashes SimpleStatistic `json:"worker_crashes"`
		} `json:"connection"`
		DBScans SimpleStatistic `json:"db_scans"`
		Docs    struct {
			CompletedStateUpdates SimpleStatistic `json:"completed_state_updates"`
			DBChanges             SimpleStatistic `json:"db_changes"`
			DbsCreated            SimpleStatistic `json:"dbs_created"`
			DbsDeleted            SimpleStatistic `json:"dbs_deleted"`
			DbsFound              SimpleStatistic `json:"dbs_found"`
			FailedStateUpdates    SimpleStatistic `json:"failed_state_updates"`
		} `json:"docs"`
		FailedStarts SimpleStatistic `json:"failed_starts"`
		Jobs         struct {
			Adds          SimpleStatistic `json:"adds"`
			Crashed       SimpleStatistic `json:"crashed"`
			Crashes       SimpleStatistic `json:"crashes"`
			DuplicateAdds SimpleStatistic `json:"duplicate_adds"`
			Pending       SimpleStatistic `json:"pending"`
			Removes       SimpleStatistic `json:"removes"`
			Running       SimpleStatistic `json:"running"`
			Starts        SimpleStatistic `json:"starts"`
			Stops         SimpleStatistic `json:"stops"`
			Total         SimpleStatistic `json:"total"`
		} `json:"jobs"`
		Requests  SimpleStatistic `json:"requests"`
		Responses struct {
			Failure SimpleStatistic `json:"failure"`
			Success SimpleStatistic `json:"success"`
		} `json:"responses"`
		StreamResponses struct {
			Failure SimpleStatistic `json:"failure"`
			Success SimpleStatistic `json:"success"`
		} `json:"stream_responses"`
		WorkerDeaths   SimpleStatistic `json:"worker_deaths"`
		WorkersStarted SimpleStatistic `json:"workers_started"`
	} `json:"couch_replicator"`
	CouchDB struct {
		AuthCacheHits      SimpleStatistic   `json:"auth_cache_hits"`
		AuthCacheMisses    SimpleStatistic   `json:"auth_cache_misses"`
		CollectResultsTime DetailedStatistic `json:"collect_results_time"`
		CouchServer        struct {
			LruSkip SimpleStatistic `json:"lru_skip"`
		} `json:"couch_server"`
		DatabaseReads   SimpleStatistic   `json:"database_reads"`
		DatabaseWrites  SimpleStatistic   `json:"database_writes"`
		DBOpenTime      DetailedStatistic `json:"db_open_time"`
		DBInfo          DetailedStatistic `json:"dbinfo"`
		DocumentInserts SimpleStatistic   `json:"document_inserts"`
		DocumentWrites  SimpleStatistic   `json:"document_writes"`
		HTTPD           struct {
			AbortedRequests          SimpleStatistic   `json:"aborted_requests"`
			BulkDocs                 DetailedStatistic `json:"bulk_docs"`
			BulkRequests             SimpleStatistic   `json:"bulk_requests"`
			ClientsRequestingChanges SimpleStatistic   `json:"clients_requesting_changes"`
			Requests                 SimpleStatistic   `json:"requests"`
			TemporaryViewReads       SimpleStatistic   `json:"temporary_view_reads"`
			ViewReads                SimpleStatistic   `json:"view_reads"`
		} `json:"httpd"`
		HTTPDRequestMethods struct {
			Copy    SimpleStatistic `json:"COPY"`
			Delete  SimpleStatistic `json:"DELETE"`
			Get     SimpleStatistic `json:"GET"`
			Head    SimpleStatistic `json:"HEAD"`
			Options SimpleStatistic `json:"OPTIONS"`
			Post    SimpleStatistic `json:"POST"`
			Put     SimpleStatistic `json:"PUT"`
		} `json:"httpd_request_methods"`
		HTTPDStatusCodes struct {
			Two00   SimpleStatistic `json:"200"`
			Two01   SimpleStatistic `json:"201"`
			Two02   SimpleStatistic `json:"202"`
			Two04   SimpleStatistic `json:"204"`
			Two06   SimpleStatistic `json:"206"`
			Three01 SimpleStatistic `json:"301"`
			Three02 SimpleStatistic `json:"302"`
			Three04 SimpleStatistic `json:"304"`
			Four00  SimpleStatistic `json:"400"`
			Four01  SimpleStatistic `json:"401"`
			Four03  SimpleStatistic `json:"403"`
			Four04  SimpleStatistic `json:"404"`
			Four05  SimpleStatistic `json:"405"`
			Four06  SimpleStatistic `json:"406"`
			Four09  SimpleStatistic `json:"409"`
			Four12  SimpleStatistic `json:"412"`
			Four13  SimpleStatistic `json:"413"`
			Four14  SimpleStatistic `json:"414"`
			Four15  SimpleStatistic `json:"415"`
			Four16  SimpleStatistic `json:"416"`
			Four17  SimpleStatistic `json:"417"`
			Five00  SimpleStatistic `json:"500"`
			Five01  SimpleStatistic `json:"501"`
			Five03  SimpleStatistic `json:"503"`
		} `json:"httpd_status_codes"`
		LocalDocumentWrites SimpleStatistic `json:"local_document_writes"`
		MrView              struct {
			Emits  SimpleStatistic `json:"emits"`
			MapDoc SimpleStatistic `json:"map_doc"`
		} `json:"mrview"`
		OpenDatabases SimpleStatistic `json:"open_databases"`
		OpenOsFiles   SimpleStatistic `json:"open_os_files"`
		QueryServer   struct {
			VduProcessTime DetailedStatistic `json:"vdu_process_time"`
			VduRejects     SimpleStatistic   `json:"vdu_rejects"`
		} `json:"query_server"`
		RequestTime DetailedStatistic `json:"request_time"`
	} `json:"couchdb"`
	DDocCache struct {
		Hit      SimpleStatistic `json:"hit"`
		Miss     SimpleStatistic `json:"miss"`
		Recovery SimpleStatistic `json:"recovery"`
	} `json:"ddoc_cache"`
	Fabric struct {
		DocUpdate struct {
			Errors            SimpleStatistic `json:"errors"`
			MismatchedErrors  SimpleStatistic `json:"mismatched_errors"`
			WriteQuorumErrors SimpleStatistic `json:"write_quorum_errors"`
		} `json:"doc_update"`
		OpenShard struct {
			Timeouts SimpleStatistic `json:"timeouts"`
		} `json:"open_shard"`
		ReadRepairs struct {
			Failure SimpleStatistic `json:"failure"`
			Success SimpleStatistic `json:"success"`
		} `json:"read_repairs"`
		Worker struct {
			Timeouts SimpleStatistic `json:"timeouts"`
		} `json:"worker"`
	} `json:"fabric"`
	GlobalChanges struct {
		DBWrites               SimpleStatistic `json:"db_writes"`
		EventDocConflict       SimpleStatistic `json:"event_doc_conflict"`
		ListenerPendingUpdates SimpleStatistic `json:"listener_pending_updates"`
		Rpcs                   SimpleStatistic `json:"rpcs"`
		ServerPendingUpdates   SimpleStatistic `json:"server_pending_updates"`
	} `json:"global_changes"`
	Mem3 struct {
		ShardCache struct {
			Eviction SimpleStatistic `json:"eviction"`
			Hit      SimpleStatistic `json:"hit"`
			Miss     SimpleStatistic `json:"miss"`
		} `json:"shard_cache"`
	} `json:"mem3"`
	Pread struct {
		ExceedEOF   SimpleStatistic `json:"exceed_eof"`
		ExceedLimit SimpleStatistic `json:"exceed_limit"`
	} `json:"pread"`
	Rexi struct {
		Buffered SimpleStatistic `json:"buffered"`
		Down     SimpleStatistic `json:"down"`
		Dropped  SimpleStatistic `json:"dropped"`
		Streams  struct {
			Timeout struct {
				InitStream SimpleStatistic `json:"init_stream"`
				Stream     SimpleStatistic `json:"stream"`
				WaitForAck SimpleStatistic `json:"wait_for_ack"`
			} `json:"timeout"`
		} `json:"streams"`
	} `json:"rexi"`
}

Statistics2 represents all of the statistics available from the CouchDB version 2 server. This is the format returned when all statistics are being accessed.

type Task

type Task struct {
	ChangesDone  int64  `json:"changes_done"`
	Database     string `json:"database"`
	PID          string `json:"pid"`
	Progress     int64  `json:"progress"`
	StartedOn    int64  `json:"started_on"`
	TotalChanges int64  `json:"total_changes"`
	Type         string `json:"type"`
	UpdatedOn    int64  `json:"updated_on"`
}

Task structs contain information about a single task on the server. Examples of tasks represented include database compaction & indexing.

type TemporaryView

type TemporaryView struct {
	Map    string `json:"map,omitempty"`
	Reduce string `json:"reduce,omitempty"`
	// contains filtered or unexported fields
}

TemporaryView is a type of view which can be created & accessed on the fly. Temporary views are good for debugging purposed but should never be used in production as they are slow for any large number of documents.

func (TemporaryView) Execute

func (v TemporaryView) Execute(params ViewParams) (DocumentList, error)

Execute implements View for TemporaryView.

type URLOptions

type URLOptions struct {
	url.Values
}

URLOptions is a slightly modified version of url.Values, the only difference being that values are automatically encoded as JSON when they are added to the URLOptions map as this is the format CouchDB will expect them in. This means that the URLOptions.Add and URLOptions.Set methods can return an error in the case that the passed value cannot be encoded as JSON.

func NewURLOptions

func NewURLOptions() URLOptions

NewURLOptions creates a new URLOptions struct to hold HTTP query options passed to the CouchDB server.

func (*URLOptions) Add

func (opts *URLOptions) Add(name string, val interface{}) error

Add adds the JSON-encoded version of val to the list of values stored for name.

func (*URLOptions) Set

func (opts *URLOptions) Set(name string, val interface{}) error

Set overwrites the currently-stored value for name with the JSON-encoded version of val.

type UserDocument

type UserDocument struct {
	DocumentMetadata

	Name    string   `json:"name"`
	Roles   []string `json:"roles"`
	TheType string   `json:"type"`

	// This field is never sent back from CouchDB (for obvious reasons)
	Password string `json:"password,omitempty"`

	// These fields are generated by CouchDB from the password provided on creation
	DerivedKey     string `json:"derived_key,omitempty"`
	Iterations     int    `json:"iterations,omitempty"`
	PasswordScheme string `json:"password_scheme,omitempty"`
	Salt           string `json:"salt,omitempty"`
}

UserDocument contains all of the fields used by CouchDB to represent a user on the server.

type View

type View interface {
	Execute(Options) (DocumentList, error)
}

View is an interface representing the way that views are executed and their results returned.

type ViewParams

type ViewParams struct {
	Conflicts              BooleanParameter        `url:"conflicts,omitempty"`
	Descending             BooleanParameter        `url:"descending,omitempty"`
	EndKey                 *InterfaceParameter     `url:"endkey,omitempty"`
	EndKeyDocID            string                  `url:"endkey_docid,omitempty"`
	Group                  BooleanParameter        `url:"group,omitempty"`
	GroupLevel             float64                 `url:"group_level,omitempty"`
	IncludeDocs            BooleanParameter        `url:"include_docs,omitempty"`
	Attachments            BooleanParameter        `url:"attachments,omitempty"`
	AttachmentEncodingInfo BooleanParameter        `url:"att_encoding_info,omitempty"`
	InclusiveEnd           BooleanParameter        `url:"inclusive_end,omitempty"`
	Key                    *InterfaceParameter     `url:"key,omitempty"`
	Keys                   *InterfaceListParameter `url:"keys,omitempty"`
	Limit                  float64                 `url:"limit,omitempty"`
	Reduce                 BooleanParameter        `url:"reduce,omitempty"`
	Skip                   float64                 `url:"skip,omitempty"`
	Sorted                 BooleanParameter        `url:"sorted,omitempty"`
	Stale                  string                  `url:"stale,omitempty"`
	StartKey               *InterfaceParameter     `url:"startkey,omitempty"`
	StartKeyDocID          string                  `url:"startkey_docid,omitempty"`
	UpdateSeq              BooleanParameter        `url:"update_seq,omitempty"`
}

ViewParams provides a type-safe implementation of the paramaters which may be passed to an execution of a CouchDB view function:

  • conflicts (boolean) – Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false
  • descending (boolean) – Return the documents in descending by key order. Default is false
  • endkey (json) – Stop returning records when the specified key is reached. Optional
  • end_key (json) – Alias for endkey param
  • endkey_docid (string) – Stop returning records when the specified document ID is reached. Requires endkey to be specified for this to have any effect. Optional
  • end_key_doc_id (string) – Alias for endkey_docid param
  • group (boolean) – Group the results using the reduce function to a group or single row. Default is false
  • group_level (number) – Specify the group level to be used. Optional
  • include_docs (boolean) – Include the associated document with each row. Default is false.
  • attachments (boolean) – Include the Base64-encoded content of attachments in the documents that are included if include_docs is true. Ignored if include_docs isn’t true. Default is false.
  • att_encoding_info (boolean) – Include encoding information in attachment stubs if include_docs is true and the particular attachment is compressed. Ignored if include_docs isn’t true. Default is false.
  • inclusive_end (boolean) – Specifies whether the specified end key should be included in the result. Default is true
  • key (json) – Return only documents that match the specified key. Optional
  • keys (json-array) – Return only documents where the key matches one of the keys specified in the array. Optional
  • limit (number) – Limit the number of the returned documents to the specified number. Optional
  • reduce (boolean) – Use the reduction function. Default is true
  • skip (number) – Skip this number of records before starting to return the results. Default is 0
  • sorted (boolean) – Sort returned rows (see Sorting Returned Rows). Setting this to false offers a performance boost. The total_rows and offset fields are not available when this is set to false. Default is true
  • stale (string) – Allow the results from a stale view to be used. Supported values: ok and update_after. Optional
  • startkey (json) – Return records starting with the specified key. Optional
  • start_key (json) – Alias for startkey param
  • startkey_docid (string) – Return records starting with the specified document ID. Requires startkey to be specified for this to have any effect. Optional
  • start_key_doc_id (string) – Alias for startkey_docid param
  • update_seq (boolean) – Response includes an update_seq value indicating which sequence id of the database the view reflects. Default is false

func (ViewParams) Values added in v0.3.1

func (v ViewParams) Values() (url.Values, error)

Values converts a ViewParams to a url.Values while handling any values which need to be converted before being passed along to CouchDB.

Jump to

Keyboard shortcuts

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