gocouch

package module
v0.0.0-...-7689f73 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2016 License: MIT Imports: 14 Imported by: 0

README

Build Status Go Report Card GoDoc

###Connecting to server:

defaultTimeout := time.Second * 10
conn, err := gocouch.Connect("127.0.0.1", 5984, nil, defaultTimeout)

// With credentials
auth := gocouch.BasicAuth{"admin", "pass"}
conn, err := gocouch.Connect("127.0.0.1", 5984, auth, defaultTimeout)

###Database operations: Get existing database or create new one:

db, err := conn.MustGetDatabase("some_db", nil)

Non-nil Auth passed to this method has higher priority, so it will owerride previously used on Connect. By default this method use Auth object provided when connection was created.

Get all existing databases:

list, err := conn.GetAllDBs()

Fetch new database related action on CouchDB instance:

var events map[string]interface{}
err := conn.GetDBEvent(&events, nil)

This request will block workflow until any event happens or default timeout (60 sec) will be exceeded. If you try to specify custom operation timeout note that it accepts milliseconds. Also it's safe to use in goroutine.

If you want to fetch many events, you can use GetDBEventChan:

eventChan, err := conn.GetDBEventChan()
// don't forget to close channel to release connection resourses
defer close(eventChan)

###Basic CRUD actions with a single document:

package main

import (
	"github.com/pupizoid/gocouch"
	"time"
)

func main() {
	server, _ := gocouch.Connect("127.0.0.1", 5984, nil, time.Second * 10)

	type Doc struct {
		Field string `json:"field"`
		// Note: struct data will override `id` param in database methods,
		// to avoid conflicts struct fields representing document's
		// `_id` & `_rev` should always contain json tag `omitempty`
		Rev   string `json:"_rev,omitempty"`
		ID    string `json:"_id,omitempty"`
	}

	var document1, document2 Doc

	db, _ := server.MustGetDatabase("test_db", nil)

	document1.Field = "value"
  
    // Create document with specified id (also accepts map as a document)
	db.Put("test_id", &document1)
	// Get document by id
	db.Get("test_id", &document2, nil)
	// Delete document's revision
	db.Del(document2.ID, document2.Rev)

}

###Bulk operations:


##TODO:

  • Server API
  • Database API
  • Document API
  • Authentication
  • Design Docs & Views
  • Attachments
  • Coverage > 90%

Documentation

Overview

Package gocouch implements wrappers for the 95% of CouchDB HTTP API

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	Name, ContentType string
	Body              io.Reader
}

Attachment represents attachment to be stored in couchdb

type AttachmentInfo

type AttachmentInfo struct {
	Encoding string
	Length   int
	Type     string
	Hash     string
}

AttachmentInfo provides information about attachment

type Auth

type Auth interface {
	// AddAuthHeaders add authorisation headers
	AddAuthHeaders(*http.Request)
}

Auth is a common interface that provides methods

type BasicAuth

type BasicAuth struct {
	Username, Password string
}

BasicAuth provides simple user:password authentication

func (BasicAuth) AddAuthHeaders

func (ba BasicAuth) AddAuthHeaders(req *http.Request)

AddAuthHeaders used to add authentication headers to the request

type DBInfo

type DBInfo struct {
	CommitedUpdateSeq int    `json:"committed_update_seq"`
	CompactRunning    bool   `json:"compact_running"`
	Name              string `json:"db_name"`
	DiskVersion       int    `json:"disk_format_version"`
	DataSize          int    `json:"data_size"`
	DiskSize          int    `json:"disk_size"`
	DocCount          int    `json:"doc_count"`
	DocDelCount       int    `json:"doc_del_count"`
	StartTime         string `json:"instance_start_time"`
	PurgeSeq          int    `json:"purge_seq"`
	UpdateSeq         int    `json:"update_seq"`
}

DBInfo describes a database information

type Database

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

Database contains connection to couchdb instance and db name auth is inherited from Server on creation, but you can change it anytime

