couchdb

package
v0.0.0-...-a1c9142 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2020 License: BSD-3-Clause Imports: 15 Imported by: 0

Documentation

Overview

Package couchdb provides a very powerful as well as convenient client for the CouchDB database.

A connection to the database or at least a server can be established by calling

cdb, err := db.Open(cfg)

The supported operations are the listing, creation, and deleting of databases, the listing of all design documents and data documents, the creation, reading, updating, and deleting of documents, searches, and views.

Index

Constants

View Source
const (
	ErrStartupActionFailed = "ESTARTUP"
	ErrInvalidVersion      = "EINVVSN"
	ErrInvalidDocument     = "EINVDOC"
	ErrNoIdentifier        = "ENOID"
	ErrNotFound            = "ENOTFOUND"
	ErrEncoding            = "EENCODING"
	ErrDecoding            = "EDECODING"
	ErrPreparingRequest    = "EPREPARE"
	ErrPerformingRequest   = "EPERFORM"
	ErrClientRequest       = "EREQ"
	ErrReadingResponseBody = "ERESP"
	ErrUserNotFound        = "ENOUSR"
	ErrUserExists          = "EUSREXIST"
)

Error codes.

View Source
const (
	SinceNow = "now"

	StyleMainOnly = "main_only"
	StyleAllDocs  = "all_docs"
)

Fixed values for some of the view parameters.

View Source
const (
	StatusOK       = http.StatusOK
	StatusCreated  = http.StatusCreated
	StatusAccepted = http.StatusAccepted

	StatusFound = http.StatusFound

	StatusBadRequest         = http.StatusBadRequest
	StatusUnauthorized       = http.StatusUnauthorized
	StatusForbidden          = http.StatusForbidden
	StatusNotFound           = http.StatusNotFound
	StatusMethodNotAllowed   = http.StatusMethodNotAllowed
	StatusNotAcceptable      = http.StatusNotAcceptable
	StatusConflict           = http.StatusConflict
	StatusPreconditionFailed = http.StatusPreconditionFailed
	StatusTooManyRequests    = http.StatusTooManyRequests

	StatusInternalServerError = http.StatusInternalServerError
)

Status codes after database requests.

View Source
const DatabaseVersionID = "database-version"

DatabaseVersionID is used for the database version document.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChangeProcessor

type ChangeProcessor func(id, sequence string, deleted bool, revisions []string, document *Unmarshable) error

ChangeProcessor is a function processing the content of a changed document.

type Changes

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

Changes provides access to the responded changes.

func (*Changes) LastSequence

func (c *Changes) LastSequence() string

LastSequence returns the sequence ID of the last change.

func (*Changes) Len

func (c *Changes) Len() int

Len returns the number of changes.

func (*Changes) Pending

func (c *Changes) Pending() int

Pending returns the number of pending changes if the query has been limited.

func (*Changes) Process

func (c *Changes) Process(process ChangeProcessor) error

Process iterates over the found changes and processes them.

type Database

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

Database provides the access to a database.

func Open

func Open(options ...Option) (*Database, error)

Open returns a configured connection to a CouchDB server. Permanent parameters, e.g. for authentication, are possible.

func (*Database) AllDocumentIDs

func (db *Database) AllDocumentIDs(params ...Parameter) ([]string, error)

AllDocumentIDs returns a list of all document IDs of the configured database.

func (*Database) BulkWriteDocuments

func (db *Database) BulkWriteDocuments(docs []interface{}, params ...Parameter) (Statuses, error)

BulkWriteDocuments allows to create or update many documents en bloc.

func (*Database) Changes

func (db *Database) Changes(params ...Parameter) (*Changes, error)

Changes returns access to the changes of the configured database.

func (*Database) CreateDocument

func (db *Database) CreateDocument(doc interface{}, params ...Parameter) *ResultSet

CreateDocument creates a new document.

func (*Database) DeleteDocument

func (db *Database) DeleteDocument(doc interface{}, params ...Parameter) *ResultSet

DeleteDocument deletes a existing document.

func (*Database) DeleteDocumentByID

func (db *Database) DeleteDocumentByID(id, revision string, params ...Parameter) *ResultSet

DeleteDocumentByID deletes an existing document simply by its identifier and revision.

func (*Database) Designs

func (db *Database) Designs() *Designs

Designs returns the design document manager.

func (*Database) Find

func (db *Database) Find(search *Search, params ...Parameter) (*Find, error)

