let

package module
Version: v0.0.0-...-3363091 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2015 License: Zlib Imports: 14 Imported by: 0

README

Let (Go) - Go <-> CouchDB

GoDoc

This is a work in progress. Consider it incomplete.

Current tests indicate the code is functional but bear in mind a major refactor and feature addition has just been committed. Consider the master branch to be unstable until further notice. This code is shared for general use/access rather than as a suggestion of stability.

It use currently used internally for prototype development and will expand as CouchDB 2.0 moves from developer preview into something more. It is being released to the public under the zlib/png licence as part of its development.

Things worth noting:

  • Targets CouchDB 2.0 (developer preview) and NOT the existing builds (1.6);
  • Has SSL/TLS support CouchDB SSL/TLS (albeit entirely untested);
  • Cookie Authentication (optional but tested);
  • Public mode (no auth/admin party);
  • Only Go built-ins are used.

The general approach

The approach adopted in this library is as follows:

  • The preference is to store, update, and iterate over pointers to objects (to avoid copying);
  • Everything should look a bit like this: <object>, err :=;
    • Errors are a good thing, checking if they are non-nil is all you should really need;
    • Errors are to be "cleaned up" if they match a known oddity (e.g. 404 status pages are translated into 403 "couchy" errors for a lack of access);
  • I speak British English (well, Australian English),
  • Access should be structured like the database (and layered like an Ogre). Thus it follows that:
    • Server objects contains databases;
    • Databases objects contain documents and design documents;
    • Design documents contain views (and other structures);
      • Design documents are first class citizens and no should use their own queries (back to the database);
    • Design document views have complex query syntax; * Views shouldn't reuse document access semantics, and should use their own direct GET calls (etc.);
      • Paginated views have the ability to step forward (Next()) or backward (Previous()), and need to be (re)loaded (Load());
      • Query objects are needed to keep views sane (View_Page_Query).
    • Documents (of all kinds) contain data but only resolve to ID (_id) and Revision (_rev), keeping the internal state as a string in the document object's fields (RawDocument);
      • Document semantics, structure, and manipulation should be done on a per-application level; this isn't Python, interface{} hacks are seriously ugly.

API

The API is let is designed to be as simple as possible.

The basics

To get a server:

// For non-TLS
server := let.Connect(couch_url)

// For TLS (this should be your default connection)
// Note: if the latter values are blank it will attempt non-TLS.
server := let.ConnectTLS(couch_url,
  path_to_cert_file,
  path_to_key_file,
  path_to_ca_file,
)