func (*Database) AttachmentInfo

func (db *Database) AttachmentInfo(id, name string) (*AttachmentInfo, error)

AttachementInfo provides basic information about specified attachment

func (*Database) Compact

func (db *Database) Compact() error

Compact runs database compaction process

func (*Database) CompactDesign

func (db *Database) CompactDesign(docName string) error

CompactDesign copacts the view indexes associated with specified design document

func (*Database) Copy

func (db *Database) Copy(id string, dest Destination, options Options) (string, error)

Copy... copies docuement with specified id to newly created document, ot to existing one. Note: if you're copying document to the existing one, you must specify target latest revision, otherwise couchdb will return 409(Conflict)

func (*Database) Del

func (db *Database) Del(id, rev string) (string, error)

Del adds new "_deleted" revision to the docuement with specified id

func (*Database) DelAttachment

func (db *Database) DelAttachment(id, name, rev string) error

DelAttachment used for deleting document's attachments

func (*Database) Delete

func (db *Database) Delete() error

Delete deletes datanase on chouchdb instance

func (*Database) DeleteMany

func (db *Database) DeleteMany(docs interface{}) ([]UpdateResult, error)

DeleteMany is a shortcut to delete method. Use it when you have documents you want to delete from database.

Argument may be `[]interface{}` or `[]map[string]string`

If you pass a slice of struct note that they must have fields with tags "_id" and "_rev", or error will be returned For maps here is a similar requirement, they must have both "_id" and "_rev" keys

func (*Database) EnsureFullCommit

func (db *Database) EnsureFullCommit() error

EnsureFullCommit tells database to commit any recent changes to the specified database to disk

func (*Database) Exists

func (db *Database) Exists(id string, options Options) (size int, rev string, err error)

Exists checks if document with specified id is present in the database

func (*Database) Get

func (db *Database) Get(id string, o interface{}, options Options) error

Get fetches single document by it's id

func (*Database) GetAllChanges

func (db *Database) GetAllChanges(options Options) (*DatabaseChanges, error)

GetAllChanges fetches all changes for current database

func (*Database) GetAllDocs

func (db *Database) GetAllDocs(options Options) (*ViewResult, error)

GetAllDocs function returns pointer to ViewResult

func (*Database) GetAllDocsByIDs

func (db *Database) GetAllDocsByIDs(keys []string, options Options) (*ViewResult, error)

GetAllDocsByIDs does same as GetAllDocs but in defferent way

func (*Database) GetAttachment

func (db *Database) GetAttachment(id, name, rev string) (*Attachment, error)

GetAttachment fetches attachement from database

func (*Database) GetChangesChan

func (db *Database) GetChangesChan(options Options) (c chan DatabaseEvent, err error)

GetChangesChan returns a channel from which a DatabaseEvents can be obtained

func (*Database) GetDatabaseSecurity

func (db *Database) GetDatabaseSecurity() *DatabaseSecurity

GetDatabaseSecurity returns security object of current database

func (*Database) GetMissedRevs

func (db *Database) GetMissedRevs(o map[string][]string) (map[string]map[string][]string, error)

GetMissedRevs with a given list of revisions returns ones that do not exists in the database. List example:

check_revs := map[string][]string{"document_id": []string{"rev1", "rev2"}}

func (*Database) GetRevsDiff

func (db *Database) GetRevsDiff(o map[string][]string) (map[string]map[string][]string, error)

GetRevsDiff returns the subset of those revs that do not correspond to stored in the database

func (*Database) GetRevsLimit

func (db *Database) GetRevsLimit() (count int, err error)

GetRevsLimit gets the current database revision limit

func (*Database) GetSecurity

func (db *Database) GetSecurity(o SecurityObject) error

GetSecurity fetches database security object

func (*Database) GetTempView

func (db *Database) GetTempView(_map, reduce string) (*ViewResult, error)

GetTempView return a pointer to ViewResult with data from temporary view based on map and reduce functions passed into parameters

func (*Database) Info

func (db *Database) Info() (*DBInfo, error)

Info returns DBInfo struct containing information about current database

func (*Database) Insert

func (db *Database) Insert(doc interface{}, batch, fullCommit bool) (id, rev string, err error)

Insert creates new document in database. If inserted struct does not contain `_id` field (you may set it using json tag) couchdb will generate itself _id for this document and return it to you with revision. `fullCommit` overrides commit policy of couchdb instance, preferred value is `false`, more - http://docs.couchdb.org/en/1.6.1/config/couchdb.html#couchdb/delayed_commits Note: client takes only exported fields of a document (also all json flags are supported)

func (*Database) InsertMany

func (db *Database) InsertMany(docs interface{}) ([]UpdateResult, error)

InsertMany is a shortcut to Update method. It saves documents to database, optional parameters are set to defaults. Consider use this method as primary insert operator

func (*Database) MustDeleteMany

func (db *Database) MustDeleteMany(docs interface{}) ([]UpdateResult, error)

MustDeleteMany acts same like DeleteMany but ensures all documents to be deleted

func (*Database) MustInsertMany

func (db *Database) MustInsertMany(docs interface{}) ([]UpdateResult, error)

MustInsertMany is a shortcut for Update method, acts like InsertMany but enshures atomicity of request.

func (*Database) Purge

func (db *Database) Purge(o map[string][]string) (*PurgeResult, error)

Purge permanently removes the referenses to deleted documents from the database

func (*Database) Put

func (db *Database) Put(id string, doc interface{}) (string, error)

Put creates new document with specified id or adds new revision to the existing one. Note: to add new revision you must specify the latest rev of the document you want to update, otherwise couchdb will answer 409(Conflict)

func (*Database) SaveAttachment

func (db *Database) SaveAttachment(id, rev string, a *Attachment) (map[string]interface{}, error)

SaveAttachment uploads given attachment to document

func (*Database) SetRevsLimit

func (db *Database) SetRevsLimit(count int) error

SetRevsLimit sets the current database revision limit

func (*Database) SetSecurity

func (db *Database) SetSecurity(o SecurityObject) error

SetSecurity sets database security object

func (*Database) Update

func (db *Database) Update(docs interface{}, atomic, updateRev, fullCommit bool) ([]UpdateResult, error)

Update represents bulk operations on couchdb instance. It's highly customizable and not considered to use in common ways, use InsertMany or MustInsertMany instead.

If you are inserting documents that have field that represent it's revision ensure that it has json tag "omitempty" otherwise coucbdb will generate an error

func (*Database) ViewCleanup

func (db *Database) ViewCleanup() error

ViewCleanup removes view index files that are no longer required by couchdb instance

type DatabaseChanges

type DatabaseChanges struct {
	LastSequence int             `json:"last_seq"`
	Rows         []DatabaseEvent `json:"results"`
}

DatabaseChanges represents all changes related to current database

type DatabaseEvent

type DatabaseEvent struct {
	Changes []map[string]string `json:"changes"`
	ID      string              `json:"id"`
	Seq     int                 `json:"seq"`
	Deleted bool                `json:"deleted"`
}

DatabaseEvent represents a single change to current database

type DatabaseSecurity

type DatabaseSecurity struct {
	DefaultSecurity
	// contains filtered or unexported fields
}

DatabaseSecurity is a default security object but referred to the database

func (*DatabaseSecurity) AddAdmin

func (sec *DatabaseSecurity) AddAdmin(login string) error

AddAdmin adds admin to database

func (*DatabaseSecurity) AddAdminRole

func (sec *DatabaseSecurity) AddAdminRole(role string) error

AddAdminRole adds admin role to database

func (*DatabaseSecurity) AddMember

func (sec *DatabaseSecurity) AddMember(login string) error

AddMember adds member to database

func (*DatabaseSecurity) AddMemberRole

func (sec *DatabaseSecurity) AddMemberRole(role string) error

AddMemberRole adds membse role to database

func (*DatabaseSecurity) DeleteAdmin

func (sec *DatabaseSecurity) DeleteAdmin(login string) error

DeleteAdmin deletes admin from database

func (*DatabaseSecurity) DeleteAdminRole

func (sec *DatabaseSecurity) DeleteAdminRole(role string) error

DeleteAdminRole deletes admin role from database

func (*DatabaseSecurity) DeleteMember

func (sec *DatabaseSecurity) DeleteMember(login string) error

DeleteMember deletes member from database

func (*DatabaseSecurity) DeleteMemberRole

func (sec *DatabaseSecurity) DeleteMemberRole(role string) error

DeleteMemberRole deletes member role to database

type DefaultSecurity

type DefaultSecurity struct {
	Admins  SecurityGroup `json:"admins"`
	Members SecurityGroup `json:"members"`
}

DefaultSecurity describes common security settings on a database

func (*DefaultSecurity) UpdateAdminRoles

func (bs *DefaultSecurity) UpdateAdminRoles(login string, delete bool) error

UpdateAdminRoles allows to add/delete admin role into security object

func (*DefaultSecurity) UpdateAdmins

func (bs *DefaultSecurity) UpdateAdmins(login string, delete bool) error

UpdateAdmins allows to add/delete admin into security object

func (*DefaultSecurity) UpdateMemberRoles

func (bs *DefaultSecurity) UpdateMemberRoles(login string, delete bool) error

UpdateMemberRoles allows to add/delete member role into security object

func (*DefaultSecurity) UpdateMembers

func (bs *DefaultSecurity) UpdateMembers(login string, delete bool) error

UpdateMembers allows to add/delete member role into security object

type Destination

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

Destination describes `id` of a document and allow to add some options to use in queries

func (*Destination) String

func (d *Destination) String() (url string)

type Error

type Error struct {
	StatusCode int
	URL        string
	Method     string
	ErrorCode  string
	Reason     string
}

Error is a general struct containing information about failed request

func (Error) Error

func (err Error) Error() string

stringify the error

type Options

type Options map[string]interface{}

Options allow to specify request parameters

type PurgeResult

type PurgeResult struct {
	PurgeSequence int                 `json:"purge_seq"`
	Purged        map[string][]string `json:"purged"`
}

PurgeResult provides object with result info of purge request

type ReplicationResult

type ReplicationResult struct {
	History        []map[string]interface{} `json:"history"`
	Ok             bool                     `json:"ok"`
	ReplicationVer int                      `json:"replication_id_version"`
	SessionID      string                   `json:"session_id"`
	SourceLastSeq  int                      `json:"source_last_seq"`
}

ReplicationResult provides information about replication request

type SecurityGroup

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

SecurityGroup is a part of database security object

type SecurityObject

type SecurityObject interface {
	UpdateAdmins(login string, delete bool) error
	UpdateMembers(login string, delete bool) error
	UpdateAdminRoles(role string, delete bool) error
	UpdateMemberRoles(role string, delete bool) error
}

SecurityObject describes a common methods used by security mechanism in couchdb

type Server

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

Server represents couchdb instance and holds connection to it

func Connect

func Connect(host string, port int, auth Auth, timeout time.Duration) (*Server, error)

Connect tries to connect to the couchdb server using given host, port and optionally Auth and default request timeout

func (*Server) Copy

func (srv *Server) Copy() (*Server, error)

Copy returns a copy of server connection with same settings and auth information but with it's own http client instance todo: move this method to private!?

func (*Server) CreateDB

func (srv *Server) CreateDB(name string) (*Database, error)

CreateDB creates database on couchdb instance and if successful returns it

func (*Server) CreateUser

func (srv *Server) CreateUser(user *UserRecord) error

CreateUser inserts user record to couchdb _users database

func (*Server) GetActiveTasks

func (srv *Server) GetActiveTasks(o interface{}) error

GetActiveTasks returns slice of maps describing tasks running on server

