couchdb

package module
v0.0.0-...-5704079 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2022 License: MIT Imports: 18 Imported by: 0

README

couchdb

Build Status Go Report Card Coverage Status GoDoc

CouchDB client for Go.

Example

package main

import (
	"log"

	"github.com/zemirco/couchdb"
)

func main() {
	u, err := url.Parse("http://127.0.0.1:5984/")
	if err != nil {
		panic(err)
	}
	// create a new client
	client, err := couchdb.NewClient(u)
	if err != nil {
		panic(err)
	}
	// get some information about your CouchDB
	info, err := client.Info()
	if err != nil {
		panic(err)
	}
	log.Println(info)

}

More examples.

Test

go test

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RandDBName

func RandDBName(length int) (string, error)

RandDBName returns random CouchDB database name. See the docs for database name rules. http://docs.couchdb.org/en/2.0.0/api/database/common.html#put--db

Types

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 describes attachments of a document. http://docs.couchdb.org/en/stable/api/document/common.html#attachments By using attachments you are also able to upload a document in multipart/related format. http://docs.couchdb.org/en/latest/api/document/common.html#creating-multiple-attachments

type BulkDoc

type BulkDoc struct {
	AllOrNothing bool       `json:"all_or_nothing,omitempty"`
	NewEdits     bool       `json:"new_edits,omitempty"`
	Docs         []CouchDoc `json:"docs"`
}

BulkDoc describes POST /db/_bulk_docs request object. http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_bulk_docs

type Client

type Client struct {
	Username  string
	Password  string
	BaseURL   *url.URL
	CookieJar *cookiejar.Jar
}

Client holds all info for database client

func NewAuthClient

func NewAuthClient(username, password string, u *url.URL) (*Client, error)

NewAuthClient returns new couchdb client with basic authentication

func NewClient

func NewClient(u *url.URL) (*Client, error)

NewClient returns new couchdb client for given url

func (*Client) ActiveTasks

func (c *Client) ActiveTasks() ([]Task, error)

ActiveTasks returns list of currently running tasks

func (*Client) All

func (c *Client) All() ([]string, error)

All returns list of all databases on server

func (*Client) Create

func (c *Client) Create(name string) (*DatabaseResponse, error)

Create database.

func (*Client) CreateSession

func (c *Client) CreateSession(name, password string) (*PostSessionResponse, error)

CreateSession creates a new session and logs in user

func (*Client) CreateUser

func (c *Client) CreateUser(user User) (*DocumentResponse, error)

CreateUser creates a new user in _users database

func (*Client) Delete

func (c *Client) Delete(name string) (*DatabaseResponse, error)

Delete database.

func (*Client) DeleteSession

func (c *Client) DeleteSession() (*DatabaseResponse, error)

DeleteSession removes current session and logs out user

func (*Client) DeleteUser

func (c *Client) DeleteUser(user *User) (*DocumentResponse, error)

DeleteUser removes user from database

func (*Client) Get

func (c *Client) Get(name string) (*DatabaseInfo, error)

Get database.

func (*Client) GetSession

func (c *Client) GetSession() (*GetSessionResponse, error)

GetSession returns session for currently logged in user

func (*Client) GetUser

func (c *Client) GetUser(name string) (*User, error)

GetUser returns user by given name

func (*Client) Info

func (c *Client) Info() (*Server, error)

Info returns some information about the server

func (*Client) Parse

func (c *Client) Parse(dirname string) ([]DesignDocument, error)

Parse takes a location and parses all design documents with corresponding views. The folder structure must look like this.

