Databases

Once you have established a session with the server, you need a Database instance to access the data. A Database instance is an representation of a database on the server. Database instances allow to access Document instances. Also, Database instances can be used to configure the user and group permissions.

Getting a Database instance

While the constructor of the Database class can be used to get a representation of a specific database, the canonical way to get an instance are the member functions of the CouchDB class.

The following code returns an instance for the animals database.

animals = await session["animals"]

aiocouch only allows to get an instance for a database that exists on the server.

Creating new databases

To create a new database on the server, the create() method of the session object is used.

animals = await session.create("animals")

By default, aiocouch only allows to use the create method for a database that does not exist on the server.

Listing documents

The _all_docs view allows to retrieve all documents stored in a given database on the server. aiocouch also exposes this view as methods of the database class.

The method docs() allows to retrieve documents by a list of ids or all documents with ids matching a given prefix. Similar to a dict, all documents of a database can be iterated with the methods akeys(), and values().

To perform more sophisticated document selections, the method find() allows to search for documents matching the complex selector syntax of CouchDB.

Reference

class aiocouch.database.Database(couchdb, id)

A local representation for the referenced CouchDB database

An instance of this class represents a local copy of a CouchDB database. It allows to create and retrieve Document instances, as well as the iteration other many documents.

Variables

id – the id of the database

Parameters
  • couchdb (CouchDB) – The CouchDB connection session

  • id (str) – the id of the database

await __getitem__(id)

Returns the document with the given id

Raises

NotFoundError – if the given document does not exist

Parameters

id (str) – the name of the document

Return type

Document

Returns

a local copy of the document

async for ... in akeys(**params)

A generator returning the names of all documents in the database

Parameters

params (Any) – passed into aiohttp.ClientSession.request()

Return type

AsyncGenerator[str, None]

Returns

returns all document ids

property all_docs: aiocouch.view.AllDocsView

Returns the all_docs view of the database

Return type

AllDocsView

Returns

Description of returned object.

async for ... in changes(last_event_id=None, **params)

Listens for events made to documents of this database

This will return DeletedEvent and ChangedEvent for deleted and modified documents, respectively.

See also /db/_changes.

For convinience, the last-event-id parameter can also be passed as last_event_id.

Return type

AsyncGenerator[BaseChangeEvent, None]

await create(id, exists_ok=False, data=None)

Returns a local representation of a new document in the database

This method will check if a document with the given name already exists and return a Document instance.

This method does not create a document with the given name on the server. You need to call save() on the returned document.

Raises

ConflictError – if the document does not exist on the server

Parameters
  • id (str) – the name of the document

  • exists_ok (bool) – If True, do not raise a ConflictError if an document with the given name already exists. Instead return the existing document.

  • data (Optional[Dict[str, Any]]) – Description of parameter data. Defaults to None.

Return type

Document

Returns

returns a Document instance representing the requested document

async with create_docs(ids=[])

Create documents in bulk.

See Bulk operations.

Parameters

ids (List[str]) – list of document ids to be created

Return type

AbstractAsyncContextManager[BulkCreateOperation]

Returns

A context manager for the bulk operation

await delete()

Delete the database on the server

Send the request to delete the database and all of its documents.

Return type

None

async for ... in docs(ids=None, create=False, prefix=None, include_ddocs=False, **params)

A generator to iterator over all or a subset of documents in the database.

When neither of ids nor prefix are specified, all documents will be iterated. Only one of ids and prefix can be specified. By default, design documents are not included.

Parameters
  • ids (Optional[List[str]]) – Allows to iterate over a subset of documents by passing a list of document ids

  • create (bool) – If True, every document contained in ids, which doesn’t exist, will be represented by an empty Document instance.

  • prefix (Optional[str]) – Allows to iterator over a subset of documents by specifing a prefix that the documents must match.

  • include_ddocs (bool) – Include the design documents of the database.

  • params (Any) – Additional query parameters, see CouchDB view endpoint.

Return type

AsyncGenerator[Document, None]

async for ... in find(selector, limit=None, **params)

Fetch documents based on search criteria

This method allows to use the _find endpoint of the database.

This method supports all request paramters listed in _find.

Note

As this method returns Document s, which contain the complete data, the fields parameter is not supported.

Parameters

selector (type) – See selectors

Return type

AsyncGenerator[Document, None]

Returns

return all documents matching the passed selector.

await get(id, default=None, *, rev=None)

Returns the document with the given id

Raises
  • NotFoundError – if the given document does not exist and default is None

  • BadRequestError – if the given rev of the document is invalid or missing

Parameters
  • id (str) – the name of the document

  • default (Optional[Dict[str, Any]]) – if default is not None and the document does not exist on the server, a new Document instance, containing default as its contents, is returned. To create the document on the server, save() has to be called on the returned instance.

  • rev (Optional[str]) – The requested rev of the document. The requested rev might not or not anymore exist on the connected server.

Return type

Document

Returns

a local representation of the requested document

await index(index, **kwargs)

Create a new index on the database

This method allows to use the _index endpoint of the database.

This method supports all request paramters listed in _index.

Parameters
  • index (Dict[str, Any]) – JSON description of the index

  • kwargs (Any) – additional parameters, refer to the CouchDB documentation

Return type

Dict[str, Any]

Returns

The response of the CouchDB _index endpoint

await info()

Returns basic information about the database

See also GET /db.

Returns

Description of returned object.

Return type

def

async with update_docs(ids=[], create=False)

Update documents in bulk.

See Bulk operations.

Parameters
  • ids (List[str]) – list of affected documents, defaults to []

  • create (bool) – [description], defaults to False

Return type

AbstractAsyncContextManager[BulkUpdateOperation]

Returns

A context manager for the bulk operation

async for ... in values(**params)

Iterates over documents in the database

See docs().

Return type

AsyncGenerator[Document, None]

class aiocouch.event.BaseChangeEvent(json)

The base event for shared properties

property id: str

Returns the id of the document

Return type

str

json: Dict[str, Any]

The raw data of the event as JSON

property rev: str

Returns the new rev of the document

Return type

str

property sequence: str

Returns the sequence identifier of the event

Return type

str

class aiocouch.event.ChangedEvent(json, database)

This event denotes that the document got modified

database: aiocouch.database.Database

The database for reference

await doc()

Returns the document after the change

If the include_docs was set, this will use the data provided in the received event. Otherwise, the document is fetched from the server.

Return type

Document

class aiocouch.event.DeletedEvent(json)

This event denotes that the document got deleted