couchdb.client.Database

Package couchdb :: Module client :: Class Database |

# Class Database

    object --+
             |
            Database

Representation of a database on a CouchDB server.

    >>> server = Server('http://localhost:5984/')
    >>> db = server.create('python-tests')

New documents can be added to the database using the create() method:

    >>> doc_id = db.create({'type': 'Person', 'name': 'John Doe'})

This class provides a dictionary-like interface to databases: documents are retrieved by their ID using item access

    >>> doc = db[doc_id]
    >>> doc                 #doctest: +ELLIPSIS
    <Document '...'@... {...}>

Documents are represented as instances of the Row class, which is basically just a normal dictionary with the additional attributes `id` and `rev`:

    >>> doc.id, doc.rev     #doctest: +ELLIPSIS
    ('...', ...)
    >>> doc['type']
    'Person'
    >>> doc['name']
    'John Doe'

To update an existing document, you use item access, too:

    >>> doc['name'] = 'Mary Jane'
    >>> db[doc.id] = doc

The create() method creates a document with a random ID generated by CouchDB (which is not recommended). If you want to explicitly specify the ID, you'd use item access just as with updating:

    >>> db['JohnDoe'] = {'type': 'person', 'name': 'John Doe'}

    >>> 'JohnDoe' in db
    True
    >>> len(db)
    2

    >>> del server['python-tests']

Instance Methods
__init__(self, uri, name=None, http=None) x.__init__(...) initializes x; see x.__class__.__doc__ for signature |
__repr__(self) repr(x) |
__contains__(self, id) Return whether the database contains a document with the specified ID. |
__iter__(self) Return the IDs of all documents in the database. |
__len__(self) Return the number of documents in the database. |
__nonzero__(self) Return whether the database is available. |
__delitem__(self, id) Remove the document with the specified ID from the database. |
Document |
__getitem__(self, id) Return the document with the specified ID. |
__setitem__(self, id, content) Create or update a document with the specified ID. |
`unicode` |
create(self, data) Create a new document in the database with a random ID that is generated by the server. |
`bool` |
compact(self) Compact the database. |
`str` |
copy(self, src, dest) Copy the given document to create a new document. |
delete(self, doc) Delete the given document from the database. |
Document |
get(self, id, default=None, **options) Return the document with the specified ID. |
revisions(self, id, **options) Return all available revisions of the given document. |
`dict` |
info(self) Return information about the database as a dictionary. |
delete_attachment(self, doc, filename) Delete the specified attachment. |
get_attachment(self, id_or_doc, filename, default=None) Return an attachment from the specified doc id and filename. |
put_attachment(self, doc, content, filename=None, content_type=None) Create or replace an attachment. |
ViewResults |
query(self, map_fun, reduce_fun=None, language=`'``javascript``'`, wrapper=None, **options) Execute an ad-hoc query (a "temp view") against the database. |
`list` |
update(self, documents, **options) Perform a bulk update or insertion of the given documents using a single HTTP request. |
ViewResults |
view(self, name, wrapper=None, **options) Execute a predefined view. |
Inherited from `object`: `__delattr__`, `__format__`, `__getattribute__`, `__hash__`, `__new__`, `__reduce__`, `__reduce_ex__`, `__setattr__`, `__sizeof__`, `__str__`, `__subclasshook__`

Properties
basestring | name The name of the database.
Inherited from `object`: `__class__`

Method Details

### __init__(self, uri, name=None, http=None) (Constructor) |
x.__init__(...) initializes x; see x.__class__.__doc__ for signature Overrides: object.__init__ (inherited documentation)

### __repr__(self) (Representation operator) |
repr(x) Overrides: object.__repr__ (inherited documentation)

### __contains__(self, id) (In operator) |
Return whether the database contains a document with the specified ID. Parameters: `id` - the document ID Returns: `True` if a document with the ID exists, `False` otherwise

### __delitem__(self, id) (Index deletion operator) |
Remove the document with the specified ID from the database. Parameters: `id` - the document ID

### __getitem__(self, id) (Indexing operator) |
Return the document with the specified ID. Parameters: `id` - the document ID Returns: Document a Row object representing the requested document

### __setitem__(self, id, content) (Index assignment operator) |
Create or update a document with the specified ID. Parameters: `id` - the document ID `content` - the document content; either a plain dictionary for new documents, or a Row object for existing documents

### create(self, data) |
Create a new document in the database with a random ID that is generated by the server. Note that it is generally better to avoid the create() method and instead generate document IDs on the client side. This is due to the fact that the underlying HTTP `POST` method is not idempotent, and an automatic retry due to a problem somewhere on the networking stack may cause multiple documents being created in the database. To avoid such problems you can generate a UUID on the client side. Python (since version 2.5) comes with a `uuid` module that can be used for this:
    from uuid import uuid4
    doc_id = uuid4().hex
    db[doc_id] = {'type': 'person', 'name': 'John Doe'}
Parameters: `data` - the data to store in the document Returns: `unicode` the ID of the created document

### compact(self) |
Compact the database. This will try to prune all revisions from the database. Returns: `bool` a boolean to indicate whether the compaction was initiated successfully

### copy(self, src, dest) |
Copy the given document to create a new document. Parameters: `src` - the ID of the document to copy, or a dictionary or Document object representing the source document. `dest` - either the destination document ID as string, or a dictionary or Document instance of the document that should be overwritten. Returns: `str` the new revision of the destination document Since: 0.6