func (*Server) GetAllDBs

func (srv *Server) GetAllDBs() (dbList []string, err error)

GetAllDbs returns a list of databases present at the server

func (*Server) GetDBEvent

func (srv *Server) GetDBEvent(o interface{}, options Options) error

GetDBEvent block execution of program until any db event on couchdb instance happens and then unmarshall this event into given variable. Query parameters are equal to official docs:

http://docs.couchdb.org/en/1.6.1/api/server/common.html#db-updates

Note: `timeout` option accepts milliseconds instead of seconds

func (*Server) GetDBEventChan

func (srv *Server) GetDBEventChan() (c chan ServerEvent, err error)

GetDBEventChan returns channel that provides events happened on couchdb instance, it's thread safe to use in other goroutines. Also, you must close channel after all things done to release resourses and prevent memory leaks.

func (*Server) GetDatabase

func (srv *Server) GetDatabase(name string, auth Auth) (*Database, error)

GetDatabase checks existence of specified database on couchdb instance and return it

func (*Server) GetLog

func (srv *Server) GetLog(size int) (*bytes.Buffer, error)

GetLog returns you a buffer with given size, containing chunk from couchdb instance log file

func (*Server) GetMembership

func (srv *Server) GetMembership(o interface{}) error

GetMembership returns lists of cluster and all nodes

func (*Server) GetUUIDs

func (srv *Server) GetUUIDs(count int) ([]string, error)

GetUUIDs returns slice of uuids generated by couchdb instance

func (*Server) Info

func (srv *Server) Info() (*ServerInfo, error)

Info provides server information, also may be used to check server status

func (*Server) MustGetDatabase

func (srv *Server) MustGetDatabase(name string, auth Auth) (*Database, error)

MustGetDatabase return database instance if it's present on server or creates new one

func (*Server) NewSession

func (srv *Server) NewSession(user, pass string) (*Session, error)

NewSession authenticates user and returns Session struct containing current session token

func (*Server) Replicate

func (srv *Server) Replicate(source, target string, options Options) (*ReplicationResult, error)

Replicate provides replication management

func (*Server) Restart

func (srv *Server) Restart() error

Restart restarts couchdb instance, admin privileges may be required

func (*Server) Stats

func (srv *Server) Stats(path []string, o interface{}) error

Stats provides couchdb usage statistics statistics

type ServerEvent

type ServerEvent struct {
	Name string `json:"db_name"`
	Ok   bool   `json:"ok"`
	Type string `json:"type"`
}

ServerEvent represents couchdb instance information about databases

type ServerInfo

type ServerInfo struct {
	Message string      `json:"couchdb"`
	UUID    string      `json:"uuid"`
	Vendor  interface{} `json:"vendor"`
	Version string      `json:"version"`
}

ServerInfo provides couchdb instance inforation

type Session

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

Session stores authentication cookie for current user at the CouchDB instance

func (Session) AddAuthHeaders

func (s Session) AddAuthHeaders(req *http.Request)

AddAuthHeaders add cookie to request

func (*Session) Close

func (s *Session) Close() error

Close deletes current session

func (*Session) Info

func (s *Session) Info() (map[string]interface{}, error)

Info returns information about current session info

type UpdateResult

type UpdateResult struct {
	ID  string `json:"id"`
	Rev string `json:"rev"`
	Ok  bool   `json:"ok"`
}

UpdateResult contains information about bulk request

type UserRecord

type UserRecord struct {
	Login    string   `json:"name"`
	Type     string   `json:"type"`
	Roles    []string `json:"roles"`
	Password string   `json:"password"`
}

UserRecord is userd to create new user in couchdb instance

type ViewResult

type ViewResult struct {
	Offset    int                      `json:"offset"`
	Rows      []map[string]interface{} `json:"rows"`
	TotalRows int                      `json:"total_rows"`
	UpdateSeq int                      `json:"update_seq"`
}

ViewResult contains result of a view request

Jump to

Keyboard shortcuts

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