design
|-- player
|   |-- byAge
|   |   |-- map.js
|   |   `-- reduce.js
|   `-- byName
|       `-- map.js
`-- user
    |-- byEmail
    |   |-- map.js
    |   `-- reduce.js
    `-- byUsername
        `-- map.js

func (*Client) Replicate

func (c *Client) Replicate(req ReplicationRequest) (*ReplicationResponse, error)

Replicate sends POST request to the _replicate URL.

http://docs.couchdb.org/en/1.6.1/api/server/common.html#replicate

func (*Client) Request

func (c *Client) Request(method, uri string, data io.Reader, contentType string) (*http.Response, error)

Request creates new http request and does it.

func (*Client) Use

func (c *Client) Use(name string) DatabaseService

Use database.

type CouchDoc

type CouchDoc interface {
	GetID() string
	GetRev() string
}

CouchDoc describes interface for every couchdb document.

type Credentials

type Credentials struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

Credentials has information about POST _session form parameters. http://docs.couchdb.org/en/latest/api/server/authn.html#cookie-authentication

type Database

type Database struct {
	Client *Client
	Name   string
}

Database performs actions on certain database

func (*Database) AllDesignDocs

func (db *Database) AllDesignDocs() ([]DesignDocument, error)

AllDesignDocs returns all design documents from database. http://stackoverflow.com/questions/2814352/get-all-design-documents-in-couchdb

func (*Database) AllDocs

func (db *Database) AllDocs(params *QueryParameters) (*ViewResponse, error)

AllDocs returns all documents in selected database. http://docs.couchdb.org/en/latest/api/database/bulk-api.html

func (*Database) Bulk

func (db *Database) Bulk(docs []CouchDoc) ([]DocumentResponse, error)

Bulk allows to create and update multiple documents at the same time within a single request. The basic operation is similar to creating or updating a single document, except that you batch the document structure and information.

func (*Database) Delete

func (db *Database) Delete(doc CouchDoc) (*DocumentResponse, error)

Delete document.

func (*Database) Get

func (db *Database) Get(doc CouchDoc, id string) error

Get document.

func (*Database) GetSecurity

func (db *Database) GetSecurity() (*SecurityDocument, error)

GetSecurity returns security document. http://docs.couchdb.org/en/latest/api/database/security.html

func (*Database) Head

func (db *Database) Head(id string) (*http.Response, error)

Head request.

func (*Database) Post

func (db *Database) Post(doc CouchDoc) (*DocumentResponse, error)

Post document.

func (*Database) Purge

func (db *Database) Purge(req map[string][]string) (*PurgeResponse, error)

Purge permanently removes the references to deleted documents from the database.

http://docs.couchdb.org/en/1.6.1/api/database/misc.html

func (*Database) Put

func (db *Database) Put(doc CouchDoc) (*DocumentResponse, error)

Put document.

func (*Database) PutAttachment

func (db *Database) PutAttachment(doc CouchDoc, path string) (*DocumentResponse, error)

PutAttachment adds attachment to document

func (*Database) PutSecurity

func (db *Database) PutSecurity(secDoc SecurityDocument) (*DatabaseResponse, error)

PutSecurity sets the security object for the given database. http://docs.couchdb.org/en/latest/api/database/security.html#put--db-_security

func (*Database) Seed

func (db *Database) Seed(cache []DesignDocument) error

Seed makes sure all your design documents are up to date.

func (*Database) View

func (db *Database) View(name string) ViewService

View returns view for given name.

type DatabaseInfo

type DatabaseInfo struct {
	DbName             string `json:"db_name"`
	DocCount           int    `json:"doc_count"`
	DocDelCount        int    `json:"doc_del_count"`
	UpdateSeq          string `json:"update_seq"`
	PurgeSeq           string `json:"purge_seq"`
	CompactRunning     bool   `json:"compact_running"`
	DiskSize           int    `json:"disk_size"`
	DataSize           int    `json:"data_size"`
	InstanceStartTime  string `json:"instance_start_time"`
	DiskFormatVersion  int    `json:"disk_format_version"`
	CommittedUpdateSeq int    `json:"committed_update_seq"`
}

DatabaseInfo has info about the specified database. http://docs.couchdb.org/en/latest/api/database/common.html#get--db

type DatabaseResponse

type DatabaseResponse struct {
	Ok bool
}

DatabaseResponse is body for successful database calls.

type DatabaseService

type DatabaseService interface {
	AllDocs(params *QueryParameters) (*ViewResponse, error)
	AllDesignDocs() ([]DesignDocument, error)
	Head(id string) (*http.Response, error)
	Get(doc CouchDoc, id string) error
	Put(doc CouchDoc) (*DocumentResponse, error)
	Post(doc CouchDoc) (*DocumentResponse, error)
	Delete(doc CouchDoc) (*DocumentResponse, error)
	PutAttachment(doc CouchDoc, path string) (*DocumentResponse, error)
	Bulk(docs []CouchDoc) ([]DocumentResponse, error)
	Purge(req map[string][]string) (*PurgeResponse, error)
	GetSecurity() (*SecurityDocument, error)
	PutSecurity(secDoc SecurityDocument) (*DatabaseResponse, error)
	View(name string) ViewService
	Seed([]DesignDocument) error
}

DatabaseService is an interface for dealing with a single CouchDB database.

type DesignDocument

type DesignDocument struct {
	Document
	Language string                        `json:"language,omitempty"`
	Views    map[string]DesignDocumentView `json:"views,omitempty"`
	Filters  map[string]string             `json:"filters,omitempty"`
}

DesignDocument is a special type of CouchDB document that contains application code. http://docs.couchdb.org/en/latest/json-structure.html#design-document

func (DesignDocument) Name

func (dd DesignDocument) Name() string

Name returns design document name without the "_design/" prefix

type DesignDocumentView

type DesignDocumentView struct {
	Map    string `json:"map,omitempty"`
	Reduce string `json:"reduce,omitempty"`
}

DesignDocumentView contains map/reduce functions.

type Document

type Document struct {
	ID          string                `json:"_id,omitempty"`
	Rev         string                `json:"_rev,omitempty"`
	Attachments map[string]Attachment `json:"_attachments,omitempty"`
}

Document is base struct which should be embedded by any other couchdb document.

func (*Document) GetID

func (d *Document) GetID() string

GetID returns document id

func (*Document) GetRev

func (d *Document) GetRev() string

GetRev returns document revision

type DocumentResponse

type DocumentResponse struct {
	Ok  bool
	ID  string
	Rev string
}

DocumentResponse is response for multipart/related file upload.

type Element

type Element struct {
	Names []string `json:"names"`
	Roles []string `json:"roles"`
}

Element is single element inside Admins/Members in security document.

type Error

type Error struct {
	Method     string
	URL        string
	StatusCode int
	Type       string `json:"error"`
	Reason     string
}

Error describes CouchDB error.

func (*Error) Error

func (e *Error) Error() string

type GetSessionResponse

type GetSessionResponse struct {
	Info struct {
		Authenticated          string   `json:"authenticated"`
		AuthenticationDb       string   `json:"authentication_db"`
		AuthenticationHandlers []string `json:"authentication_handlers"`
	} `json:"info"`
	Ok          bool `json:"ok"`
	UserContext struct {
		Db    string   `json:"db"`
		Name  string   `json:"name"`
		Roles []string `json:"roles"`
	} `json:"userCtx"`
}

GetSessionResponse returns complete information about authenticated user. http://docs.couchdb.org/en/latest/api/server/authn.html#get--_session

type PostSessionResponse

type PostSessionResponse struct {
	Ok    bool
	Name  string
	Roles []string
}

PostSessionResponse is response from posting to session api.

type PurgeResponse

type PurgeResponse struct {
	PurgeSeq float64 `json:"purge_seq"`
	Purged   map[string][]string
}

PurgeResponse is response from POST request to the _purge URL.

type QueryParameters

type QueryParameters struct {
	Conflicts       *bool   `url:"conflicts,omitempty"`
	Descending      *bool   `url:"descending,omitempty"`
	Group           *bool   `url:"group,omitempty"`
	IncludeDocs     *bool   `url:"include_docs,omitempty"`
	Attachments     *bool   `url:"attachments,omitempty"`
	AttEncodingInfo *bool   `url:"att_encoding_info,omitempty"`
	InclusiveEnd    *bool   `url:"inclusive_end,omitempty"`
	Reduce          *bool   `url:"reduce,omitempty"`
	UpdateSeq       *bool   `url:"update_seq,omitempty"`
	GroupLevel      *int    `url:"group_level,omitempty"`
	Limit           *int    `url:"limit,omitempty"`
	Skip            *int    `url:"skip,omitempty"`
	Key             *string `url:"key,omitempty"`
	EndKey          *string `url:"endkey,comma,omitempty"`
	EndKeyDocID     *string `url:"end_key_doc_id,omitempty"`
	Stale           *string `url:"stale,omitempty"`
	StartKey        *string `url:"startkey,comma,omitempty"`
	StartKeyDocID   *string `url:"startkey_docid,omitempty"`
}

QueryParameters is struct to define url query parameters for design documents. http://docs.couchdb.org/en/latest/api/ddoc/views.html#db-design-design-doc-view-view-name

type RFC1123

type RFC1123 time.Time

RFC1123 is time format used by CouchDB for history fields. We have to define a custom type because Go uses RFC 3339 as default JSON time format.

https://golang.org/pkg/time/#Time.MarshalJSON http://docs.couchdb.org/en/1.6.1/api/server/common.html#replicate

func (*RFC1123) UnmarshalJSON

func (r *RFC1123) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

https://golang.org/pkg/encoding/json/#Unmarshaler

type Replication

type Replication struct {
	ReplicationRequest
	ReplicationState       string    `json:"_replication_state"`
	ReplicationStateTime   Timestamp `json:"_replication_state_time"`
	ReplicationStateReason string    `json:"_replication_state_reason"`
	ReplicationID          string    `json:"_replication_id"`
}

Replication is a document from the _replicator database. ReplicationState, ReplicationStateTime, ReplicationStateReason and ReplicationID are automatically updated by CouchDB.

http://docs.couchdb.org/en/1.6.1/replication/replicator.html#basics

type ReplicationHistory

type ReplicationHistory struct {
	DocWriteFailures float64 `json:"doc_write_failures"`
	DocsRead         float64 `json:"docs_read"`
	DocsWritten      float64 `json:"docs_written"`
	EndLastSeq       float64 `json:"end_last_seq"`
	EndTime          RFC1123 `json:"end_time"`
	MissingChecked   float64 `json:"missing_checked"`
	MissingFound     float64 `json:"missing_found"`
	RecordedSeq      float64 `json:"recorded_seq"`
	SessionID        string  `json:"session_id"`
	StartLastSeq     float64 `json:"start_last_seq"`
	StartTime        RFC1123 `json:"start_time"`
}

ReplicationHistory is part of the ReplicationResponse JSON object.

http://docs.couchdb.org/en/1.6.1/api/server/common.html#replicate

type ReplicationRequest

type ReplicationRequest struct {
	Document
	Cancel       bool              `json:"cancel,omitempty"`
	Continuous   bool              `json:"continuous,omitempty"`
	CreateTarget bool              `json:"create_target,omitempty"`
	DocIDs       []string          `json:"doc_ids,omitempty"`
	Proxy        string            `json:"proxy,omitempty"`
	Source       string            `json:"source,omitempty"`
	Target       string            `json:"target,omitempty"`
	Filter       string            `json:"filter,omitempty"`
	QueryParams  map[string]string `json:"query_params,omitempty"`
}

ReplicationRequest is JSON object for post request to _replicate URL.

http://docs.couchdb.org/en/1.6.1/api/server/common.html#replicate

type ReplicationResponse

type ReplicationResponse struct {
	History              []ReplicationHistory `json:"history"`
	Ok                   bool                 `json:"ok"`
	ReplicationIDVersion float64              `json:"replication_id_version"`
	SessionID            string               `json:"session_id"`
	SourceLastSeq        float64              `json:"source_last_seq"`
}

ReplicationResponse is JSON object for response from post request to _replicate URL.

http://docs.couchdb.org/en/1.6.1/api/server/common.html#replicate

type Row

type Row struct {
	ID    string                 `json:"id"`
	Key   interface{}            `json:"key"`
	Value interface{}            `json:"value,omitempty"`
	Doc   map[string]interface{} `json:"doc,omitempty"`
}

Row is single row inside design document query response.

type SecurityDocument

type SecurityDocument struct {
	Admins  Element `json:"admins"`
	Members Element `json:"members"`
}

SecurityDocument describes document _security document.

type Server

type Server struct {
	Couchdb string
	UUID    string
	Vendor  struct {
		Version string
		Name    string
	}
	Version string
}

Server gives access to the welcome string and version information. http://docs.couchdb.org/en/latest/intro/api.html#server

type Task

type Task struct {
	ChangesDone  int `json:"changes_done"`
	Database     string
	Pid          string
	Progress     int
	StartedOn    int `json:"started_on"`
	Status       string
	Task         string
	TotalChanges int `json:"total_changes"`
	Type         string
	UpdatedOn    int `json:"updated_on"`
}

Task describes currently running task. http://docs.couchdb.org/en/latest/api/server/common.html#active-tasks

type Timestamp

type Timestamp time.Time

Timestamp is time format used by CouchDB for the _replication_state_time field. It simply is a unix timestamp (number of seconds since 1 Jan 1970). We have to define our own custom type because Go uses RFC 3339 as default JSON time format.

ttp://docs.couchdb.org/en/latest/replication/replicator.html#basics

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

https://golang.org/pkg/encoding/json/#Unmarshaler

type User

type User struct {
	Document
	DerivedKey     string   `json:"derived_key,omitempty"`
	Name           string   `json:"name,omitempty"`
	Roles          []string `json:"roles"`
	Password       string   `json:"password,omitempty"`     // plain text password when creating the user
	PasswordSha    string   `json:"password_sha,omitempty"` // hashed password when requesting user information
	PasswordScheme string   `json:"password_scheme,omitempty"`
	Salt           string   `json:"salt,omitempty"`
	Type           string   `json:"type,omitempty"`
	Iterations     int      `json:"iterations,omitempty"`
}

User is special CouchDB document format. http://docs.couchdb.org/en/latest/intro/security.html#users-documents

func NewUser

func NewUser(name, password string, roles []string) User

NewUser returns new user instance.

type View

type View struct {
	URL    string
	Client *Client
}

View performs actions and certain view documents

func (*View) Get

func (v *View) Get(name string, params QueryParameters) (*ViewResponse, error)

Get executes specified view function from specified design document.

func (*View) Post

func (v *View) Post(name string, keys []string, params QueryParameters) (*ViewResponse, error)

Post executes specified view function from specified design document. Unlike View.Get for accessing views, View.Post supports the specification of explicit keys to be retrieved from the view results.

type ViewResponse

type ViewResponse struct {
	Offset    int   `json:"offset,omitempty"`
	Rows      []Row `json:"rows,omitempty"`
	TotalRows int   `json:"total_rows,omitempty"`
	UpdateSeq int   `json:"update_seq,omitempty"`
}

ViewResponse is response for querying design documents.

type ViewService

type ViewService interface {
	Get(name string, params QueryParameters) (*ViewResponse, error)
	Post(name string, keys []string, params QueryParameters) (*ViewResponse, error)
}

ViewService is an interface for dealing with a view inside a CouchDB database.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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