Module: Perfect-CouchDB
enum CouchDBError : Error
This enum type indicates an exception when dealing with a CouchDB database
case Error(code: Int, msg: String)
A CouchDB error code and message.
401 - Session authentication failed
1001 - Events error: Feed must be one of longpoll, continuous, or eventsource
class CouchDB
Main CouchDB Class
var debug: Bool = false
Boolean switch for enabling/disabling debug mode
func init(_ db: String)
Define a CouchDB database
- parameter db: String path to CouchDB database
func init(_ c: CouchDBConnector)
Define a CouchDB instance with a connector
- parameter c: CouchDBConnector object
func listDatabaseEvents(feed: String = "longpoll", timeout: Int = 60, heartbeat: Bool = true) throws -> (CouchDBResponse, [String:Any])
Server - List all database events
Query Parameters:
- feed (string) –
- longpoll: Closes the connection after the first event.
- continuous: Send a line of JSON per event. Keeps the socket open until timeout.
- eventsource: Like, continuous, but sends the events in EventSource format.
- timeout (number) – Number of seconds until CouchDB closes the connection. Default is 60.
- heartbeat (boolean) – Whether CouchDB will send a newline character (\n) on timeout. Default is true.
func listNodeMembership() -> (CouchDBResponse, [String:Any])
Server - List node membership
Displays the nodes that are part of the cluster as cluster_nodes. The field all_nodes displays all nodes this node knows about, including the ones that are part of the cluster. The endpoint is useful when setting up a cluster, see Node Management
func log(bytes: Int = 1000, offset: Int = 0) throws -> (CouchDBResponse, [String:Any])
Server - Retrieve Server log
Gets the CouchDB log, equivalent to accessing the local log file of the corresponding CouchDB instance.
func databaseExists(_ db: String) -> Bool
Check if Database Exists
Returns true / false
func databaseInfo(_ name: String = "") -> (CouchDBResponse, [String:Any])
Get Database Info
- committed_update_seq (number) – The number of committed update.
- compact_running (boolean) – Set to true if the database compaction routine is operating on this database.
- db_name (string) – The name of the database.
- disk_format_version (number) – The version of the physical format used for the data when it is stored on disk.
- data_size (number) – The number of bytes of live data inside the database file.
- disk_size (number) – The length of the database file on disk. Views indexes are not included in the calculation.
- doc_count (number) – A count of the documents in the specified database.
- doc_del_count (number) – Number of deleted documents
- instance_start_time (string) – Timestamp of when the database was opened, expressed in microseconds since the epoch.
- purge_seq (number) – The number of purge operations on the database.
- update_seq (number) – The current number of updates to the database.
Status Codes - 200 OK; 404 Not Found – Requested database not found
func addDoc(_ db: String = "", doc: Any) throws -> (CouchDBResponse, [String:Any])
Creates a new document in the specified database, using the supplied JSON document structure.
If the JSON structure includes the _id field, then the document will be created with the specified document ID.
If the _id field is not specified, a new unique ID will be generated, following whatever UUID algorithm is configured for that server.
Parameters:
- db: The database name
- doc: The document to be stored.
The stored document can be supplied as a JSON encoded string, or as a [String: Any] type.
Returns a tuple of CouchDBResponse and the returned JSON as [String:Any]
func filter(_ db: String = "", queryParams: CouchDBQuery) throws -> (CouchDBResponse, [String:Any])
Returns a JSON structure of all of the documents in a given database. The information is returned as a JSON structure containing meta information about the return structure, including a list of all documents and basic contents, consisting the ID, revision and key. The key is the from the document’s _id.
Uses the CouchDB _all_docs route

Parameters:
db – Database name
queryParams - CouchDBQuery type.

Response JSON Object:
offset (number) – Offset where the document list started
rows (array) – Array of view row objects. By default the information returned contains only the document ID and revision.
total_rows (number) – Number of documents in the database/view. Note that this is not the number of rows returned in the actual query.
update_seq (number) – Current update sequence for the database
func find(_ db: String = "", queryParams: CouchDBQuery) throws -> (CouchDBResponse, [String:Any])
Find documents using a declarative JSON querying syntax. Queries can use the built-in _all_docs index or custom indices, specified using the _index endpoint.

Query Parameters:
selector (json) – JSON object describing criteria used to select documents. More information provided in the section on selector syntax.
limit (number) – Maximum number of results returned. Default is 25. Optional
skip (number) – Skip the first ‘n’ results, where ‘n’ is the value specified. Optional
sort (json) – JSON array following sort syntax. Optional
fields (json) – JSON array specifying which fields of each object should be returned. If it is omitted, the entire object is returned. More information provided in the section on filtering fields. Optional
use_index (json) – Instruct a query to use a specific index. Specified either as "<design_document>" or ["<design_document>", "<index_name>"]. Optional
Response JSON Object:
docs (object) – Documents matching the selector
Status Codes:
200 OK – Request completed successfully
400 Bad Request – Invalid request
401 Unauthorized – Read permission required
500 Internal Server Error – Query execution error
func explain(_ db: String = "", queryParams: CouchDBQuery) throws -> (CouchDBResponse, [String:Any])
Query parameters are the same as find.

Response JSON Object:
dbname (string) – Name of database
index (object) – Index used to fullfil the query
selector (object) – Query selector used
opts (object) – Query options used
limit (number) – Limit parameter used
skip (number) – Skip parameter used
fields (object) – Fields to be returned by the query
range (object) – Range parameters passed to the underlying view

Status Codes:
200 OK – Request completed successfully
400 Bad Request – Invalid request
401 Unauthorized – Read permission required
500 Internal Server Error – Execution error
func get(
_ db: String = "",
docid: String,
attachments: Bool = false,
att_encoding_info: Bool = false,
atts_since: [String] = [String](),
conflicts: Bool = false,
deleted_conflicts: Bool = false,
latest: Bool = false,
local_seq: Bool = false,
meta: Bool = false,
open_revs: [String] = [String](),
rev: String = "",
revs: Bool = false,
revs_info: Bool = false
) throws -> (CouchDBResponse, [String:Any])
Returns document by the specified docid from the specified db. Unless you request a specific revision, the latest revision of the document will always be returned.

Parameters:
db – Database name
docid – Document ID

Query Parameters:
attachments (boolean) – Includes attachments bodies in response. Default is false
att_encoding_info (boolean) – Includes encoding information in attachment stubs if the particular attachment is compressed. Default is false.
atts_since (array) – Includes attachments only since specified revisions. Doesn’t includes attachments for specified revisions. Optional
conflicts (boolean) – Includes information about conflicts in document. Default is false
deleted_conflicts (boolean) – Includes information about deleted conflicted revisions. Default is false
latest (boolean) – Forces retrieving latest “leaf” revision, no matter what rev was requested. Default is false
local_seq (boolean) – Includes last update sequence for the document. Default is false
meta (boolean) – Acts same as specifying all conflicts, deleted_conflicts and open_revs query parameters. Default is false
open_revs (array) – Retrieves documents of specified leaf revisions. Additionally, it accepts value as all to return all leaf revisions. Optional
rev (string) – Retrieves document of specified revision. Optional
revs (boolean) – Includes list of all known document revisions. Default is false
revs_info (boolean) – Includes detailed information for all known document revisions. Default is false

Response JSON Object:
_id (string) – Document ID
_rev (string) – Revision MVCC token
_deleted (boolean) – Deletion flag. Available if document was removed
_attachments (object) – Attachment’s stubs. Available if document has any attachments
_conflicts (array) – List of conflicted revisions. Available if requested with conflicts=true query parameter
_deleted_conflicts (array) – List of deleted conflicted revisions. Available if requested with deleted_conflicts=true query parameter
_local_seq (string) – Document’s update sequence in current database. Available if requested with local_seq=true query parameter
_revs_info (array) – List of objects with information about local revisions and their status. Available if requested with open_revs query parameter
_revisions (object) – List of local revision tokens without. Available if requested with revs=true query parameter

Status Codes:
200 OK – Request completed successfully
304 Not Modified – Document wasn’t modified since specified revision
400 Bad Request – The format of the request or revision was invalid
401 Unauthorized – Read privilege required
404 Not Found – Document not found
func create(_ db: String = "", docid: String, doc: [String: Any]) throws -> (CouchDBResponse, [String:Any])
Creates a new named document, or creates a new revision of the existing document. Unlike the POST /{db}, you must specify the document ID in the request URL.
Parameters:
db – Database name
docid – Document ID
doc - [String: Any] object to be stored as JSON

Query Parameters:
batch (string) – Stores document in batch mode. Possible values: ok. Optional
new_edits (boolean) – Prevents insertion of a conflicting document. Possible values: true (default) and false. If false, a well-formed _rev must be included in the document. new_edits=false is used by the replicator to insert documents into the target database even if that leads to the creation of conflicts. Optional