Find runs a selection and returns access to the found results.

func (*Database) HasDocument

func (db *Database) HasDocument(id string, params ...Parameter) (bool, error)

HasDocument checks if the document with the ID exists.

func (*Database) Manager

func (db *Database) Manager() *Manager

Manager returns the database system manager.

func (*Database) Name

func (db *Database) Name() string

Name returns the name of the configured database.

func (*Database) ReadDocument

func (db *Database) ReadDocument(id string, params ...Parameter) *ResultSet

ReadDocument reads the a document by ID.

func (*Database) Request

func (db *Database) Request() *Request

Request returns a raw database request for this database. Can be used for not covered low-level commands.

func (*Database) StartSession

func (db *Database) StartSession(name, password string) (*Session, error)

StartSession starts a cookie based session for the given user.

func (*Database) UpdateDocument

func (db *Database) UpdateDocument(doc interface{}, params ...Parameter) *ResultSet

UpdateDocument update a document if exists.

func (*Database) View

func (db *Database) View(designID, viewID string, params ...Parameter) (*View, error)

View returns access to a view of the configured database.

type DatabaseVersion

type DatabaseVersion struct {
	ID       string `json:"_id"`
	Revision string `json:"_rev,omitempty"`
	Version  string `json:"version"`
}

DatabaseVersion stores the current database version with the document ID "database-version".

type Design

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

Design provides convenient access to one design document.

func (*Design) Delete

func (d *Design) Delete(params ...Parameter) *ResultSet

Delete removes a design document.

func (*Design) ID

func (d *Design) ID() string

ID returns the ID of the design.

func (*Design) Language

func (d *Design) Language() string

Language returns the language for views and shows.

func (*Design) SetLanguage

func (d *Design) SetLanguage(language string)

SetLanguage sets the language for views and shows.

func (*Design) SetShow

func (d *Design) SetShow(id, showf string)

SetShow sets the show function with the ID.

func (*Design) SetView

func (d *Design) SetView(id, mapf, reducef string)

SetView sets the map and the reduce functions of the view with the ID.

func (*Design) Show

func (d *Design) Show(id string) (string, bool)

Show returns the show function with the ID, otherwise false.

func (*Design) View

func (d *Design) View(id string) (string, string, bool)

View returns the map and the reduce functions of the view with the ID, otherwise false.

func (*Design) Write

func (d *Design) Write(params ...Parameter) *ResultSet

Write creates a new design document or updates an existing one.

type Designs

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

Designs manages access to all design documents.

func (*Designs) Design

func (ds *Designs) Design(id string) (*Design, error)

Design returns one design document by identifier.

func (*Designs) IDs

func (ds *Designs) IDs() ([]string, error)

IDs returns the identifiers of all design documents.

type Find

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

Find allows to find and process documents by a given selector.

func (*Find) Len

func (f *Find) Len() int

Len returns the number of found documents.

func (*Find) Process

func (f *Find) Process(process FindProcessor) error

Process iterates over the found documents and processes them.

type FindProcessor

type FindProcessor func(document *Unmarshable) error

FindProcessor is a function processing the content of a found document.

type Index

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

Index allows to generate an index for faster find operations.

func NewIndex

func NewIndex(name string, fields ...string) *Index

NewIndex creates an index.

func (*Index) Limit

func (idx *Index) Limit(limit int) *Index

Limit sets the maximum number of index documents.

func (*Index) MarshalJSON

func (idx *Index) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Index) Selector

func (idx *Index) Selector(selector string) *Index

Selector adds a selector to the index.

func (*Index) Skip

func (idx *Index) Skip(skip int) *Index

Skip sets a number of documents to skip.

func (*Index) Sort

func (idx *Index) Sort(fieldsOrDirs ...string) *Index

Sort sets the sorting of the index by alternates of field names and directions like "asc" or "desc". For examle ("name", "asc", "age", "desc").

type KeyValue

type KeyValue struct {
	Key   string
	Value string
}

KeyValue is used for generic query and header parameters.

type Manager

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

Manager bundles the methods to manage the database system opposite to handle documents.

func (*Manager) AllDatabaseIDs

func (m *Manager) AllDatabaseIDs() ([]string, error)

AllDatabaseIDs returns a list of all database IDs of the connected server.

func (*Manager) CreateDatabase

func (m *Manager) CreateDatabase(params ...Parameter) *ResultSet

CreateDatabase creates the configured database.

func (*Manager) CreateIndex