### delete(self, doc) |
Delete the given document from the database. Use this method in preference over `__del__` to ensure you're deleting the revision that you had previously retrieved. In the case the document has been updated since it was retrieved, this method will raise a ResourceConflict exception.
    >>> server = Server('http://localhost:5984/')
    >>> db = server.create('python-tests')
    >>> doc = dict(type='Person', name='John Doe')
    >>> db['johndoe'] = doc
    >>> doc2 = db['johndoe']
    >>> doc2['age'] = 42
    >>> db['johndoe'] = doc2
    >>> db.delete(doc)
    Traceback (most recent call last):
      ...
    ResourceConflict: ('conflict', 'Document update conflict.')
    >>> del server['python-tests']
Parameters: `doc` - a dictionary or Document object holding the document data Raises: `ResourceConflict` - if the document was updated in the database Since: 0.4.1

### get(self, id, default=None, **options) |
Return the document with the specified ID. Parameters: `id` - the document ID `default` - the default value to return when the document is not found Returns: Document a Row object representing the requested document, or `None` if no document with the ID was found

### revisions(self, id, **options) |
Return all available revisions of the given document. Parameters: `id` - the document ID Returns: an iterator over Document objects, each a different revision, in reverse chronological order, if any were found

### info(self) |
Return information about the database as a dictionary. The returned dictionary exactly corresponds to the JSON response to a `GET` request on the database URI. Returns: `dict` a dictionary of database properties Since: 0.4

### delete_attachment(self, doc, filename) |
Delete the specified attachment. Note that the provided `doc` is required to have a `_rev` field. Thus, if the `doc` is based on a view row, the view row would need to include the `_rev` field. Parameters: `doc` - the dictionary or Document object representing the document that the attachment belongs to `filename` - the name of the attachment file Since: 0.4.1

### get_attachment(self, id_or_doc, filename, default=None) |
Return an attachment from the specified doc id and filename. Parameters: `id_or_doc` - either a document ID or a dictionary or Document object representing the document that the attachment belongs to `filename` - the name of the attachment file `default` - default value to return when the document or attachment is not found Returns: the content of the attachment as a string, or the value of the `default` argument if the attachment is not found Since: 0.4.1

### put_attachment(self, doc, content, filename=None, content_type=None) |
Create or replace an attachment. Note that the provided `doc` is required to have a `_rev` field. Thus, if the `doc` is based on a view row, the view row would need to include the `_rev` field. Parameters: `doc` - the dictionary or Document object representing the document that the attachment should be added to `content` - the content to upload, either a file-like object or a string `filename` - the name of the attachment file; if omitted, this function tries to get the filename from the file-like object passed as the `content` argument value `content_type` - content type of the attachment; if omitted, the MIME type is guessed based on the file name extension Since: 0.4.1

### query(self, map_fun, reduce_fun=None, language=`'``javascript``'`, wrapper=None, **options) |
Execute an ad-hoc query (a "temp view") against the database.
    >>> server = Server('http://localhost:5984/')
    >>> db = server.create('python-tests')
    >>> db['johndoe'] = dict(type='Person', name='John Doe')
    >>> db['maryjane'] = dict(type='Person', name='Mary Jane')
    >>> db['gotham'] = dict(type='City', name='Gotham City')
    >>> map_fun = '''function(doc) {
    ...     if (doc.type == 'Person')
    ...         emit(doc.name, null);
    ... }'''
    >>> for row in db.query(map_fun):
    ...     print row.key
    John Doe
    Mary Jane
    >>> for row in db.query(map_fun, descending=True):
    ...     print row.key
    Mary Jane
    John Doe
    >>> for row in db.query(map_fun, key='John Doe'):
    ...     print row.key
    John Doe
    >>> del server['python-tests']
Parameters: `map_fun` - the code of the map function `reduce_fun` - the code of the reduce function (optional) `language` - the language of the functions, to determine which view server to use `wrapper` - an optional callable that should be used to wrap the result rows `options` - optional query string parameters Returns: ViewResults the view reults

### update(self, documents, **options) |
Perform a bulk update or insertion of the given documents using a single HTTP request.
    >>> server = Server('http://localhost:5984/')
    >>> db = server.create('python-tests')
    >>> for doc in db.update([
    ...     Document(type='Person', name='John Doe'),
    ...     Document(type='Person', name='Mary Jane'),
    ...     Document(type='City', name='Gotham City')
    ... ]):
    ...     print repr(doc) #doctest: +ELLIPSIS
    (True, '...', '...')
    (True, '...', '...')
    (True, '...', '...')
    >>> del server['python-tests']
The return value of this method is a list containing a tuple for every element in the `documents` sequence. Each tuple is of the form `(success, docid, rev_or_exc)`, where `success` is a boolean indicating whether the update succeeded, `docid` is the ID of the document, and `rev_or_exc` is either the new document revision, or an exception instance (e.g. ResourceConflict) if the update failed. If an object in the documents list is not a dictionary, this method looks for an `items()` method that can be used to convert the object to a dictionary. Effectively this means you can also use this method with schema.Document objects. Parameters: `documents` - a sequence of dictionaries or Document objects, or objects providing a `items()` method that can be used to convert them to a dictionary Returns: `list` an iterable over the resulting documents Since: version 0.2

### view(self, name, wrapper=None, **options) |
Execute a predefined view.
    >>> server = Server('http://localhost:5984/')
    >>> db = server.create('python-tests')
    >>> db['gotham'] = dict(type='City', name='Gotham City')
    >>> for row in db.view('_all_docs'):
    ...     print row.id
    gotham
    >>> del server['python-tests']
Parameters: `name` - the name of the view; for custom views, use the format `design_docid/viewname`, that is, the document ID of the design document and the name of the view, separated by a slash `wrapper` - an optional callable that should be used to wrap the result rows `options` - optional query string parameters Returns: ViewResults the view results

Property Details

### name The name of the database. Note that this may require a request to the server unless the name has already been cached by the info() method. Get Method: unreachable.name(self) - The name of the database. Type: basestring