Response JSON Object:
id (string) – Document ID
ok (boolean) – Operation status
rev (string) – Revision MVCC token

Status Codes:
201 Created – Document created and stored on disk
202 Accepted – Document data accepted, but not yet stored on disk
400 Bad Request – Invalid request body or parameters
401 Unauthorized – Write privileges required
404 Not Found – Specified database or document ID doesn’t exists
409 Conflict – Document with the specified ID already exists or specified revision is not latest for target document
func delete(_ db: String = "", docid: String, rev: String) throws -> (CouchDBResponse, [String:Any])
Marks the specified document as deleted by adding a field _deleted with the value true. Documents with this field will not be returned within requests anymore, but stay in the database. You must supply the current (latest) revision by using the rev parameter.
Note: CouchDB doesn’t completely delete the specified document. Instead, it leaves a tombstone with very basic information about the document. The tombstone is required so that the delete action can be replicated across databases.
Parameters:
db – Database name
docid – Document ID
rev - Actual document’s revision

Response JSON Object:
id (string) – Document ID
ok (boolean) – Operation status
rev (string) – Revision MVCC token

Status Codes:
200 OK – Document successfully removed
202 Accepted – Request was accepted, but changes are not yet stored on disk
400 Bad Request – Invalid request body or parameters
401 Unauthorized – Write privileges required
404 Not Found – Specified database or document ID doesn’t exists
409 Conflict – Specified revision is not the latest for target document
func copy(
_ db: String = "",
docid: String,
doc: [String:Any],
rev: String = "",
destination: String
) throws -> (CouchDBResponse, [String:Any])
The COPY (which is non-standard HTTP) copies an existing document to a new or existing document.
The source document is specified on the request line,
with the Destination header of the request specifying the target document.

Parameters:
db – Database name
docid – Document ID
rev (string) – Revision to copy from. Optional
destination – Destination document

Response JSON Object:
id (string) – Document document ID
ok (boolean) – Operation status
rev (string) – Revision MVCC token

Status Codes:
201 Created – Document successfully created
202 Accepted – Request was accepted, but changes are not yet stored on disk
400 Bad Request – Invalid request body or parameters
401 Unauthorized – Read or write privileges required
404 Not Found – Specified database, document ID or revision doesn’t exists
409 Conflict – Document with the specified ID already exists or specified revision is not latest for target document
func update(_ db: String = "", docid: String, doc: [String:Any], rev: String) throws -> (CouchDBResponse, [String:Any])
To update an existing document you must specify the current revision number within the _rev parameter.

Parameters:
db – Database name
docid – Document ID
doc – Document body as [String: Any]
rev – Document Revision