func (m *Manager) CreateIndex(index *Index, params ...Parameter) *ResultSet

CreateIndex creates a new index for finds.

func (*Manager) CreateUser

func (m *Manager) CreateUser(user *User, params ...Parameter) error

CreateUser adds a new user to the system.

func (*Manager) DatabaseVersion

func (m *Manager) DatabaseVersion() (version.Version, error)

DatabaseVersion returns the version number of the database.

func (*Manager) DeleteAdministrator

func (m *Manager) DeleteAdministrator(nodename, name string, params ...Parameter) error

DeleteAdministrator deletes an administrator from the given database.

func (*Manager) DeleteDatabase

func (m *Manager) DeleteDatabase(params ...Parameter) *ResultSet

DeleteDatabase removes the configured database.

func (*Manager) DeleteNamedDatabase

func (m *Manager) DeleteNamedDatabase(name string, params ...Parameter) *ResultSet

DeleteNamedDatabase removes the given database.

func (*Manager) DeleteUser

func (m *Manager) DeleteUser(name string, params ...Parameter) error

DeleteUser deletes a user from the system.

func (*Manager) HasAdministrator

func (m *Manager) HasAdministrator(nodename, name string, params ...Parameter) (bool, error)

HasAdministrator checks if a given administrator account exists.

func (*Manager) HasDatabase

func (m *Manager) HasDatabase() (bool, error)

HasDatabase checks if the configured database exists.

func (*Manager) Init

func (m *Manager) Init(steps ...Step) error

Init checks and creates the database if needed and performs the individual steps.

func (*Manager) ReadSecurity

func (m *Manager) ReadSecurity(params ...Parameter) (*Security, error)

ReadSecurity returns the security for the given database.

func (*Manager) ReadUser

func (m *Manager) ReadUser(name string, params ...Parameter) (*User, error)

ReadUser reads an existing user from the system.

func (*Manager) UpdateUser

func (m *Manager) UpdateUser(user *User, params ...Parameter) error

UpdateUser updates a user in the system.

func (*Manager) Version

func (m *Manager) Version() (version.Version, error)

Version returns the version number of CouchDB.

func (*Manager) WriteAdministrator

func (m *Manager) WriteAdministrator(nodename, name, password string, params ...Parameter) error

WriteAdministrator adds or updates an administrator to the given database.

func (*Manager) WriteSecurity

func (m *Manager) WriteSecurity(security Security, params ...Parameter) error

WriteSecurity writes new or changed security data to the given database.

type NamesRoles

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

NamesRoles contains names and roles for administrators and users.

type Option

type Option func(db *Database) error

Option defines a function setting an option.

func Host

func Host(address string, port int) Option

Host sets the network address and port of the CouchDB.

func Logging

func Logging() Option

Logging activates the logging.

func Name

func Name(name string) Option

Name sets the database name to use.

type Options

type Options struct {
	Host    string
	Logging bool
	Name    string
}

Options is returned when calling Options() on Database to provide information about the database configuration.

type Parameter

type Parameter func(req *Request)

Parameter is a function changing one (or if needed multile) parameter.

func BasicAuthentication

func BasicAuthentication(name, password string) Parameter

BasicAuthentication is intended for basic authentication against the database.

func Descending

func Descending() Parameter

Descending sets the flag for a descending order of changes gathering.

func EndKey

func EndKey(end interface{}) Parameter

EndKey sets the endkey for a view request.

func FilterDocumentIDs

func FilterDocumentIDs(documentIDs ...string) Parameter

FilterDocumentIDs sets a filtering of the changes to the given document identifiers.

func FilterSelector

func FilterSelector(selector json.RawMessage) Parameter

FilterSelector sets the filter to the passed selector expression.

func FilterView

func FilterView(view string) Parameter

FilterView sets the name of a view which map function acts as filter in case it emits at least one record.

func Group

func Group(level int) Parameter

Group sets the flag for grouping including the level for the reduce function.

func Header(kvs ...KeyValue) Parameter

Header is generic for setting request header parameters.

func IncludeDocuments

func IncludeDocuments() Parameter

IncludeDocuments sets the flag for the including of found view documents.

func Keys

func Keys(keys ...interface{}) Parameter

Keys sets a number of keys wanted for a view request.

func Limit

func Limit(limit int) Parameter

Limit sets the maximum number of result rows.

func NoReduce

func NoReduce() Parameter

NoReduce sets the flag for usage of a reduce function to false.

