couchdb

package module
v1.2.9 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2023 License: BSD-3-Clause Imports: 21 Imported by: 0

README

CouchDB-Golang

Build Status GoDoc GitHub license

A Golang library for CouchDB 2.x, inspired by CouchDB-Python.

Features

  • Resource : a simple wrapper for HTTP requests and error handling
  • Server : CouchDB server instance
  • Database : CouchDB database instance
  • ViewResults : a representation of the results produced by design document views
  • ViewDefinition : a definition of view stored in a specific design document
  • Document : a representation of document object in database
  • tools/replicate : a command-line tool for replicating
func (d *Database) Query(fields []string, selector string, sorts []string, limit, skip, index interface{}) ([]map[string]interface{}, error)

You can query documents using a conditional selector statement in Golang. It will converts to the corresponding JSON query string.

  • selector: A filter string declaring which documents to return, formatted as a Golang statement.
  • fields: Specifying which fields to be returned, if passing nil the entire is returned, no automatic inclusion of _id or other metadata fields.
  • sorts: How to order the documents returned, formatted as ["desc(fieldName1)", "desc(fieldName2)"] or ["fieldNameA", "fieldNameB"] of which "asc" is used by default, passing nil to disable ordering.
  • limit: Maximum number of results returned, passing nil to use default value(25).
  • skip: Skip the first 'n' results, where 'n' is the number specified, passing nil for no-skip.
  • index: Instruct a query to use a specific index, specified either as "<design_document>" or ["<design_document>", "<index_name>"], passing nil to use primary index(_all_docs) by default.

For example:

docsQuery, err := movieDB.Query(nil, `year == 1989 && (director == "Ademir Kenovic" || director == "Dezs Garas")`, nil, nil, nil, nil)

equals to:

docsRaw, err := movieDB.QueryJSON(`
{
  "selector": {
    "year": 1989,
    "$or": [
      { "director": "Ademir Kenovic" },
      { "director": "Dezs Garas" }
    ]
  }
}`)
Inner functions for selector syntax
  • nor(condexprs...) matches if none of the conditions in condexprs match($nor). For example: nor(year == 1990, year == 1989, year == 1997) returns all documents whose year field not in 1989, 1990 and 1997.

  • all(field, array) matches an array value if it contains all the elements of the argument array($all). For example: all(genre, []string{"Comedy", "Short"} returns all documents whose genre field contains "Comedy" and "Short".

  • any(field, condexpr) matches an array field with at least one element meets the specified condition($elemMatch). For example: any(genre, genre == "Short" || genre == "Horror") returns all documents whose genre field contains "Short" or "Horror" or both.

  • exists(field, boolean) checks whether the field exists or not, regardless of its value($exists). For example: exists(director, false) returns all documents who does not have a director field.

  • typeof(field, type) checks the document field's type, valid types are "null", "boolean", "number", "string", "array", "object"($type). For example: typeof(genre, "array") returns all documents whose genre field is of array type.

  • in(field, array) the field must exist in the array provided($in). For example: in(director, []string{"Mike Portnoy", "Vitali Kanevsky"}) returns all documents whose director field is "Mike Portnoy" or "Vitali Kanevsky".

  • nin(field, array) the document field must not exist in the array provided($nin). For example: nin(year, []int{1990, 1992, 1998}) returns all documents whose year field is not in 1990, 1992 or 1998.

  • size(field, int) matches the length of an array field in a document($size). For example: size(genre, 2) returns all documents whose genre field is of length 2.

  • mod(field, divisor, remainder) matches documents where field % divisor == remainder($mod). For example: mod(year, 2, 1) returns all documents whose year field is an odd number.

  • regex(field, regexstr) a regular expression pattern to match against the document field. For example: regex(title, "^A") returns all documents whose title is begin with an "A".

Inner functions for sort syntax

asc(field) sorts the field in ascending order, this is the default option while desc(field) sorts the field in descending order.

Requirements

  • Golang 1.7.x and above

Installation

go get -u -v github.com/leesper/couchdb-golang

Authors and acknowledgment

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update unit tests as appropriate.

Documentation

Overview

Package couchdb provides components to work with CouchDB 2.x with Go.

Resource is the low-level wrapper functions of HTTP methods used for communicating with CouchDB Server.

Server contains all the functions to work with CouchDB server, including some basic functions to facilitate the basic user management provided by it.

Database contains all the functions to work with CouchDB database, such as documents manipulating and querying.

ViewResults represents the results produced by design document views. When calling any of its functions like Offset(), TotalRows(), UpdateSeq() or Rows(), it will perform a query on views on server side, and returns results as slice of Row

ViewDefinition is a definition of view stored in a specific design document, you can define your own map-reduce functions and Sync with the database.

Document represents a document object in database. All struct that can be mapped into CouchDB document must have it embedded. For example:

type User struct {
  Name string `json:"name"`
  Age int `json:"age"`
  Document
}
user := User{"Mike", 18}
anotherUser := User{}

Then you can call Store(db, &user) to store it into CouchDB or Load(db, user.GetID(), &anotherUser) to get the data from database.

ViewField represents a view definition value bound to Document.

tools/replicate is a command-line tool for replicating databases from one CouchDB server to another. This is mainly for backup purposes, but you can also use -continuous option to set up automatic replication.

Index

Constants

View Source
const (
	// DefaultBaseURL is the default address of CouchDB server.
	DefaultBaseURL = "http://localhost:5984"
)

Variables

View Source
var (
	// ErrBatchValue for invalid batch parameter of IterView
	ErrBatchValue = errors.New("batch must be 1 or more")
	// ErrLimitValue for invalid limit parameter of IterView
	ErrLimitValue = errors.New("limit must be 1 or more")
)
View Source
var (
	// ErrSetID for setting ID to document which already has one.
	ErrSetID = errors.New("id can only be set on new documents")
	// ErrNotStruct for not a struct value
	ErrNotStruct = errors.New("value not of struct type")
	// ErrNotDocumentEmbedded for not a document-embedded value
	ErrNotDocumentEmbedded = errors.New("value not Document-embedded")
)
View Source
var (

	// ErrNotModified for HTTP status code 304
	ErrNotModified = errors.New("status 304 - not modified")
	// ErrBadRequest for HTTP status code 400
	ErrBadRequest = errors.New("status 400 - bad request")
	// ErrUnauthorized for HTTP status code 401
	ErrUnauthorized = errors.New("status 401 - unauthorized")
	// ErrForbidden for HTTP status code 403
	ErrForbidden = errors.New("status 403 - forbidden")
	// ErrNotFound for HTTP status code 404
	ErrNotFound = errors.New("status 404 - not found")
	// ErrResourceNotAllowed for HTTP status code 405
	ErrResourceNotAllowed = errors.New("status 405 - resource not allowed")
	// ErrNotAcceptable for HTTP status code 406
	ErrNotAcceptable = errors.New("status 406 - not acceptable")
	// ErrConflict for HTTP status code 409
	ErrConflict = errors.New("status 409 - conflict")
	// ErrPreconditionFailed for HTTP status code 412
	ErrPreconditionFailed = errors.New("status 412 - precondition failed")
	// ErrBadContentType for HTTP status code 415
	ErrBadContentType = errors.New("status 415 - bad content type")
	// ErrRequestRangeNotSatisfiable for HTTP status code 416
	ErrRequestRangeNotSatisfiable = errors.New("status 416 - requested range not satisfiable")
	// ErrExpectationFailed for HTTP status code 417
	ErrExpectationFailed = errors.New("status 417 - expectation failed")
	// ErrInternalServerError for HTTP status code 500
	ErrInternalServerError = errors.New("status 500 - internal server error")
)

Functions

func FromJSONCompatibleMap

func FromJSONCompatibleMap(obj interface{}, docMap map[string]interface{}) error

FromJSONCompatibleMap constructs a Document-embedded struct from a JSON-compatible map.

func GenerateUUID

func GenerateUUID() string

GenerateUUID returns a random 128-bit UUID

func Load

func Load(ctx context.Context, db *Database, docID string, obj interface{}) error

Load loads the document in specified database.

func Store

func Store(ctx context.Context, db *Database, obj interface{}) error

Store stores the document in specified database. obj: a Document-embedded struct value, its id and rev will be updated after stored, so caller must pass a pointer value.

func ToJSONCompatibleMap

func ToJSONCompatibleMap(obj interface{}) (map[string]interface{}, error)

ToJSONCompatibleMap converts a Document-embedded struct into a JSON-compatible map, e.g. anything that cannot be jsonified will be ignored silently.

Types

type Database

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

Database represents a CouchDB database instance.

func NewDatabase

func NewDatabase(urlStr string) (*Database, error)

NewDatabase returns a CouchDB database instance.

func NewDatabaseWithResource

func NewDatabaseWithResource(res *Resource) (*Database, error)

NewDatabaseWithResource returns a CouchDB database instance with resource obj.

func (*Database) Available

func (d *Database) Available(ctx context.Context) error

Available returns error if the database is not good to go.

func (*Database) Changes

func (d *Database) Changes(ctx context.Context, options url.Values) (map[string]interface{}, error)

Changes returns a sorted list of changes feed made to documents in the database.

func (*Database) Cleanup

func (d *Database) Cleanup(ctx context.Context) error

Cleanup removes all view index files no longer required by CouchDB.

func (*Database) Commit

func (d *Database) Commit(ctx context.Context) error

Commit flushes any recent changes to the specified database to disk. If the server is configured to delay commits or previous requests use the special "X-Couch-Full-Commit: false" header to disable immediate commits, this method can be used to ensure that non-commited changes are commited to physical storage.

func (*Database) Compact

func (d *Database) Compact(ctx context.Context) error

Compact compacts the database by compressing the disk database file.

func (*Database) Contains

func (d *Database) Contains(ctx context.Context, docid string) error

Contains returns true if the database contains a document with the specified ID.

func (*Database) Copy

func (d *Database) Copy(ctx context.Context, srcID, destID, destRev string) (string, error)

Copy copies an existing document to a new or existing document.

func (*Database) Delete

func (d *Database) Delete(ctx context.Context, docid string) error

Delete deletes the document with the specified ID.

func (*Database) DeleteAttachment

func (d *Database) DeleteAttachment(ctx context.Context, doc map[string]interface{}, name string) error

DeleteAttachment deletes the specified attachment

func (*Database) DeleteDoc

func (d *Database) DeleteDoc(ctx context.Context, doc map[string]interface{}) error

DeleteDoc deletes the specified document

func (*Database) DeleteIndex

func (d *Database) DeleteIndex(ctx context.Context, ddoc, name string) error

DeleteIndex deletes index in database.

func (*Database) DocIDs

func (d *Database) DocIDs(ctx context.Context) ([]string, error)

DocIDs returns the IDs of all documents in database.

func (*Database) Get

func (d *Database) Get(ctx context.Context, docid string, options url.Values) (map[string]interface{}, error)

Get returns the document with the specified ID.

func (*Database) GetAttachment

func (d *Database) GetAttachment(ctx context.Context, doc map[string]interface{}, name string) ([]byte, error)

GetAttachment returns the file attachment associated with the document. The raw data is returned as a []byte.

func (*Database) GetAttachmentID

func (d *Database) GetAttachmentID(ctx context.Context, docid, name string) ([]byte, error)

GetAttachmentID returns the file attachment associated with the document ID. The raw data is returned as []byte.

func (*Database) GetIndex

func (d *Database) GetIndex(ctx context.Context) (map[string]*json.RawMessage, error)

GetIndex gets all indexes created in database.

func (*Database) GetRevsLimit

func (d *Database) GetRevsLimit(ctx context.Context) (int, error)

GetRevsLimit gets the current revs_limit(revision limit) setting.

func (*Database) GetSecurity

func (d *Database) GetSecurity(ctx context.Context) (map[string]interface{}, error)

GetSecurity returns the current security object from the given database.

func (*Database) Info

func (d *Database) Info(ctx context.Context, ddoc string) (map[string]interface{}, error)

Info returns the information about the database or design document

func (*Database) IterView

func (d *Database) IterView(ctx context.Context, name string, batch int, wrapper func(Row) Row, opts map[string]interface{}) (<-chan IterViewResult, error)

IterView returns a channel fetching rows in batches which iterates a row at a time(pagination).

name: the name of the view, for user-defined views use the format "design_docid/viewname", that is, the document ID of the design document and the name of the view, separated by a /.

wrapper: an optional function for processing the result rows after retrieved.

options: optional query parameters.

func (*Database) Len

func (d *Database) Len(ctx context.Context) (int, error)

Len returns the number of documents stored in it.

func (*Database) List

func (d *Database) List(ctx context.Context, name, view string, options map[string]interface{}) (http.Header, []byte, error)

List formats a view using a server-side 'list' function.

name: the name of the list function in the format "designdoc/listname"

view: the name of the view in the format "designdoc/viewname"

options: optional query parameters

func (*Database) Name

func (d *Database) Name(ctx context.Context) (string, error)

Name returns the name of database.

func (*Database) Purge

func (d *Database) Purge(ctx context.Context, docs []map[string]interface{}) (map[string]interface{}, error)

Purge performs complete removing of the given documents.

func (*Database) PutAttachment

func (d *Database) PutAttachment(ctx context.Context, doc map[string]interface{}, content []byte, name, mimeType string) error

PutAttachment uploads the supplied []byte as an attachment to the specified document. doc: the document that the attachment belongs to. Must have _id and _rev inside. content: the data to be attached to doc. name: name of attachment. mimeType: MIME type of content.

func (*Database) PutIndex

func (d *Database) PutIndex(ctx context.Context, indexFields []string, ddoc, name string) (string, string, error)

PutIndex creates a new index in database.

indexFields: a JSON array of field names following the sort syntax.

ddoc: optional, name of the design document in which the index will be created. By default each index will be created in its own design document. Indexes can be grouped into design documents for efficiency. However a change to one index in a design document will invalidate all other indexes in the same document.

name: optional, name of the index. A name generated automatically if not provided.

func (*Database) Query

func (d *Database) Query(ctx context.Context, fields []string, selector string, sorts []string, limit, skip, index interface{}) ([]map[string]interface{}, error)

Query returns documents using a conditional selector statement in Golang.

selector: A filter string declaring which documents to return, formatted as a Golang statement.

fields: Specifying which fields to be returned, if passing nil the entire is returned, no automatic inclusion of _id or other metadata fields.

sorts: How to order the documents returned, formatted as ["desc(fieldName1)", "desc(fieldName2)"] or ["fieldNameA", "fieldNameB"] of which "asc" is used by default, passing nil to disable ordering.

limit: Maximum number of results returned, passing nil to use default value(25).

skip: Skip the first 'n' results, where 'n' is the number specified, passing nil for no-skip.

index: Instruct a query to use a specific index, specified either as "<design_document>" or ["<design_document>", "<index_name>"], passing nil to use primary index(_all_docs) by default.

Inner functions for selector syntax

nor(condexprs...) matches if none of the conditions in condexprs match($nor).

For example: nor(year == 1990, year == 1989, year == 1997) returns all documents whose year field not in 1989, 1990 and 1997.

all(field, array) matches an array value if it contains all the elements of the argument array($all).

For example: all(genre, []string{"Comedy", "Short"} returns all documents whose genre field contains "Comedy" and "Short".

any(field, condexpr) matches an array field with at least one element meets the specified condition($elemMatch).

For example: any(genre, genre == "Short" || genre == "Horror") returns all documents whose genre field contains "Short" or "Horror" or both.

exists(field, boolean) checks whether the field exists or not, regardless of its value($exists).

For example: exists(director, false) returns all documents who does not have a director field.

typeof(field, type) checks the document field's type, valid types are "null", "boolean", "number", "string", "array", "object"($type).

For example: typeof(genre, "array") returns all documents whose genre field is of array type.

in(field, array) the field must exist in the array provided($in).

For example: in(director, []string{"Mike Portnoy", "Vitali Kanevsky"}) returns all documents whose director field is "Mike Portnoy" or "Vitali Kanevsky".

nin(field, array) the document field must not exist in the array provided($nin).

For example: nin(year, []int{1990, 1992, 1998}) returns all documents whose year field is not in 1990, 1992 or 1998.

size(field, int) matches the length of an array field in a document($size).

For example: size(genre, 2) returns all documents whose genre field is of length 2.

mod(field, divisor, remainder) matches documents where field % divisor == remainder($mod).

For example: mod(year, 2, 1) returns all documents whose year field is an odd number.

regex(field, regexstr) a regular expression pattern to match against the document field.

For example: regex(title, "^A") returns all documents whose title is begin with an "A".

Inner functions for sort syntax

asc(field) sorts the field in ascending order, this is the default option while desc(field) sorts the field in descending order.

func (*Database) QueryJSON

func (d *Database) QueryJSON(ctx context.Context, query string) ([]map[string]interface{}, error)

QueryJSON returns documents using a declarative JSON querying syntax.

func (*Database) Revisions

func (d *Database) Revisions(ctx context.Context, docid string, options url.Values) ([]map[string]interface{}, error)

Revisions returns all available revisions of the given document in reverse order, e.g. latest first.

func (*Database) Save

func (d *Database) Save(ctx context.Context, doc map[string]interface{}, options url.Values) (string, string, error)

Save creates a new document or update an existing document. If doc has no _id the server will generate a random UUID and a new document will be created. Otherwise the doc's _id will be used to identify the document to create or update. Trying to update an existing document with an incorrect _rev will cause failure. *NOTE* It is recommended to avoid saving doc without _id and instead generate document ID on client side. To avoid such problems you can generate a UUID on the client side. GenerateUUID provides a simple, platform-independent implementation. You can also use other third-party packages instead. doc: the document to create or update.

func (*Database) Set

func (d *Database) Set(ctx context.Context, docid string, doc map[string]interface{}) error

Set creates or updates a document with the specified ID.

func (*Database) SetRevsLimit

func (d *Database) SetRevsLimit(ctx context.Context, limit int) error

SetRevsLimit sets the maximum number of document revisions that will be tracked by CouchDB.

func (*Database) SetSecurity

func (d *Database) SetSecurity(ctx context.Context, securityDoc map[string]interface{}) error

SetSecurity sets the security object for the given database.

func (*Database) Show

func (d *Database) Show(ctx context.Context, name, docID string, params url.Values) (http.Header, []byte, error)

Show calls a server-side 'show' function.

name: the name of the show function in the format "designdoc/showname"

docID: optional document ID to pass to the show function

params: optional query parameters

func (*Database) String

func (d *Database) String() string

func (*Database) Update

func (d *Database) Update(ctx context.Context, docs []map[string]interface{}, options map[string]interface{}) ([]UpdateResult, error)

Update performs a bulk update or creation of the given documents in a single HTTP request. It returns a 3-tuple (id, rev, error)

func (*Database) UpdateDoc

func (d *Database) UpdateDoc(ctx context.Context, name, docID string, params url.Values) (http.Header, []byte, error)

UpdateDoc calls server-side update handler.

name: the name of the update handler function in the format "designdoc/updatename".

docID: optional document ID to pass to the show function

params: optional query parameters

func (*Database) View

func (d *Database) View(name string, wrapper func(Row) Row, options map[string]interface{}) IViewResults

View executes a predefined design document view and returns the results.

name: the name of the view, for user-defined views use the format "design_docid/viewname", that is, the document ID of the design document and the name of the view, separated by a /.

wrapper: an optional function for processing the result rows after retrieved.

options: optional query parameters.

type DatabaseInfo added in v1.2.2

type DatabaseInfo struct {
	DbName    string `json:"db_name"`
	PurgeSeq  string `json:"purge_seq"`
	UpdateSeq string `json:"update_seq"`
	Sizes     struct {
		File     int `json:"file"`
		External int `json:"external"`
		Active   int `json:"active"`
	} `json:"sizes"`
	Other struct {
		DataSize int `json:"data_size"`
	} `json:"other"`
	DocDelCount       int  `json:"doc_del_count"`
	DocCount          int  `json:"doc_count"`
	DiskSize          int  `json:"disk_size"`
	DiskFormatVersion int  `json:"disk_format_version"`
	DataSize          int  `json:"data_size"`
	CompactRunning    bool `json:"compact_running"`
	Cluster           struct {
		Q int `json:"q"`
		N int `json:"n"`
		W int `json:"w"`
		R int `json:"r"`
	} `json:"cluster"`
	InstanceStartTime string `json:"instance_start_time"`
}

type Document

type Document struct {
	ID  string `json:"_id,omitempty"`  // for json only, call SetID/GetID instead
	Rev string `json:"_rev,omitempty"` // for json only, call GetRev instead
	// contains filtered or unexported fields
}

Document represents a document object in database.

func DocumentWithID

func DocumentWithID(id string) Document

DocumentWithID returns a new Document with ID.

func (*Document) GetID

func (d *Document) GetID() string

GetID returns the document ID.

func (*Document) GetRev

func (d *Document) GetRev() string

GetRev returns the document revision.

func (*Document) SetID

func (d *Document) SetID(id string) error

SetID sets ID for new document or return error.

func (*Document) SetRev

func (d *Document) SetRev(rev string)

SetRev sets revision for document.

type IDatabase added in v1.2.3

type IDatabase interface {
	Save(doc map[string]interface{}, options url.Values) (string, string, error)
	Get(docid string, options url.Values) (map[string]interface{}, error)
	View(name string, wrapper func(Row) Row, options map[string]interface{}) IViewResults
}

type IServer added in v1.2.3

type IServer interface {
	Get(ctx context.Context, name string) (*Database, error)
}

type IViewResults added in v1.2.3

type IViewResults interface {
	Rows(context.Context) ([]Row, error)
	UpdateSeq(context.Context) (int, error)
	TotalRows(context.Context) (int, error)
	Offset(context.Context) (int, error)
}

type IterViewResult added in v1.2.7

type IterViewResult struct {
	Row   Row
	Error error
}

type Resource

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

Resource handles all requests to CouchDB

func NewResource

func NewResource(urlStr string, header http.Header) (*Resource, error)

NewResource returns a newly-created Resource instance

func NewResourceWithClient added in v1.2.4

func NewResourceWithClient(urlStr string, header http.Header, client *http.Client) (*Resource, error)

NewResourceWithClient returns a newly-created Resource instance with a received http client

func (*Resource) Delete

func (r *Resource) Delete(ctx context.Context, path string, header http.Header, params url.Values) (http.Header, []byte, error)

Delete is a wrapper around http.Delete

func (*Resource) DeleteJSON

func (r *Resource) DeleteJSON(ctx context.Context, path string, header http.Header, params url.Values) (http.Header, []byte, error)

DeleteJSON issues a DELETE to the specified URL, with data returned as json

func (*Resource) Get

func (r *Resource) Get(ctx context.Context, path string, header http.Header, params url.Values) (http.Header, []byte, error)

Get is a wrapper around http.Get

func (*Resource) GetJSON

func (r *Resource) GetJSON(ctx context.Context, path string, header http.Header, params url.Values) (http.Header, []byte, error)

GetJSON issues a GET to the specified URL, with data returned as json

func (*Resource) Head

func (r *Resource) Head(ctx context.Context, path string, header http.Header, params url.Values) (http.Header, []byte, error)

Head is a wrapper around http.Head

func (*Resource) NewResourceWithURL

func (r *Resource) NewResourceWithURL(resStr string) (*Resource, error)

NewResourceWithURL returns newly created *Resource combined with resource string.

func (*Resource) Post

func (r *Resource) Post(ctx context.Context, path string, header http.Header, body []byte, params url.Values) (http.Header, []byte, error)

Post is a wrapper around http.Post

func (*Resource) PostJSON

func (r *Resource) PostJSON(ctx context.Context, path string, header http.Header, body map[string]interface{}, params url.Values) (http.Header, []byte, error)

PostJSON issues a POST to the specified URL, with data returned as json

func (*Resource) Put

func (r *Resource) Put(ctx context.Context, path string, header http.Header, body []byte, params url.Values) (http.Header, []byte, error)

Put is a wrapper around http.Put

func (*Resource) PutJSON

func (r *Resource) PutJSON(ctx context.Context, path string, header http.Header, body map[string]interface{}, params url.Values) (http.Header, []byte, error)

PutJSON issues a PUT to the specified URL, with data returned as json

type Row

type Row struct {
	ID  string
	Key interface{}
	Val interface{}
	Doc interface{}
	Err error
}

Row represents a row returned by database views.

func (Row) String

func (r Row) String() string

String returns a string representation for Row

type Server

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

Server represents a CouchDB server instance.

func NewServer

func NewServer(urlStr string) (*Server, error)

NewServer creates a CouchDB server instance in address urlStr.

func NewServerNoFullCommit

func NewServerNoFullCommit(urlStr string) (*Server, error)

NewServerNoFullCommit creates a CouchDB server instance in address urlStr with X-Couch-Full-Commit disabled.

func NewServerWithClient added in v1.2.4

func NewServerWithClient(urlStr string, httpClient *http.Client) (*Server, error)

NewServerWithClient creates a CouchDB server instance in address urlStr and including configuration for prometheus metrics

func (*Server) ActiveTasks

func (s *Server) ActiveTasks(ctx context.Context) ([]interface{}, error)

ActiveTasks lists of running tasks.

func (*Server) AddUser

func (s *Server) AddUser(ctx context.Context, name, password string, roles []string) (string, string, error)

AddUser adds regular user in authentication database. Returns id and rev of the registered user.

func (*Server) Config

func (s *Server) Config(ctx context.Context, node string) (map[string]map[string]string, error)

Config returns the entire CouchDB server configuration as JSON structure.

func (*Server) Contains

func (s *Server) Contains(ctx context.Context, name string) bool

Contains returns true if a db with given name exsited.

func (*Server) Create

func (s *Server) Create(ctx context.Context, name string) (*Database, error)

Create returns a database instance with the given name, returns true if created, if database already existed, returns false, *Database will be nil if failed.

func (*Server) DBs

func (s *Server) DBs(ctx context.Context) ([]string, error)

DBs returns a list of all the databases in the CouchDB server instance.

func (*Server) DBsWithParams added in v1.2.3

func (s *Server) DBsWithParams(ctx context.Context, headers http.Header, params url.Values) ([]string, error)

DBsWithParams returns a list of all the databases in the CouchDB server instance, supporting headers and params

func (*Server) Delete

func (s *Server) Delete(ctx context.Context, name string) error

Delete deletes a database with the given name. Return false if failed.

func (*Server) Get

func (s *Server) Get(ctx context.Context, name string) (*Database, error)

Get gets a database instance with the given name. Return nil if failed.

func (*Server) GetDatabaseInfo added in v1.2.2

func (s *Server) GetDatabaseInfo(ctx context.Context, name string) (*DatabaseInfo, error)

GetDatabaseInfo retrieve information about the database

func (*Server) Len

func (s *Server) Len(ctx context.Context) (int, error)

Len returns the number of dbs in CouchDB server instance.

func (*Server) Login

func (s *Server) Login(ctx context.Context, name, password string) (string, error)

Login regular user in CouchDB, returns authentication token.

func (*Server) Logout

func (s *Server) Logout(ctx context.Context, token string) error

Logout regular user in CouchDB

func (*Server) Membership

func (s *Server) Membership(ctx context.Context) ([]string, []string, error)

Membership displays the nodes that are part of the cluster as clusterNodes. The field allNodes displays all nodes this node knows about, including the ones that are part of cluster.

func (*Server) RemoveUser

func (s *Server) RemoveUser(ctx context.Context, name string) error

RemoveUser removes regular user in authentication database.

func (*Server) Replicate

func (s *Server) Replicate(ctx context.Context, source, target string, options map[string]interface{}) (map[string]interface{}, error)

Replicate requests, configure or stop a replication operation.

func (*Server) Stats

func (s *Server) Stats(ctx context.Context, node, entry string) (map[string]interface{}, error)

Stats returns a JSON object containing the statistics for the running server.

func (*Server) String

func (s *Server) String() string

func (*Server) UUIDs

func (s *Server) UUIDs(ctx context.Context, count int) ([]string, error)

UUIDs requests one or more Universally Unique Identifiers from the CouchDB instance. The response is a JSON object providing a list of UUIDs. count - Number of UUIDs to return. Default is 1.

func (*Server) VerifyToken

func (s *Server) VerifyToken(ctx context.Context, token string) error

VerifyToken returns error if user's token is invalid.

func (*Server) Version

func (s *Server) Version(ctx context.Context) (string, error)

Version returns the version info about CouchDB instance.

type UpdateResult

type UpdateResult struct {
	ID, Rev string
	Err     error
}

UpdateResult represents result of an update.

func SyncMany

func SyncMany(ctx context.Context, db *Database, viewDefns []*ViewDefinition, removeMissing bool, callback func(map[string]interface{})) ([]UpdateResult, error)

SyncMany ensures that the views stored in the database match the views defined by the corresponding view definitions. This function might update more than one design document. This is done using CouchDB's bulk update to ensure atomicity of the opeation. db: the corresponding database.

viewDefns: a sequence of *ViewDefinition instances.

removeMissing: whether to remove views found in a design document that are not found in the list of ViewDefinition instances, default false.

callback: a callback function invoked when a design document gets updated; it is called before the doc has actually been saved back to the database.

type ViewDefinition

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

ViewDefinition is a definition of view stored in a specific design document.

func NewViewDefinition

func NewViewDefinition(design, name, mapFun, reduceFun, language string, wrapper func(Row) Row, options map[string]interface{}) (*ViewDefinition, error)

NewViewDefinition returns a newly-created *ViewDefinition. design: the name of the design document.

name: the name of the view.

mapFun: the map function code.

reduceFun: the reduce function code(optional).

language: the name of the programming language used, default is javascript.

wrapper: an optional function for processing the result rows after retrieved.

options: view specific options.

func (*ViewDefinition) GetDoc

func (vd *ViewDefinition) GetDoc(ctx context.Context, db *Database) (map[string]interface{}, error)

GetDoc retrieves the design document corresponding to this view definition from the given database.

func (*ViewDefinition) Sync

func (vd *ViewDefinition) Sync(ctx context.Context, db *Database) ([]UpdateResult, error)

Sync ensures that the view stored in the database matches the view defined by this instance.

func (*ViewDefinition) View

func (vd *ViewDefinition) View(db *Database, options map[string]interface{}) IViewResults

View executes the view definition in the given database.

type ViewField

type ViewField func() (*ViewDefinition, error)

ViewField represents a view definition value bound to Document.

func NewViewField

func NewViewField(design, name, mapFun, reduceFun, language string, wrapper func(Row) Row, options map[string]interface{}) ViewField

NewViewField returns a ViewField function. design: the name of the design document.

name: the name of the view.

mapFun: the map function code.

reduceFun: the reduce function code(optional).

language: the name of the programming language used, default is javascript.

wrapper: an optional function for processing the result rows after retrieved.

options: view specific options.

type ViewResults

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

ViewResults represents the results produced by design document views.

func (*ViewResults) Offset

func (vr *ViewResults) Offset(ctx context.Context) (int, error)

Offset returns offset of ViewResults

func (*ViewResults) Rows

func (vr *ViewResults) Rows(ctx context.Context) ([]Row, error)

Rows returns a slice of rows mapped (and reduced) by the view.

func (*ViewResults) TotalRows

func (vr *ViewResults) TotalRows(ctx context.Context) (int, error)

TotalRows returns total rows of ViewResults

func (*ViewResults) UpdateSeq

func (vr *ViewResults) UpdateSeq(ctx context.Context) (int, error)

UpdateSeq returns update sequence of ViewResults

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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