Response JSON Object:
id (string) – Document document ID
ok (boolean) – Operation status
rev (string) – Revision MVCC token
enum CouchDBAuthType
CouchDBAuthType provides a simple switch for how interaction is maintained over a connection's lifetime.
Options are: basic, and session
case none
None
No authentication by default
case basic
Basic
The main drawback is the need to send user credentials with each request which may be insecure and could hurt operation performance (since CouchDB must compute the password hash with every request)
case session
Session
CouchDB generates a token that the client can use for the next few requests to CouchDB. Tokens are valid until a timeout.
These are effectively Cookies but can also be handled via JSON
struct CouchDBAuthentication
Container struct for holding the CouchDB Authentication information
struct CouchDBConnector
Connector information.
var ssl: Bool = false
SSL mode enabled/disabled.
Default value: disabled (false)
var host: String = "localhost"
CouchDB Server hostname or IP address
Default: localhost
var port: Int = 5984
CouchDB Server port
Default: 5984
class CouchDBQuery
A container class for query params used in the _all_docs selection
var conflicts : Bool = false
conflicts (Bool) – Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false.
Used for an _all_docs / filter query only
var descending : Bool = false
descending (Bool) – Return the documents in descending by key order. Default is false.
Used for an _all_docs / filter query only
var endkey : String = ""
endkey (String) – Stop returning records when the specified key is reached. Optional.
Used for an _all_docs / filter query only
var endkey_docid : String = ""
endkey_docid (String) – Stop returning records when the specified document ID is reached. Optional.
Used for an _all_docs / filter query only
var include_docs : Bool = false
include_docs (Bool) – Include the full content of the documents in the return. Default is false.
Used for an _all_docs / filter query only
var inclusive_end : Bool = true
inclusive_end (Bool) – Specifies whether the specified end key should be included in the result. Default is true.
Used for an _all_docs / filter query only
var key : String = ""
key (String) – Return only documents that match the specified key. Optional.
Used for an _all_docs / filter query only
var keys : [String] = [String]()
keys ([String]) – Return only documents that match the specified keys. Optional.
Used for an _all_docs / filter query only
var limit : Int = 0
limit (Int) – Limit the number of the returned documents to the specified number. Optional.
var skip : Int = 0
skip (Int) – Skip this number of records before starting to return the results. Default is 0.
var stale : CouchDBQueryStale = .ignore
stale (CouchDBQueryStale) – Allow the results from a stale view to be used, without triggering a rebuild of all views within the encompassing design doc. Supported values: ok and update_after. Optional.
Used for an _all_docs / filter query only
var startkey : String = ""
startkey (String) – Return records starting with the specified key. Optional.
Used for an _all_docs / filter query only
var startkey_docid : String = ""
startkey_docid (String) – Return records starting with the specified document ID. Optional.
Used for an _all_docs / filter query only
var update_seq : Bool = false
update_seq (Bool) – Response includes an update_seq value indicating which sequence id of the underlying database the view reflects. Default is false.
Used for an _all_docs / filter query only
var selector = [String:Any]()
selector (json) – JSON object describing criteria used to select documents. More information provided in the section on selector syntax.
Used for an find query only
var sort = [String:Any]()
sort (json) – JSON array following sort syntax. Optional.
Used for an find query only
var fields = [String:Any]()
fields (json) – JSON array specifying which fields of each object should be returned. If it is omitted, the entire object is returned. More information provided in the section on filtering fields. Optional.
Used for an find query only
var use_index = [String:Any]()
use_index (json) – Instruct a query to use a specific index. Specified either as "<design_document>" or ["<design_document>", "<index_name>"]. Optional.
Used for an find query only
enum CouchDBResponse
case undefined
CouchDB HTTP Response Codes
Undefined.
case ok
Request completed successfully.
case created
Document created successfully.
case accepted
Request has been accepted, but the corresponding operation may not have completed. This is used for background operations, such as database compaction.
case notModified
The additional content requested has not been modified. This is used with the ETag system to identify the version of information returned.
case badRequest
Bad request structure. The error can indicate an error with the request URL, path or headers. Differences in the supplied MD5 hash and content also trigger this error, as this may indicate message corruption.
case unauthorized
The item requested was not available using the supplied authorization, or authorization was not supplied.
case forbidden
The requested item or operation is forbidden.
case notFound
The requested content could not be found. The content will include further information, as a JSON object, if available. The structure will contain two keys, error and reason. For example:
{"error":"not_found","reason":"no_db_file"}
case resourceNotAllowed
A request was made using an invalid HTTP request type for the URL requested. For example, you have requested a PUT when a POST is required. Errors of this type can also triggered by invalid URL strings.
case notAcceptable
The requested content type is not supported by the server.
case conflict
Request resulted in an update conflict.
case preconditionFailed
The request headers from the client and the capabilities of the server do not match.
case badContentType
The content types supported, and the content type of the information being requested or submitted indicate that the content type is not supported.
case requestedRangeNotSatisfiable
The range specified in the request header cannot be satisfied by the server.
case expectationFailed
When sending documents in bulk, the bulk load operation failed.
case internalServerError
The request was invalid, either because the supplied JSON was invalid, or invalid information was supplied as part of the request.
static func func statusFrom(_ code: Int) -> CouchDBResponse
converts an HTTP status code to the correct enum value
struct CouchDBResult
CouchDBResult is the individual document record
var id: String = ""
The id of the document
var var rev: String = ""
Document revision
var doc = [String: Any]()
The contents of the document
class HTTPHeaderParser
A lightweight HTTP Response Header Parser
transform the header into a dictionary with http status code
func init(header: String)
HTTPHeaderParser default constructor
- header: the HTTP response header string
var variables: [String:String]
HTTP response header information by keywords
var code: Int
The HTTP response code, e.g.,, HTTP/1.1 200 OK -> let code = 200
var status: String
The HTTP response code, e.g.,, HTTP/1.1 200 OK -> let status = "OK"
var version: String
The HTTP response code, e.g.,, HTTP/1.1 200 OK -> let version = "HTTP/1.1"