func OneKey

func OneKey(key interface{}) Parameter

OneKey reduces a view result to only one emitted key.

func Query

func Query(kvs ...KeyValue) Parameter

Query is generic for setting request query parameters.

func Revision

func Revision(revision string) Parameter

Revision sets the revision for the access to concrete document revisions.

func Since

func Since(sequence string) Parameter

Since sets the start of the changes gathering, can also be "now".

func Skip

func Skip(skip int) Parameter

Skip sets the number to skip for view requests.

func SkipLimit

func SkipLimit(skip, limit int) Parameter

SkipLimit sets the number to skip and the limit for view requests.

func StartEndKey

func StartEndKey(start, end interface{}) Parameter

StartEndKey sets the startkey and endkey for a view request.

func StartKey

func StartKey(start interface{}) Parameter

StartKey sets the startkey for a view request.

func StringKeys

func StringKeys(keys ...string) Parameter

StringKeys sets a number of keys of type string wanted for a view request.

func Style

func Style(style string) Parameter

Style sets how many revisions are returned. Default is StyleMainOnly only returning the winning document revision. StyleAllDocs will return all revision including possible conflicts.

type Request

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

Request is responsible for an individual request to a CouchDB. It has to be created by the dabase and can be used queued.

cdb.Request().SetPath(...).SetDocument(...).Put()

func (*Request) AddQuery

func (req *Request) AddQuery(key, value string)

AddQuery adds a query parameter to an existing one.

func (*Request) ApplyParameters

func (req *Request) ApplyParameters(params ...Parameter) *Request

ApplyParameters applies a list of parameters to the request.

func (*Request) Delete

func (req *Request) Delete() *ResultSet

Delete performs a DELETE request.

func (*Request) Get

func (req *Request) Get() *ResultSet

Get performs a GET request.

func (*Request) GetOrPost

func (req *Request) GetOrPost() *ResultSet

GetOrPost decides based on the document if it will perform a GET request or a POST request. The document can be set directly or by one of the parameters. Several of the CouchDB commands work this way.

func (*Request) Head

func (req *Request) Head() *ResultSet

Head performs a HEAD request.

func (*Request) Post

func (req *Request) Post() *ResultSet

Post performs a POST request.

func (*Request) Put

func (req *Request) Put() *ResultSet

Put performs a PUT request.

func (*Request) SetDocument

func (req *Request) SetDocument(doc interface{}) *Request

SetDocument sets the document of the request.

func (*Request) SetHeader

func (req *Request) SetHeader(key, value string)

SetHeader sets a header parameter.

func (*Request) SetPath

func (req *Request) SetPath(parts ...string) *Request

SetPath sets the absolute path of the request.

func (*Request) SetQuery

func (req *Request) SetQuery(key, value string)

SetQuery sets a query parameter.

func (*Request) UpdateDocument

func (req *Request) UpdateDocument(update func(interface{}) interface{})

UpdateDocument allows to modify or exchange the request document.

type ResultSet

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

ResultSet contains the server result set.

func (*ResultSet) Document

func (rs *ResultSet) Document(value interface{}) error

Document returns the received document of a client request and unmorshals it.

func (*ResultSet) Error

func (rs *ResultSet) Error() error

Error returns a possible error of a request.

func (*ResultSet) Header

func (rs *ResultSet) Header(key string) string

Header provides access to header variables.

func (*ResultSet) ID

func (rs *ResultSet) ID() string

ID returns a potentially returned document identifier.

func (*ResultSet) IsDeleted

func (rs *ResultSet) IsDeleted() bool

IsDeleted returns true if a returned document is already deleted.

func (*ResultSet) IsOK

func (rs *ResultSet) IsOK() bool

IsOK checks the status code if the result is okay.

func (*ResultSet) Raw

func (rs *ResultSet) Raw() ([]byte, error)

Raw returns the received raw data of a client request.

func (*ResultSet) Revision

func (rs *ResultSet) Revision() string

Revision returns a potentially returned document revision.

func (*ResultSet) StatusCode

func (rs *ResultSet) StatusCode() int

StatusCode returns the status code of the request.

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

Search allows to formulate what documents shall be selected and the additional parameters.

func NewSearch

func NewSearch(selector string) *Search

NewSearch creates a query for the search of documents.

func (*Search) Bookmark

func (s *Search) Bookmark(bookmark string) *Search

Bookmark enables to specify which page of results is required. Every search returns an opaque string under the bookmark key that can be passed this way. Only works for indexes of type "text".

