Documentation ¶
Overview ¶
Example (CreateDatabase) ¶
ExampleCreateDatabase
package main import ( "fmt" "time" "github.com/joelnb/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/joelnb/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/joelnb/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/joelnb/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 ¶
- Constants
- func ErrorStatus(err error, statusCode int) bool
- func ToBoolean(b BooleanParameter) bool
- type AlwaysString
- type Attachment
- type Authenticator
- func BasicAuthenticator(user, pass string) Authenticator
- func ClientCertAuthenticator(certPath, keyPath, caPath string) (Authenticator, error)
- func ClientCertAuthenticatorPassword(certPath, keyPath, caPath, password string) (Authenticator, error)
- func CookieAuthenticator() Authenticator
- func NullAuthenticator() Authenticator
- func ProxyAuthenticator(username string, roles []string, secret string) Authenticator
- type BooleanParameter
- type ChangesFeed
- type ChangesFeedChange
- type ChangesFeedParams
- type ChangesFeedParams1
- type ChangesFeedParams2
- type ChangesFeedParams3
- type ChangesFeedUpdate
- type Connection
- func (con *Connection) AllClusterStatistics() (Statistics2, error)
- func (con *Connection) ClusterStatistic(category, name string) (Statistics2, error)
- func (con *Connection) CreateDatabase(name string) (*Database, error)
- func (con *Connection) CreateUser(user *UserDocument) (string, error)
- func (con *Connection) Database(name string) *Database
- func (con *Connection) Databases() (databases []*Database, err error)
- func (con *Connection) Delete(path string, opts Options) (resp *http.Response, err error)
- func (con *Connection) DeleteDatabase(name string) error
- func (con *Connection) DeleteReplication(repl *Replication) (string, error)
- func (con *Connection) DeleteUser(user *UserDocument) (string, error)
- func (con *Connection) EnsureDatabase(name string) (*Database, error)
- func (con *Connection) Get(path string, opts Options) (resp *http.Response, err error)
- func (con *Connection) Head(path string, opts Options) (resp *http.Response, err error)
- func (con *Connection) ListDatabases() (databases []string, err error)
- func (con *Connection) Patch(path string, opts Options, body io.Reader) (resp *http.Response, err error)
- func (con *Connection) Ping() error
- func (con *Connection) Post(path string, opts Options, body io.Reader) (resp *http.Response, err error)
- func (con *Connection) Put(path string, opts Options, body io.Reader) (resp *http.Response, err error)
- func (con *Connection) PutReplication(repl *Replication) (string, error)
- func (con *Connection) Replication(id, rev string) (Replication, error)
- func (con *Connection) Replications() ([]Replication, error)
- func (con *Connection) Request(method, path string, opts Options, body io.Reader) (resp *http.Response, err error)
- func (con *Connection) URL(path string) url.URL
- func (con *Connection) UpdateUser(user *UserDocument) (string, error)
- func (con *Connection) User(name string, rev string) (UserDocument, error)
- func (con *Connection) UserByID(id string, rev string) (UserDocument, error)
- func (con *Connection) Users() ([]UserDocument, error)
- type ContinuousChangesFeed
- type CouchDB1Connection
- type CouchDB2Connection
- type CouchDB3Connection
- type Database
- func (d *Database) AllDocuments() (DocumentList, error)
- func (d *Database) CompactView(name string) error
- func (d *Database) ContinuousChangesFeed(params ChangesFeedParams) ContinuousChangesFeed
- func (d *Database) Delete(document Document) (string, error)
- func (db *Database) DeleteAttachment(docid, name, rev string) (string, error)
- func (d *Database) DocumentPath(id string) string
- func (d *Database) Documents(ids ...string) (DocumentList, error)
- func (d *Database) Get(document Document, id, rev string) (string, error)
- func (db *Database) GetAttachment(docid, name, rev string) ([]byte, error)
- func (d *Database) ListDocuments() (DocumentList, error)
- func (d *Database) Metadata() (DatabaseMetadata, error)
- func (d *Database) Name() string
- func (d *Database) NamedView(design, name string) NamedView
- func (d *Database) Path() string
- func (d *Database) PollingChangesFeed(long bool) PollingChangesFeed
- func (d *Database) Put(document Document) (string, error)
- func (db *Database) PutAttachment(docid, name string, doc io.Reader, rev string) (string, error)
- func (d *Database) TemporaryView(mapFunc string) TemporaryView
- func (d *Database) ViewCleanup() error
- func (d *Database) ViewPath(view string) string
- type DatabaseMetadata
- type DetailedStatistic
- type Document
- type DocumentList
- type DocumentMetadata
- type GenericDocument
- type InterfaceListParameter
- type InterfaceParameter
- type NamedView
- type Options
- type PollingChangesFeed
- type Replication
- type ResponseError
- type Row
- type ServerDetails1
- type ServerDetails2
- type ServerResponse
- type SimpleStatistic
- type Statistic1
- type Statistics1
- type Statistics2
- type Task
- type TemporaryView
- type URLOptions
- type UserDocument
- type View
- type ViewParams
Examples ¶
Constants ¶
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 ¶
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 AlwaysString ¶ added in v0.3.0
type AlwaysString string
AlwaysString allows fields which can be either an int or string (depending on the version) to always be unmarshaled as a string.
func (*AlwaysString) UnmarshalJSON ¶ added in v0.3.0
func (fs *AlwaysString) UnmarshalJSON(b []byte) error
UnmarshalJSON implements the json.Unmarshaler interface, returning directly as a string if one is found or converting an int if that is found. Other types are not supported and the error from json.Unmarshal will be returned.
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.1.2
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.1.2
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 AlwaysString `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 ChangesFeedParams1 ¶ added in v0.3.0
type ChangesFeedParams1 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"` }
ChangesFeedParams1 includes all parameters which can be provided to control the output of a changes feed from a database on a version 1 server.
func (*ChangesFeedParams1) SetFeedType ¶ added in v0.3.0
func (params *ChangesFeedParams1) SetFeedType(ftype string)
type ChangesFeedParams2 ¶ added in v0.3.0
type ChangesFeedParams2 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 string `url:"since,omitempty"` Style string `url:"style,omitempty"` Timeout int64 `url:"timeout,omitempty"` View string `url:"view,omitempty"` }
ChangesFeedParams2 includes all parameters which can be provided to control the output of a changes feed from a database on a version 2/3 server.
func (*ChangesFeedParams2) SetFeedType ¶ added in v0.3.0
func (params *ChangesFeedParams2) SetFeedType(ftype string)
type ChangesFeedParams3 ¶ added in v0.3.0
type ChangesFeedParams3 = ChangesFeedParams2
type ChangesFeedUpdate ¶
type ChangesFeedUpdate struct { LastSeq AlwaysString `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.1.2
func (con *Connection) AllClusterStatistics() (Statistics2, error)
AllClusterStatistics gets all of the available statistics from the server.
func (*Connection) ClusterStatistic ¶ added in v0.1.2
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.2.0
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 ¶
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.2.0
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) 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.0
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.2.0
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.2.0
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 ¶
func (f *ContinuousChangesFeed) Next() (ChangesFeedChange, error)
Next gets the next available item from the changes feed. This will block until an item becomes available.
type CouchDB1Connection ¶ added in v0.1.2
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.1.2
func (con *CouchDB1Connection) AllStatistics() (Statistics1, error)
AllStatistics gets all of the available statistics from the server.
func (*CouchDB1Connection) FutonURL ¶ added in v0.1.2
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.1.2
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.1.2
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.1.2
type CouchDB2Connection struct {
*Connection
}
CouchDB2Connection is a connection specifically for a version 2 server.
func NewConnection2 ¶ added in v0.1.2
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.1.2
func (con *CouchDB2Connection) AllStatistics() (Statistics2, error)
AllStatistics gets all of the available statistics from the server.
func (*CouchDB2Connection) FauxtonURL ¶ added in v0.1.2
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.1.2
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.1.2
func (con *CouchDB2Connection) Statistic(category, name string) (Statistics2, error)
Statistic loads a single specific statistic from the server by category & name.
type CouchDB3Connection ¶ added in v0.3.0
type CouchDB3Connection struct {
*CouchDB2Connection
}
CouchDB3Connection is a connection specifically for a version 3 server.
func NewConnection3 ¶ added in v0.3.0
func NewConnection3(serverURL string, timeout time.Duration, auth Authenticator) (*CouchDB3Connection, error)
NewConnection3 creates a new CouchDB3Connection which can be used to interact with a single CouchDB server. Any query parameters passed in the serverUrl are discarded before creating the connection.
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 ¶
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) DeleteAttachment ¶ added in v0.3.0
DeleteAttachment removes an attachment from a document in CouchDB.
func (*Database) DocumentPath ¶
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 ¶
Get retrieves a single document from the database and unmarshals it into the provided interface.
func (*Database) GetAttachment ¶ added in v0.3.0
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) 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 ¶
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 ¶
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.0
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 ¶
ViewCleanup cleans old data from the database. From the CouchDB API documentation: "Old view output remains on disk until you explicitly run cleanup."
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 AlwaysString `json:"purge_seq"` UpdateSeq AlwaysString `json:"update_seq"` CommittedUpdateSeq AlwaysString `json:"committed_update_seq"` }
DatabaseMetadata contains information about the database in CouchDB.
type DetailedStatistic ¶ added in v0.1.2
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.1.2
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.1.2
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.1.2
func (i InterfaceListParameter) MarshalJSON() ([]byte, error)
MarshalJSON simply marshals the internal value.
type InterfaceParameter ¶ added in v0.1.2
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.1.2
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.1.2
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.1.2
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 ¶
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.
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 ¶
func (f PollingChangesFeed) Next(params ChangesFeedParams) (ChangesFeedUpdate, error)
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.0
func NewReplication(id, source, target string) Replication
NewReplication creates a new Replication instance with the source and target defined.
type ResponseError ¶
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 ¶
HasDocument checks the current Row for the presence of the Document attached to it.
type ServerDetails1 ¶ added in v0.1.2
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.1.2
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.1.2
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.1.2
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.1.2
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.1.2
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 ¶
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