To authenticate (optional where your database or server doesn't need it):

// Authentication using Cookies
// Non-TLS fires this over a wire as expected, so keep that in mind.
server.SetCookieAuth(username, password)

// OAuth is presently unavailable as it seems to want you to sign in before
// you can sign in ... (I know, I thought the same thing.)

To get a database:

// Gets a database only if it exists
db, err := server.Get(name)

// Gets a database or creates it if it's missing
db, err := server.GetOrCreate(name)

// Creates a database (only if it doesn't exist)
db, err := server.Create(name)

To get a document:

// Gets a document from a given database
doc, err := db.Get(id)

To save:

// Saves []byte as a document
// _id and _rev are extracted using encoding/json and interface{}
// If no _rev is present or it's blank, _rev will be removed;
// If no _id is present, or it's blanked, _id will be given a UUID.
db.Save(json_as_byte_array)

Licence

The licence for this library is: zlib/png (see LICENCE).

This licence was selected for what it brings and what it does not restrict; it is a simple, clean, neat licence which allows the use of the library liberally.

Bugs

If you find one please file it. Better yet, if you know how to fix it, and have the time, please send a pull request with a fix.

Changes

  • 2015-10-12 - Pagination update

    • Summary
      • Minor changes to pagination to allow for the same code to be re-used (to a degree) elsewhere (e.g. _all_docs);
      • Renaming and interfacing of things (to prevent too many changes and to keep things consistent).
    • Added
      • Pagination related code;
        • Pagination interface (allowing the View pagination to remain largely unchanged);
        • PaginationJSON for common variables in non-reduced views/pagination instances.
      • AllDocuments and AllDocumentsQuery (to Database);
        • AllDocumentsPagination (using the Pagination interface);
    • Changed
      • NewViewQuery() -> NewQuery();
      • ViewPaginationQuery -> PaginationQuery;
      • ViewPagination now follows the interface.
  • 2015-10-11 - Minor update

    • Added
      • Bulk document object (BulkDocuments);
      • GetUUIDs(count) to the server interface.
      • Added directory for tests/suite (but still planning implementation).
    • Changed
      • Moved tests into subdirectories.
  • 2015-10-11 - Lint Update #2 (run to a confidence of 0.25)

    • Changed
      • Collapsed Copy into a direct call to CopyRevision;
      • Tweaked internals of Next and Previous for views;
      • Comment strings (in violation of the linter).
  • 2015-10-11 - Lint Update (prompted by using golint on the merged code)

    • Added
      • designdocumentrewrite.go
    • Changed - Breaking API changes (in compliance with linting)
      • Stylistic changes;
      • Added fmt.Errorf where relevant (retiring Sprintf + errors.New);
      • Functional changes (dropping else logic where irrelevant);
      • Collapsed all server related code into server.go;
      • Collapsed CopyLatest into a direct call to CopyRevision;
      • Split rewrite functionality into its own document (for future use);
      • Split options functionality into its own document (for future use);
      • Renamed all files to remove underscores (it does make them harder to read);
      • Renamed all internal HTTP functions (what I was trying to avoid with the underscore):
        • HTTP_GET -> HTTPGet;
        • HTTP_PUT -> HTTPPut;
        • HTTP_POST -> HTTPPost;
        • HTTP_DELETE -> HTTPDelete;
        • HTTP_COPY -> HTTPCopy;
        • HTTP_HEAD -> HTTPHead.
      • Renamed all underscore violations (31 violations);
        • Info_Database_Sizes -> DatabaseInfoSizes;
        • Info_Database_Other -> DatabaseInfoOther;
        • Info_Database -> DatabaseInfo;
        • DesignDocument_Options -> DesignDocumentOptions;
        • DesignDocumentRewrite -> DesignDocumentRewrite;
        • DesignDocumentInfo -> DesignDocumentInfo;
        • Info_DesignDocument_ViewIndex -> DesignDocumentViewIndexInfo;
        • DesignDocument_View -> DesignDocumentView;
        • DesignDocument_View_Row -> DesignDocumentViewRow;
        • ServerInfo_Vendor -> ServerInfoVendor;
        • Session_UserCtx -> SessionUserContext;
        • Session_Info -> SessionInfo;
        • View_Page -> ViewPagination;
        • View_Page_Query -> ViewPaginationQuery;
        • Various params (e.g. doc_id -> docID).
  • 2015-10-11

    • Added
      • Server IsAuthenticated() function (returns boolean);
      • FEATURES.md to better track things at a macro scale;
      • Document Copy() functionality (with CopyRevision and CopyLatest shortcuts/helpers);
      • Document Delete() functionality (with ForceDelete shortcut/helper).
    • Removed
      • Removed authentication timeout/removal (401/403/404) semantic catcher - users will now have to detect their own failed authentication states if in doubt.
  • 2015-10-10

    • Added
      • Public repository;
      • Stable API (I hope);
      • Weird semantics catch-all -- 404 arises where 403 should -- the document/database/url returns as missing when it is a redirect. Instead of moving the status and throwing the error let catches this and returns a 403 so you know why. This has been tweaked a bit to stop it from landing on pages it shouldn't;
      • Query object for Views (View_Page_Query, accessible via NewViewQuery());
      • Two quick/simple tests (let-doc-check.go, let-view-check.go).
    • Changed
      • Existing functions pushed into a sane API;
      • Massive refactor (moved things for a 'class-like' structuring) - all functions of objects are in their respective files; structs are in their respective files (etc.);
      • Fixed some comment strings and added status specificity to View_Page;
    • Removed
      • Server to document interfaces;
      • Database to view interfaces (now accessible via _design documents);
      • Database to pagination (now accessible via _view instances).
      • Ugly, strange, and hacky _design and _view semantics;
      • Various outdated tests;
      • That bamboozling comment over the old server object (now ConnectTLS) with the infinitive split by a gerund masquerading as an adverb (probably caused by hyperediting and the early fluid nature of the function);
      • Various (redundant) checks (e.g. _rev is no longer required in save (CouchDB error returns instead if the system is asked to find the error)).

TODO

  • Attachment support (I haven't needed it yet);
  • Some sort of test-suite;
    • Moved to automation.
  • Test SSL (another couple of VMs should do it);
  • Test behaviour with latency;
  • Clean up some internals, check for bottlenecks, {ref,pointer} <-> value mistakes are probably visible;
  • Document anything lacking/missing documentation (including the obvious things); also add 'doc.go' for clarity/header.
Structure/refactoring

Prior to release a few major changes were introduced. These introduced some inconsistencies beyond the 'hacky' nature of the code. A lot of the bad this brought about is here:

  • Make error handling a little more standard (fix let internal/deployed/release divides);
  • Do status checks;
  • Move to HTTP_<VERB> requests where appropriate.
Code cleanliness (and cleaning)

This began as internal hacky code for a given purpose; it was quite literally hacked together around basic HTTP call wrappers. TLS was added for HAProxy client authentication support, stripped, and then restored for HTTPS enabled CouchDB (and left untested). A lot of other changes ranging from minor shifts in design pattern to a rework of legacy functions into a structured approach mean there is probably a lot to be fixed. Here is how this is maintained:

  • Values are de/serialised into structures;
  • By default all structures are returned by pointer (avoiding replication when writing code using := assignment syntax);
  • Comments are removed as the component becomes stable enough, though some comments are retained for transparency.
"Working"

This list should appear to be in some sort of working order once the development branch gets updated/pushed/created.

  • Complex query semantics for pages with complex query syntax (most probably with the syntax of <Obj>_Query, following View_Page_Query);
  • Remainder of design document entries (helpers, etc.).
The Dream (aka the Wishlist)

The wishlist is derived from comments, fragments of code, and other things from within the repository.

  • Change watching utility/service (proposed: dir/name let/it):
    • Filters (to clear up the swirling storm inside);
    • Appropriate security: conceal/don't feel (appropriate 'rejection' without admitting to things existing/don't use forwards; throw a 404);
    • Optional rule system (no rules for me/kingdom of isolation).
  • Map/Reduce utility/service (name TBA):
    • Explore potential marshy areas around this idea.

It is worth noting that any let/it references found in the directory will be a dangling until internal and external code issues are fixed.

"Not on the list"

Things not being taken too seriously are ...

  • Any documented CouchDB API HEAD call (Sentential hasn't once used one of these calls; are these even in other libraries?);
  • OAuth (at least until it's fixed and doesn't require authentication to access the end-point ...).
Unplanned, unreleased, and disabled

This list is comprised predominantly of things that aren't actively testable or have shown themselves to be unstable in the last few months. The exceptions to this are the items listed on the watch list (below).

  • Various interfaces not currently used (because I won't know if they break!):
    • Complex view/design functions;
    • Helpers for populating views without constructing them manually.
Watch list

The following are points which are under observation and consideration. However, just because they are on the list does not mean they are potential candidates for inclusion; it merely indicates they are of some interest. (Candidates for inclusion will appear at some stage listed somewhere in this README).

  • OAuth currently requires authentication to be accessed (404 returns with a redirect);
  • Replication and other functions (some GET calls exist, but POST, PUT, etc., do not). Consider these disabled or partially implemented (and unlikely to be implemented in the near future). These will make the list when they are more testable within the environment (i.e. have a reason to be tested);
  • Design documents (additional features, shows, etc.) -- helpers.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AllDocumentsPagination

type AllDocumentsPagination struct {
	Pagination     // Interface
	PaginationJSON // JSON Variables used by pagination views

	Query *PaginationQuery `json:"-"` // Variables
	// contains filtered or unexported fields
}

AllDocumentsPagination is an object used for pagination of _all_docs.

func (*AllDocumentsPagination) Load

func (ad *AllDocumentsPagination) Load() error

Load retrieves data based on the current settings within the view.

func (*AllDocumentsPagination) Next

func (ad *AllDocumentsPagination) Next() error

Next performs a Load after moving skip forward based on the limit. If the limit is 0 nothing happens.

func (*AllDocumentsPagination) Previous

func (ad *AllDocumentsPagination) Previous() error

Previous performs a Load after moving skip back based on the limit. Where limit is 0 but skip is not the query just sets skip to 0 and loads.

type BulkDocuments

type BulkDocuments struct {
	Database     *Database               `json:"-"`
	AllOrNothing bool                    `json:"all_or_nothing"`
	NewEdits     bool                    `json:"new_edits"`
	Documents    []map[string]json.Token `json:"docs"`
}

BulkDocuments represents a collection of documents to be saved, updated, or added, in bulk. Contrary to the Save functions in let, BulkDocuments functions have no default safety on the Save function.

func (*BulkDocuments) Save

func (bd *BulkDocuments) Save() error

Save triggers a bulk save function sent to _bulk_docs.

type Database

type Database struct {
	Name string // name

	Info DatabaseInfo // Information
	// contains filtered or unexported fields
}

Database represents a CouchDB Database (tied to a Server object)

func (*Database) AllDocuments

func (db *Database) AllDocuments() (*AllDocumentsPagination, error)

AllDocuments returns a list of all documents (as per _all_docs)

func (*Database) AllDocumentsQuery

func (db *Database) AllDocumentsQuery(query *PaginationQuery) (*AllDocumentsPagination, error)

AllDocumentsQuery returns a list of all documents (as per _all_docs) based on the query object.

func (*Database) Get

func (db *Database) Get(id string, rev string) (doc *Document, err error)

Get retreives a document (if it exists), or an error if it does not. _id and _rev must be provided (via id and rev); a blank _rev will trigger the latest.

func (*Database) GetBulkDocumentObject

func (db *Database) GetBulkDocumentObject() *BulkDocuments

GetBulkDocumentObject returns an empty BulkDocuments object pointing to the given database.

func (*Database) GetByRevision

func (db *Database) GetByRevision(id string, revision string) (doc *Document, err error)

GetByRevision returns a document based on revision

func (*Database) GetDesignDocument

func (db *Database) GetDesignDocument(name string) (dd *DesignDocument, err error)

GetDesignDocument returns a given design document (if it exists).

func (*Database) GetLatest

func (db *Database) GetLatest(id string) (doc *Document, err error)

GetLatest gets the latest version of a document (if it exists). _id must be provided (via id)

func (*Database) NewDocument

func (db *Database) NewDocument() *Document

NewDocument creates an empty document bound to the database.

func (*Database) Save

func (db *Database) Save(b []byte) (doc *Document, err error)

Save triggers ad ocument save (based on serialised byte data).

func (*Database) UpdateInfo

func (db *Database) UpdateInfo() (err error)

UpdateInfo performs an update on the information (via GET request)

type DatabaseInfo

type DatabaseInfo struct {
	Name                 string            `json:"db_name"`             // Name of the database
	UpdateSequenceNumber string            `json:"update_seq"`          // The current number of updates to the database.
	Sizes                DatabaseInfoSizes `json:"sizes"`               // Sizes (not described in the docs (yet))
	PurgeSequenceNumber  uint64            `json:"purge_seq"`           // The number of purge operations on the database.
	Other                DatabaseInfoOther `json:"other"`               // Other (not described in the docs (yet))
	DocumentDeleteCount  uint64            `json:"doc_del_count"`       // Number of deleted documents
	DocumentCount        uint64            `json:"doc_count"`           // A count of the documents in the specified database.
	SizeOnDisk           uint64            `json:"disk_size"`           // The length of the database file on disk; Views indexes are not included in the calculation.
	DiskFormatVersion    uint64            `json:"disk_format_version"` // The version of the physical format used for; the data when it is stored on disk.
	DataSize             uint64            `json:"data_size"`           // The number of bytes of live data inside the database file.
	CompactRunning       bool              `json:"compact_running"`     // Set to true if the database compaction routine is operating on this database.
	InstanceStartTime    string            `json:"instance_start_time"` // Timestamp of when the database was opened, expressed in microseconds since the epoch.
}

DatabaseInfo is a json de/serialisation object JSON reply from CouchDB 2.0 - as of 2015/09/21

type DatabaseInfoOther

type DatabaseInfoOther struct {
	Size uint64 `json:"data_size"`
}

DatabaseInfoOther is a json de/serialisation object representing _info["other"]

type DatabaseInfoSizes

type DatabaseInfoSizes struct {
	File     uint64
	External uint64
	Active   uint64
}

DatabaseInfoSizes is a json de/serialisation object representing _info["sizes"].

type DatabaseUpdate

type DatabaseUpdate struct {
	// Database name
	DatabaseName string `json:"db_name"`

	// Event operation status
	OK bool

	// A database event; one of created, updated, deleted
	Type string
}

DatabaseUpdate is a Go struct representing _db_updates

type DesignDocument

type DesignDocument struct {
	Name string `json:"-"` // Design document name
	Path string `json:"-"` // Design document path

	Language           string                         `json:"language"`            // Language (defaults to JavaScript if missing)
	Options            DesignDocumentOptions          `json:"options"`             // Default options (not yet implemented)
	Filters            map[string]string              `json:"filters"`             // Key is the function name; value is a function's source (stringified)
	Lists              map[string]string              `json:"lists"`               // Key is the function name; value is a function's source (stringified)
	Rewrites           []*DesignDocumentRewrite       `json:"rewrites"`            // From/To (as per the docs)
	Shows              map[string]string              `json:"shows"`               // Key is the function name; value is a function's source (stringified)
	Updates            map[string]string              `json:"updates"`             // "Update functions definition"
	Views              map[string]*DesignDocumentView `json:"views"`               // Views
	ValidateDocUpdates string                         `json:"validate_doc_update"` // Validate document update function source; value is a function's source (stringified)
	// contains filtered or unexported fields
}

DesignDocument represents the data found in a design document.

func (*DesignDocument) GetView

func (dd *DesignDocument) GetView(name string) (*DesignDocumentView, error)

GetView obtains a design document.

func (*DesignDocument) Info

func (dd *DesignDocument) Info() (*DesignDocumentInfo, error)

Info returns `/db/_design/design-doc/_info`

func (*DesignDocument) Reload

func (dd *DesignDocument) Reload() (err error)

Reload triggers a reload.

func (*DesignDocument) Save

func (dd *DesignDocument) Save() (err error)

Save stores a design document (using raw data).

func (*DesignDocument) String

func (dd *DesignDocument) String() string

String performs stringification for sprintf (etc.)

type DesignDocumentInfo

type DesignDocumentInfo struct {
	Name      string                      `json:"name"`       // Name
	ViewIndex DesignDocumentViewIndexInfo `json:"view_index"` // View Index
}

DesignDocumentInfo represents values returned by `/db/_design/design-doc/_info`

type DesignDocumentOptions

type DesignDocumentOptions struct {
}

DesignDocumentOptions represents the Options stored within a design document.

type DesignDocumentRewrite

type DesignDocumentRewrite struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Method string `json:"method"`
	Query  string `json:"query"`
}

DesignDocumentRewrite represents a rewrite rule from a design document.

type DesignDocumentView

type DesignDocumentView struct {
	Name   string `json:"-"` // Name
	Map    string `json:"map"`
	Reduce string `json:"reduce"`
	// contains filtered or unexported fields
}

DesignDocumentView represents a view function from a design document.

func (*DesignDocumentView) Get

func (dv *DesignDocumentView) Get() (*ViewPagination, error)

Get returns the first page using default options (no skip, no key, no limit)

func (*DesignDocumentView) Query

Query uses a Query object (`PaginationQuery`) to perform a guided query.

func (*DesignDocumentView) Save

func (dv *DesignDocumentView) Save() (err error)

Save triggers a design document save (which should encompass the view)

func (*DesignDocumentView) String

func (dv *DesignDocumentView) String() string

String performs stringification for sprintf (etc.)

type DesignDocumentViewIndexInfo

type DesignDocumentViewIndexInfo struct {
	CompactRunning bool   `json:"compact_running"`
	DataSize       int    `json:"data_size"`
	DiskSize       int    `json:"disk_size"`
	Language       string `json:"language"`
	PurgeSequence  string `json:"purge_seq"`
	Signature      string `json:"signature"`
	UpdateSequence int    `json:"update_seq"`
	UpdaterRunning bool   `json:"updater_running"`
	WaitingClients int    `json:"waiting_clients"`
	WaitingCommit  bool   `json:"waiting_commit"`
}

DesignDocumentViewIndexInfo represents values returned by the view_index field of `/db/_design/design-doc/_info`

type DesignDocumentViewRow

type DesignDocumentViewRow struct {
	ID    string     `json:"id"`
	Key   json.Token `json:"key"`
	Value json.Token `json:"value"`
}

DesignDocumentViewRow represents a row of data within a view.

type Document

type Document struct {
	ID          string `json:"_id"`            // ID (_id) field
	Revision    string `json:"_rev,omitempty"` // Revision (_rev) field
	RawDocument string `json:"-"`              // Raw document as string (for printing or json-related use)
	// contains filtered or unexported fields
}

Document is a json de/serialisation object of a CouchDB document. It only contains _id and _rev; the RawDocument should be used by your application.

func (*Document) Copy

func (doc *Document) Copy(targetID string) (*Document, error)

Copy performs a copy based on the stored revision. The returned document pointer is to the NEW document

func (*Document) CopyLatest

func (doc *Document) CopyLatest(targetID string) (*Document, error)

CopyLatest performs a copy from the current document based on the latest revision. The returned document pointer is to the NEW document

func (*Document) CopyRevision

func (doc *Document) CopyRevision(revision string, targetID string) (*Document, error)

CopyRevision performs a copy from the current document based on the given revision. The returned document is the NEW document and not the current document.

func (*Document) Delete

func (doc *Document) Delete() bool

Delete attempts to remove the document based on the internal revision data. Errors are irrelevent here; all the user needs is 'did it happen?'

func (*Document) ForceDelete

func (doc *Document) ForceDelete() bool

ForceDelete attempts to remove the document regardless of revision.

func (*Document) GetRevisions

func (doc *Document) GetRevisions() (revs map[string]string, err error)

GetRevisions performs a revs_info lookup to find all available revisions.

func (*Document) LatestRevision

func (doc *Document) LatestRevision() string

LatestRevision fetches the highest revision value. In the event of a collision the first found will be returned.

func (*Document) Load

func (doc *Document) Load() error

Load retrieves the RawDocument data for processing (based on ID and Revision fields)

func (*Document) Save

func (doc *Document) Save(b []byte) (err error)

Save stores the document based on raw data; this will overwrite the RawDocument and update _id and _rev on success. If _id and/or _rev or invalid they will be added, updated, or removed (as appropriate).

func (*Document) SaveRaw

func (doc *Document) SaveRaw() bool

SaveRaw saves the document based on current content (RawDocument). If successful it will do an internal update; on failure it returns false. This is a semi-legacy interface; it has been kept for weird use-cases.

As with delete a fault is logged if present. Errors are irrelevent here; all the user needs is 'did it happen?'

type Pagination

type Pagination interface {
	Load() error     // Data is loaded.
	Next() error     // Skip moves up by limit and the next page is loaded.
	Previous() error // Skip moves down by limit (or to 0) and the previous page is loaded.
}

Pagination is an interface which is designed to cover all common pagination requests.

type PaginationJSON

type PaginationJSON struct {
	Total int                      `json:"total_rows"` // total_rows field
	Skip  int                      `json:"offset"`     // offset field
	Rows  []*DesignDocumentViewRow `json:"rows"`       // rows field
}

PaginationJSON describes common variables

type PaginationQuery

type PaginationQuery struct {
	Conflicts              bool
	Descending             bool
	EndKey                 string
	EndKeyDocID            string
	Group                  bool
	GroupLevel             int
	IncludeDocuments       bool
	Attachments            bool
	AttachmentEncodingInfo bool
	InclusiveEnd           bool
	Key                    string
	Keys                   []string
	Limit                  int
	Reduce                 bool
	Skip                   int
	Stale                  string
	StartKey               string
	StartKeyDocID          string
	UpdateSequence         bool
}

PaginationQuery represents the full range of options which may be queried. See: http://docs.couchdb.org/en/latest/api/ddoc/views.html

func NewQuery

func NewQuery() *PaginationQuery

NewQuery creates a new query (for pagination)

func (*PaginationQuery) String

func (pq *PaginationQuery) String() string

String turns a pagination query into a string (using fmt.Sprintf)

type Server

type Server struct {
	// In the format of http(s)://<host>:<port>(/<prefix>)
	// Should not contain a trailing slash;
	// prefix only where required (multiple DBs on the virtual hosts, etc.)
	ServerURL string

	// HTTP Client
	ClientHTTP *http.Client
	// contains filtered or unexported fields
}

Server connection (non-SSL)

func Connect

func Connect(uri string) (server *Server, err error)

Connect creates a server connection without TLS

func ConnectTLS

func ConnectTLS(uri string, certFile string,
	keyFile string, caFile string) (server *Server, err error)

ConnectTLS creates a server connection with TLS is available; if the TLS fields are blank (i.e. "") a non-TLS connection is used.

This connection call should be used when the application is unsure and is using a configuration file to load the server.

func (*Server) Create

func (server *Server) Create(name string) (db *Database, err error)

Create attempts to create a database of a given name.

func (*Server) Delete

func (server *Server) Delete(db *Database) (err error)

Delete removes a database

func (*Server) DoCookieAuth

func (server *Server) DoCookieAuth() (err error)

DoCookieAuth performs the authentication (based on stored credentials). Typically `SetCookieAuth` should be used directly; this function should only be used to handle authentication timeouts (verifiable using `IsAuthenticated`).

func (*Server) Exists

func (server *Server) Exists(name string) (exists bool)

Exists checks if the database exists.

func (*Server) Get

func (server *Server) Get(name string) (db *Database, err error)

Get returns an existing database (it does not attempt to create if the requested database is not found).

func (*Server) GetActiveTasks

func (server *Server) GetActiveTasks() (tasks []ServerActiveTask, err error)

GetActiveTasks returns a list of active server tasks. This is currently untested and has been drafted based on documentation.

func (*Server) GetAllDatabaseUpdates

func (server *Server) GetAllDatabaseUpdates() (updates []DatabaseUpdate, err error)

GetAllDatabaseUpdates lists all updates from _db_updates using a list of DatabaseUpdate objects.

func (*Server) GetAllDatabases

func (server *Server) GetAllDatabases() (names []string, err error)

GetAllDatabases returns a list of database names based on _all_dbs; the results may vary based on access control.

func (*Server) GetMembership

func (server *Server) GetMembership() (memberships map[string][]string, err error)

GetMembership returns membership information from the _membership API call. It appears to function as intended.

func (*Server) GetOrCreate

func (server *Server) GetOrCreate(name string) (db *Database, err error)

GetOrCreate gets a database of the given name; it is created if it is not found and access allows.

func (*Server) GetSession

func (server *Server) GetSession() (ses *Session, err error)

GetSession gets the current user's session information (or nil and an error if the user is not authenticated).

func (*Server) GetUUID

func (server *Server) GetUUID() (string, error)

GetUUID gets a single UUID from the server generator. This function is used by internal functions to avoid using POST for document creation.

func (*Server) GetUUIDs

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

GetUUIDs returns a number of UUIDs from the server.

func (*Server) HTTPCopy

func (server *Server) HTTPCopy(path string, destinationDocumentID string) (status int, header *http.Header, body string, err error)

HTTPCopy performs the 'COPY' requests returning status code, headers, body, and error (if any).

func (*Server) HTTPDelete

func (server *Server) HTTPDelete(path string) (status int, header *http.Header, body string, err error)

HTTPDelete performs the 'DELETE' requests returning status code, headers, body, and error (if any).

func (*Server) HTTPGet

func (server *Server) HTTPGet(path string) (status int, header *http.Header, body string, err error)

HTTPGet performs the 'GET' requests returning status code, headers, body, and error (if any). path must include the query (if required)

func (*Server) HTTPHead

func (server *Server) HTTPHead(path string) (status int, header *http.Header, err error)

HTTPHead performs the 'HEAD' requests returning status code, headers, and error (if any).

func (*Server) HTTPPost

func (server *Server) HTTPPost(path string, inBody io.Reader) (status int, header *http.Header, body string, err error)

HTTPPost performs the 'POST' requests returning status code, headers, body, and error (if any).

func (*Server) HTTPPut

func (server *Server) HTTPPut(path string, inBody io.Reader) (status int, header *http.Header, body string, err error)

HTTPPut performs the 'PUT' requests returning status code, headers, body, and error (if any).

func (*Server) Info

func (server *Server) Info() (info *ServerInfo, err error)

Info gets basic server information

func (*Server) IsAuthenticated

func (server *Server) IsAuthenticated() bool

IsAuthenticated is a trivial GetSession wrapper to check for an authenticated state against _session.

func (*Server) Replicate

func (server *Server) Replicate(source string, target string) (err error)

Replicate performs replication between a source and target. This function is untested and has been created based on the documentation.

func (*Server) SetCookieAuth

func (server *Server) SetCookieAuth(username string, password string)

SetCookieAuth stores and attempts to use the username and password for authentication.

type ServerActiveTask

type ServerActiveTask struct {

	//Processed changes
	ChangesDone uint64 `json:"changes_done"`

	// Source database
	Database string

	// Process ID
	PID string

	// Current percentage progress (0-100)
	Progress uint8

	// Task start time as unix timestamp
	StartedOn uint64 `json:"started_on"`

	// Task status message
	Status string

	// Task name
	Task string

	// Total changes to process
	TotalChanges uint64 `json:"total_changes"`

	// Operation Type
	Type string

	// Unix timestamp of last operation update
	UpdatedOn uint64 `json:"updated_on"`
}

ServerActiveTask is a representation of the json data Currently unknown if this works.

type ServerInfo

type ServerInfo struct {
	// Messaage
	CouchDB string

	// UUID
	Version string

	// Vendor information
	Vendor ServerInfoVendor
}

ServerInfo provides basic server information.

type ServerInfoVendor

type ServerInfoVendor struct {
	// Typically "The Apache Software Foundation"
	Name string
}

ServerInfoVendor provides basic information about the vendor of the build.

type Session

type Session struct {
	Ok       bool
	UserData SessionUserContext `json:"userCtx"`
}

Session represents CouchDB session information from _session.

type SessionUserContext

type SessionUserContext struct {
	Name  string
	Roles []string
}

SessionUserContext represents the userCtx information from _session.

type ViewPagination

type ViewPagination struct {
	Pagination                  // Interface
	Query      *PaginationQuery // Variables

	PaginationJSON // JSON Variables used by pagination views
	// contains filtered or unexported fields
}

ViewPagination is an object used for pagination of a view.

func (*ViewPagination) Load

func (vp *ViewPagination) Load() error

Load retrieves data based on the current settings within the view.

func (*ViewPagination) Next

func (vp *ViewPagination) Next() error

Next performs a Load after moving skip forward based on the limit. If the limit is 0 nothing happens.

func (*ViewPagination) Previous

func (vp *ViewPagination) Previous() error

Previous performs a Load after moving skip back based on the limit. Where limit is 0 but skip is not the query just sets skip to 0 and loads.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL