Documentation ¶
Index ¶
- Constants
- Variables
- func AddHook(doctype, event string, hook listener)
- func AllDoctypes(db Database) ([]string, error)
- func BulkDeleteDocs(db Database, doctype string, docs []Doc) error
- func BulkForceUpdateDocs(db Database, doctype string, docs []map[string]interface{}) error
- func BulkGetDocs(db Database, doctype string, payload []IDRev) ([]map[string]interface{}, error)
- func BulkUpdateDocs(db Database, doctype string, docs, olddocs []interface{}) error
- func CountAllDocs(db Database, doctype string) (int, error)
- func CreateDB(db Database, doctype string) error
- func CreateDoc(db Database, doc Doc) error
- func CreateNamedDoc(db Database, doc Doc) error
- func CreateNamedDocWithDB(db Database, doc Doc) error
- func DefineIndex(db Database, index *mango.Index) error
- func DefineIndexes(db Database, indexes []*mango.Index) error
- func DefineViews(db Database, views []*View) error
- func DeleteAllDBs(db Database) error
- func DeleteDB(db Database, doctype string) error
- func DeleteDoc(db Database, doc Doc) error
- func DeleteLocal(db Database, doctype, id string) error
- func EnsureDBExist(db Database, doctype string) error
- func EscapeCouchdbName(name string) string
- func ExecView(db Database, view *View, req *ViewRequest, results interface{}) error
- func FindDocs(db Database, doctype string, req *FindRequest, results interface{}) error
- func FindDocsRaw(db Database, doctype string, req interface{}, results interface{}) error
- func FindDocsUnoptimized(db Database, doctype string, req interface{}, results interface{}) error
- func ForeachDocs(db Database, doctype string, fn func(id string, doc json.RawMessage) error) error
- func GetAllDocs(db Database, doctype string, req *AllDocsRequest, results interface{}) (err error)
- func GetDoc(db Database, doctype, id string, out Doc) error
- func GetDocRev(db Database, doctype, id, rev string, out Doc) error
- func GetLocal(db Database, doctype, id string) (map[string]interface{}, error)
- func InitGlobalDB() error
- func IsConflictError(err error) bool
- func IsFileExists(err error) bool
- func IsInternalServerError(err error) bool
- func IsNoDatabaseError(err error) bool
- func IsNoUsableIndexError(err error) bool
- func IsNotFoundError(err error) bool
- func Proxy(db Database, doctype, path string) *httputil.ReverseProxy
- func ProxyBulkDocs(db Database, doctype string, req *http.Request) (*httputil.ReverseProxy, *http.Request, error)
- func PutLocal(db Database, doctype, id string, doc map[string]interface{}) error
- func RTEvent(db Database, verb string, doc, oldDoc Doc)
- func ResetDB(db Database, doctype string) error
- func UpdateDoc(db Database, doc Doc) error
- func UpdateDocWithOld(db Database, doc, oldDoc Doc) error
- func Upsert(db Database, doc Doc) error
- type AllDocsRequest
- type AllDocsResponse
- type BulkGetResponse
- type Change
- type ChangesFeedMode
- type ChangesFeedStyle
- type ChangesRequest
- type ChangesResponse
- type Cursor
- type DBStatusResponse
- type Database
- type Doc
- type DocReference
- type Error
- type FindRequest
- type IDRev
- type IndexCreationResponse
- type JSONDoc
- func (j JSONDoc) Clone() Doc
- func (j JSONDoc) DocType() string
- func (j JSONDoc) Get(key string) interface{}
- func (j JSONDoc) ID() string
- func (j JSONDoc) MarshalJSON() ([]byte, error)
- func (j JSONDoc) Match(field, value string) bool
- func (j JSONDoc) Rev() string
- func (j JSONDoc) SetID(id string)
- func (j JSONDoc) SetRev(rev string)
- func (j *JSONDoc) ToMapWithType() map[string]interface{}
- func (j *JSONDoc) UnmarshalJSON(bytes []byte) error
- type NormalDocsResponse
- type SkipCursor
- type StartKeyCursor
- type UpdateResponse
- type View
- type ViewDesignDoc
- type ViewRequest
- type ViewResponse
- type ViewResponseRow
Constants ¶
const ( // ChangesModeNormal is the only mode supported by cozy-stack ChangesModeNormal ChangesFeedMode = "normal" // ChangesStyleAllDocs pass all revisions including conflicts ChangesStyleAllDocs ChangesFeedStyle = "all_docs" // ChangesStyleMainOnly only pass the winning revision ChangesStyleMainOnly ChangesFeedStyle = "main_only" )
const ( EventCreate = realtime.EventCreate EventUpdate = realtime.EventUpdate EventDelete = realtime.EventDelete )
Events to hook into
const MaxString = mango.MaxString
MaxString is the unicode character "\uFFFF", useful in query as a upperbound for string.
const SelectorReferencedBy = "referenced_by"
SelectorReferencedBy is the string constant for the references in a JSON document.
Variables ¶
var ContactByEmail = &View{ Name: "contacts-by-email", Doctype: consts.Contacts, Map: ` function(doc) { if (isArray(doc.email)) { for (var i = 0; i < doc.email.length; i++) { emit(doc.email[i].address, doc._id); } } } `, }
ContactByEmail is used to find a contact by its email address
var DomainAndAliasesView = &View{ Name: "domain-and-aliases", Doctype: consts.Instances, Map: ` function(doc) { emit(doc.domain); if (isArray(doc.domain_aliases)) { for (var i = 0; i < doc.domain_aliases.length; i++) { emit(doc.domain_aliases[i]); } } } `, }
DomainAndAliasesView defines a view to fetch instances by domain and domain aliases.
var GlobalDB = newDatabase("global")
GlobalDB is the prefix used for stack-scoped db
var GlobalSecretsDB = newDatabase("secrets")
GlobalSecretsDB is the the prefix used for db which hold a cozy stack secrets.
var Views = []*View{ ContactByEmail, }
Views is the list of all views that are created by the stack.
Functions ¶
func AddHook ¶
func AddHook(doctype, event string, hook listener)
AddHook adds an hook for the given doctype and event. Useful for special doctypes cleanup
func AllDoctypes ¶
AllDoctypes returns a list of all the doctypes that have a database on a given instance
func BulkDeleteDocs ¶
BulkDeleteDocs is used to delete serveral documents in one call.
func BulkForceUpdateDocs ¶
BulkForceUpdateDocs is used to update several docs in one call, and to force the revisions history. It is used by replications.
func BulkGetDocs ¶
BulkGetDocs returns the documents with the given id at the given revision
func BulkUpdateDocs ¶
BulkUpdateDocs is used to update several docs in one call, as a bulk. olddocs parameter is used for realtime / event triggers.
func CountAllDocs ¶
CountAllDocs returns the number of documents of the given doctype.
func CreateDoc ¶
CreateDoc is used to persist the given document in the couchdb database. The document's SetRev and SetID function will be called with the document's new ID and Rev. This function creates a database if this is the first document of its type
func CreateNamedDoc ¶
CreateNamedDoc persist a document with an ID. if the document already exist, it will return a 409 error. The document ID should be fillled. The doc SetRev function will be called with the new rev.
func CreateNamedDocWithDB ¶
CreateNamedDocWithDB is equivalent to CreateNamedDoc but creates the database if it does not exist
func DefineIndex ¶
DefineIndex define the index on the doctype database see query package on how to define an index
func DefineIndexes ¶
DefineIndexes defines a list of indexes
func DefineViews ¶
DefineViews creates a design doc with some views
func DeleteAllDBs ¶
DeleteAllDBs will remove all the couchdb doctype databases for a couchdb.DB.
func DeleteDoc ¶
DeleteDoc deletes a struct implementing the couchb.Doc interface If the document's current rev does not match the one passed, a CouchdbError(409 conflict) will be returned. The document's SetRev will be called with tombstone revision
func DeleteLocal ¶
DeleteLocal will delete a local document in CouchDB.
func EnsureDBExist ¶
EnsureDBExist creates the database for the doctype if it doesn't exist
func EscapeCouchdbName ¶
EscapeCouchdbName can be used to build the name of a database from the instance prefix and doctype.
func ExecView ¶
func ExecView(db Database, view *View, req *ViewRequest, results interface{}) error
ExecView executes the specified view function
func FindDocs ¶
func FindDocs(db Database, doctype string, req *FindRequest, results interface{}) error
FindDocs returns all documents matching the passed FindRequest documents will be unmarshalled in the provided results slice.
func FindDocsRaw ¶
FindDocsRaw find documents TODO: pagination
func FindDocsUnoptimized ¶
FindDocsUnoptimized allows search on non-indexed fields. /!\ Use with care
func ForeachDocs ¶
ForeachDocs traverse all the documents from the given database with the specified doctype and calls a function for each document.
func GetAllDocs ¶
func GetAllDocs(db Database, doctype string, req *AllDocsRequest, results interface{}) (err error)
GetAllDocs returns all documents of a specified doctype. It filters out the possible _design document.
func GetDoc ¶
GetDoc fetch a document by its docType and ID, out is filled with the document by json.Unmarshal-ing
func GetDocRev ¶
GetDocRev fetch a document by its docType and ID on a specific revision, out is filled with the document by json.Unmarshal-ing
func GetLocal ¶
GetLocal fetch a local document from CouchDB http://docs.couchdb.org/en/stable/api/local.html#get--db-_local-docid
func InitGlobalDB ¶
func InitGlobalDB() error
InitGlobalDB defines views and indexes on the global databases. It is called on every startup of the stack.
func IsConflictError ¶
IsConflictError checks if the given error is a couch conflict error
func IsFileExists ¶
IsFileExists checks if the given error is a couch conflict error
func IsInternalServerError ¶
IsInternalServerError checks if CouchDB has returned a 5xx code
func IsNoDatabaseError ¶
IsNoDatabaseError checks if the given error is a couch no_db_file error
func IsNoUsableIndexError ¶
IsNoUsableIndexError checks if the given error is an error form couch, for an invalid request on an index that is not usable.
func IsNotFoundError ¶
IsNotFoundError checks if the given error is a couch not_found error
func Proxy ¶
func Proxy(db Database, doctype, path string) *httputil.ReverseProxy
Proxy generate a httputil.ReverseProxy which forwards the request to the correct route.
func ProxyBulkDocs ¶
func ProxyBulkDocs(db Database, doctype string, req *http.Request) (*httputil.ReverseProxy, *http.Request, error)
ProxyBulkDocs generates a httputil.ReverseProxy to forward the couchdb request on the _bulk_docs endpoint. This endpoint is specific since it will mutate many document in database, the stack has to read the response from couch to emit the correct realtime events.
func PutLocal ¶
PutLocal will put a local document in CouchDB. Note that you should put the last revision in `doc` to avoid conflicts.
func UpdateDoc ¶
UpdateDoc update a document. The document ID and Rev should be filled. The doc SetRev function will be called with the new rev.
func UpdateDocWithOld ¶
UpdateDocWithOld updates a document, like UpdateDoc. The difference is that if we already have oldDoc there is no need to refetch it from database.
Types ¶
type AllDocsRequest ¶
type AllDocsRequest struct { Descending bool `url:"descending,omitempty"` Limit int `url:"limit,omitempty"` Skip int `url:"skip,omitempty"` StartKey string `url:"startkey,omitempty"` StartKeyDocID string `url:"startkey_docid,omitempty"` EndKey string `url:"endkey,omitempty"` EndKeyDocID string `url:"endkey_docid,omitempty"` Keys []string `url:"keys,omitempty"` }
AllDocsRequest is used to build a _all_docs request
type AllDocsResponse ¶
type AllDocsResponse struct { Offset int `json:"offset"` TotalRows int `json:"total_rows"` Rows []struct { ID string `json:"id"` Doc json.RawMessage `json:"doc"` } `json:"rows"` }
AllDocsResponse is the response we receive from an _all_docs request
type BulkGetResponse ¶
type BulkGetResponse struct { Results []struct { Docs []struct { OK map[string]interface{} `json:"ok"` } `json:"docs"` } `json:"results"` }
BulkGetResponse is the response we receive from a _bulk_get request
type Change ¶
type Change struct { DocID string `json:"id"` Seq string `json:"seq"` Doc JSONDoc `json:"doc"` Changes []struct { Rev string `json:"rev"` } `json:"changes"` }
A Change is an atomic change in couchdb
type ChangesFeedMode ¶
type ChangesFeedMode string
ChangesFeedMode is a value for the feed parameter of a ChangesRequest
func ValidChangesMode ¶
func ValidChangesMode(feed string) (ChangesFeedMode, error)
ValidChangesMode convert any string into a ChangesFeedMode or gives an error if the string is invalid.
type ChangesFeedStyle ¶
type ChangesFeedStyle string
ChangesFeedStyle is a value for the style parameter of a ChangesRequest
func ValidChangesStyle ¶
func ValidChangesStyle(style string) (ChangesFeedStyle, error)
ValidChangesStyle convert any string into a ChangesFeedStyle or gives an error if the string is invalid.
type ChangesRequest ¶
type ChangesRequest struct { DocType string `url:"-"` // see Changes Feeds. Default is normal. Feed ChangesFeedMode `url:"feed,omitempty"` // Maximum period in milliseconds to wait for a change before the response // is sent, even if there are no results. Only applicable for longpoll or // continuous feeds. Default value is specified by httpd/changes_timeout // configuration option. Note that 60000 value is also the default maximum // timeout to prevent undetected dead connections. Timeout int `url:"timeout,omitempty"` // Period in milliseconds after which an empty line is sent in the results. // Only applicable for longpoll, continuous, and eventsource feeds. Overrides // any timeout to keep the feed alive indefinitely. Default is 60000. May be // true to use default value. Heartbeat int `url:"heartbeat,omitempty"` // Includes conflicts information in response. Ignored if include_docs isn’t // true. Default is false. Conflicts bool `url:"conflicts,omitempty"` // Return the change results in descending sequence order (most recent change // first). Default is false. Descending bool `url:"descending,omitempty"` // Include the associated document with each result. If there are conflicts, // only the winning revision is returned. Default is false. IncludeDocs bool `url:"include_docs,omitempty"` // 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. Attachments bool `url:"attachments,omitempty"` // 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. AttEncodingInfo bool `url:"att_encoding_info,omitempty"` // Alias of Last-Event-ID header. LastEventID int `url:"last,omitempty"` // Limit number of result rows to the specified value (note that using 0 here // has the same effect as 1). Limit int `url:"limit,omitempty"` // Start the results from the change immediately after the given update // sequence. Can be valid update sequence or now value. Default is 0. Since string `url:"since,omitempty"` // Specifies how many revisions are returned in the changes array. The // default, main_only, will only return the current “winning” revision; // all_docs will return all leaf revisions (including conflicts and deleted // former conflicts). Style ChangesFeedStyle `url:"style,omitempty"` // Reference to a filter function from a design document that will filter // whole stream emitting only filtered events. See the section Change // Notifications in the book CouchDB The Definitive Guide for more // information. Filter string `url:"filter,omitempty"` // Allows to use view functions as filters. Documents counted as “passed” for // view filter in case if map function emits at least one record for them. // See _view for more info. View string `url:"view,omitempty"` // SeqInterval tells CouchDB to only calculate the update seq with every // Nth result returned. It is used by PouchDB replication, and helps to // lower the load on a CouchDB cluster. SeqInterval int `url:"seq_interval,omitempty"` }
A ChangesRequest are all parameters than can be passed to a changes feed
type ChangesResponse ¶
type ChangesResponse struct { LastSeq string `json:"last_seq"` // Last change update sequence Pending int `json:"pending"` // Count of remaining items in the feed Results []Change `json:"results"` // Changes made to a database }
A ChangesResponse is the response provided by a GetChanges call
func GetChanges ¶
func GetChanges(db Database, req *ChangesRequest) (*ChangesResponse, error)
GetChanges returns a list of change in couchdb
type Cursor ¶
type Cursor interface { HasMore() bool ApplyTo(req *ViewRequest) UpdateFrom(res *ViewResponse) }
A Cursor holds a reference to a page in a couchdb View
func NewKeyCursor ¶
NewKeyCursor returns a new key based Cursor pointing to the given start_key & startkey_docid
func NewSkipCursor ¶
NewSkipCursor returns a new skip based Cursor pointing to the page after skip items
type DBStatusResponse ¶
type DBStatusResponse struct { DBName string `json:"db_name"` UpdateSeq string `json:"update_seq"` Sizes struct { File int `json:"file"` External int `json:"external"` Active int `json:"active"` } `json:"sizes"` PurgeSeq interface{} `json:"purge_seq"` // Was an int before CouchDB 2.3, and a string since then 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"` InstanceStartTime string `json:"instance_start_time"` }
DBStatusResponse is the response from DBStatus
type Database ¶
Database is the type passed to every function in couchdb package for now it is just a string with the database prefix.
type Doc ¶
type Doc interface { ID() string Rev() string DocType() string Clone() Doc SetID(id string) SetRev(rev string) }
Doc is the interface that encapsulate a couchdb document, of any serializable type. This interface defines method to set and get the ID of the document.
type DocReference ¶
DocReference is a reference to a document
type Error ¶
type Error struct { StatusCode int `json:"status_code"` CouchdbJSON []byte `json:"-"` Name string `json:"error"` Reason string `json:"reason"` Original error `json:"-"` }
Error represent an error from couchdb
func IsCouchError ¶
IsCouchError returns whether or not the given error is of type couchdb.Error.
type FindRequest ¶
type FindRequest struct { Selector mango.Filter `json:"selector"` UseIndex string `json:"use_index,omitempty"` Limit int `json:"limit,omitempty"` Skip int `json:"skip,omitempty"` Sort mango.SortBy `json:"sort,omitempty"` Fields []string `json:"fields,omitempty"` }
FindRequest is used to build a find request
type IndexCreationResponse ¶
type IndexCreationResponse struct { Result string `json:"result,omitempty"` Error string `json:"error,omitempty"` Reason string `json:"reason,omitempty"` ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` }
IndexCreationResponse is the response from couchdb when we create an Index
func DefineIndexRaw ¶
func DefineIndexRaw(db Database, doctype string, index interface{}) (*IndexCreationResponse, error)
DefineIndexRaw defines a index
type JSONDoc ¶
JSONDoc is a map representing a simple json object that implements the Doc interface.
func (JSONDoc) DocType ¶
DocType returns the document type of the document
"io.cozy.event" == doc.Doctype()
func (JSONDoc) ID ¶
ID returns the identifier field of the document
"io.cozy.event/123abc123" == doc.ID()
func (JSONDoc) MarshalJSON ¶
MarshalJSON implements json.Marshaller by proxying to internal map
func (JSONDoc) Match ¶
Match implements permissions.Matcher on JSONDoc.
The `referenced_by` selector is a special case: the `values` field of such rule has the format "doctype/id" and it cannot directly be compared to the same field of a JSONDoc since, in the latter, the format is: "referenced_by": [
{"type": "doctype1", "id": "id1"}, {"type": "doctype2", "id": "id2"},
]
func (*JSONDoc) ToMapWithType ¶
ToMapWithType returns the JSONDoc internal map including its DocType its used in request response.
func (*JSONDoc) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaller by proxying to internal map
type NormalDocsResponse ¶
type NormalDocsResponse struct { Total int `json:"total_rows"` Rows []json.RawMessage `json:"rows"` }
NormalDocsResponse is the response the stack send for _normal_docs queries
func NormalDocs ¶
func NormalDocs(db Database, doctype string, skip, limit int) (*NormalDocsResponse, error)
NormalDocs returns all the documents from a database, with pagination, but it excludes the design docs.
type SkipCursor ¶
type SkipCursor struct { // Skip is the number of elements to start from Skip int // contains filtered or unexported fields }
SkipCursor is a Cursor using Skip to know how deep in the request it is.
func (*SkipCursor) ApplyTo ¶
func (c *SkipCursor) ApplyTo(req *ViewRequest)
ApplyTo applies the cursor to a ViewRequest the transformed ViewRequest will retrieve elements from Cursor to Limit or EndKey whichever comes first /!\ Mutates req
func (SkipCursor) HasMore ¶
func (c SkipCursor) HasMore() bool
HasMore returns true if there is more document after the current batch. This value is meaning full only after UpdateFrom
func (*SkipCursor) UpdateFrom ¶
func (c *SkipCursor) UpdateFrom(res *ViewResponse)
UpdateFrom change the cursor status depending on information from the view's response
type StartKeyCursor ¶
type StartKeyCursor struct { // NextKey & NextDocID contains a reference to the document // right after the last fetched one NextKey interface{} NextDocID string // contains filtered or unexported fields }
StartKeyCursor is a Cursor using start_key, ie a reference to the last fetched item to keep pagination
func (*StartKeyCursor) ApplyTo ¶
func (c *StartKeyCursor) ApplyTo(req *ViewRequest)
ApplyTo applies the cursor to a ViewRequest the transformed ViewRequest will retrieve elements from Cursor to Limit or EndKey whichever comes first /!\ Mutates req
func (StartKeyCursor) HasMore ¶
func (c StartKeyCursor) HasMore() bool
HasMore returns true if there is more document after the current batch. This value is meaning full only after UpdateFrom
func (*StartKeyCursor) UpdateFrom ¶
func (c *StartKeyCursor) UpdateFrom(res *ViewResponse)
UpdateFrom change the cursor status depending on information from the view's response
type UpdateResponse ¶
UpdateResponse is the response from couchdb when updating documents
type View ¶
type View struct { Name string `json:"-"` Doctype string `json:"-"` Map string `json:"map"` Reduce string `json:"reduce,omitempty"` }
View is the map/reduce thing in CouchDB
func ViewsByDoctype ¶
ViewsByDoctype returns the list of views for a specified doc type.
type ViewDesignDoc ¶
type ViewDesignDoc struct { ID string `json:"_id,omitempty"` Rev string `json:"_rev,omitempty"` Lang string `json:"language"` Views map[string]*View `json:"views"` }
ViewDesignDoc is the structure if a _design doc containing views
type ViewRequest ¶
type ViewRequest struct { Key interface{} `json:"key,omitempty" url:"key,omitempty"` StartKey interface{} `json:"start_key,omitempty" url:"start_key,omitempty"` EndKey interface{} `json:"end_key,omitempty" url:"end_key,omitempty"` StartKeyDocID string `json:"startkey_docid,omitempty" url:"startkey_docid,omitempty"` EndKeyDocID string `json:"endkey_docid,omitempty" url:"endkey_docid,omitempty"` // Keys cannot be used in url mode Keys []interface{} `json:"keys,omitempty" url:"-"` Limit int `json:"limit,omitempty" url:"limit,omitempty"` Skip int `json:"skip,omitempty" url:"skip,omitempty"` Descending bool `json:"descending,omitempty" url:"descending,omitempty"` IncludeDocs bool `json:"include_docs,omitempty" url:"include_docs,omitempty"` InclusiveEnd bool `json:"inclusive_end,omitempty" url:"inclusive_end,omitempty"` Reduce bool `json:"reduce" url:"reduce"` Group bool `json:"group" url:"group"` GroupLevel int `json:"group_level,omitempty" url:"group_level,omitempty"` }
ViewRequest are all params that can be passed to a view It can be encoded either as a POST-json or a GET-url.
type ViewResponse ¶
type ViewResponse struct { Total int `json:"total_rows"` Offset int `json:"offset,omitempty"` Rows []*ViewResponseRow `json:"rows"` }
ViewResponse is the response we receive when executing a view
type ViewResponseRow ¶
type ViewResponseRow struct { ID string `json:"id"` Key interface{} `json:"key"` Value interface{} `json:"value"` Doc json.RawMessage `json:"doc"` }
ViewResponseRow is a row in a ViewResponse