func (*Search) Fields

func (s *Search) Fields(fields ...string) *Search

Fields sets the fields to return.

func (*Search) Limit

func (s *Search) Limit(limit int) *Search

Limit sets the maximum number of results returned.

func (*Search) MarshalJSON

func (s *Search) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Search) ReadQuorum

func (s *Search) ReadQuorum(quorum int) *Search

ReadQuorum sets the needed read quorum for the result. The default is 1, so that the document found un the index is returned. Higher quorums forces to read from more replicas. This case needs more time.

func (*Search) Skip

func (s *Search) Skip(skip int) *Search

Skip sets a number of results to skip.

func (*Search) Sort

func (s *Search) Sort(fieldsOrDirs ...string) *Search

Sort sets the sorting of the result by alternates of field names and directions like "asc" or "desc". For examle ("name", "asc", "age", "desc").

func (*Search) Stable

func (s *Search) Stable(stable bool) *Search

Stable sets whether to view results from a "stable" set of shards.

func (*Search) Update

func (s *Search) Update(update bool) *Search

Update sets whether to update the index prior to returning the result. Default is true.

func (*Search) UseIndex

func (s *Search) UseIndex(designDocument, name string) *Search

UseIndex instructs the search to use a specific index. Name is allowed be empty.

type Security

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

Security contains administrators and members for one database.

type Session

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

Session contains the information of a CouchDB session.

func (*Session) Cookie

func (s *Session) Cookie() Parameter

Cookie returns the session cookie as parameter to be used in the individual database requests.

func (*Session) Name

func (s *Session) Name() string

Name returns the users name of this session.

func (*Session) Stop

func (s *Session) Stop() error

Stop ends the session.

func (*Session) String

func (s *Session) String() string

String returns a string representation of the session.

type Status

type Status struct {
	OK       bool   `json:"ok"`
	ID       string `json:"id"`
	Revision string `json:"rev"`
	Error    string `json:"error"`
	Reason   string `json:"reason"`
}

Status contains internal status information CouchDB returns.

type Statuses

type Statuses []Status

Statuses is the list of status information after a bulk writing.

type Step

type Step func() (version.Version, StepAction)

Step returns the version after a startup step and the action that shall be performed on the database. The returned action will only be performed, if the current if the new version is than the current version.

type StepAction

type StepAction func(db *Database) error

StepAction is the concrete action of a step.

type Steps

type Steps []Step

Steps is just an ordered number of steps.

type Unmarshable

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

Unmarshable describes a not yet unmarshalled value that can be unmarshalled into a given variable. It is used to access key, value, or document of view result rows.

func NewUnmarshableJSON

func NewUnmarshableJSON(msg json.RawMessage) *Unmarshable

NewUnmarshableJSON creates a new Unmarshable out of a json.RawMessage

func NewUnmarshableRaw

func NewUnmarshableRaw(raw []byte) *Unmarshable

NewUnmarshableRaw creates a new Unmarshable out of the raw bytes.

func (*Unmarshable) Raw

func (u *Unmarshable) Raw() []byte

Raw returns the unmarshable as raw byte slice.

func (*Unmarshable) String

func (u *Unmarshable) String() string

String returns the unmarshable as string.

func (*Unmarshable) Unmarshal

func (u *Unmarshable) Unmarshal(doc interface{}) error

Unmarshal unmarshals the interface into the passed variable.

type User

type User struct {
	DocumentID       string `json:"_id,omitempty"`
	DocumentRevision string `json:"_rev,omitempty"`

	Name     string   `json:"name"`
	Password string   `json:"password"`
	Type     string   `json:"type,omitempty"`
	Roles    []string `json:"roles,omitempty"`
}

User contains name and password for user management and authentication.

type View

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

View provides access to the responded views.

func (*View) Offset

func (v *View) Offset() int

Offset returns the starting offset of the view rows.

func (*View) Process

func (v *View) Process(process ViewProcessor) error

Process iterates over the found view documents and processes them.

func (*View) ReturnedRows

func (v *View) ReturnedRows() int

ReturnedRows returns the nnumber of returned view rows.

func (*View) TotalRows

func (v *View) TotalRows() int

TotalRows returns the number of view rows.

type ViewProcessor

type ViewProcessor func(id string, key, value, document *Unmarshable) error

ViewProcessor is a function processing the content of a view row.

Jump to

Keyboard shortcuts

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