1.. Licensed under the Apache License, Version 2.0 (the "License"); you may not
2.. use this file except in compliance with the License. You may obtain a copy of
3.. the License at
4..
5..   http://www.apache.org/licenses/LICENSE-2.0
6..
7.. Unless required by applicable law or agreed to in writing, software
8.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10.. License for the specific language governing permissions and limitations under
11.. the License.
12
13.. _api/db:
14
15=======
16``/db``
17=======
18
19.. http:head:: /{db}
20    :synopsis: Checks the database existence
21
22    Returns the HTTP Headers containing a minimal amount of information
23    about the specified database. Since the response body is empty, using the
24    HEAD method is a lightweight way to check if the database exists already or
25    not.
26
27    :param db: Database name
28    :code 200: Database exists
29    :code 404: Requested database not found
30
31    **Request**:
32
33    .. code-block:: http
34
35        HEAD /test HTTP/1.1
36        Host: localhost:5984
37
38    **Response**:
39
40    .. code-block:: http
41
42        HTTP/1.1 200 OK
43        Cache-Control: must-revalidate
44        Content-Type: application/json
45        Date: Mon, 12 Aug 2013 01:27:41 GMT
46        Server: CouchDB (Erlang/OTP)
47
48.. http:get:: /{db}
49    :synopsis: Returns the database information
50
51    Gets information about the specified database.
52
53    :param db: Database name
54    :<header Accept: - :mimetype:`application/json`
55                     - :mimetype:`text/plain`
56    :>header Content-Type: - :mimetype:`application/json`
57                           - :mimetype:`text/plain; charset=utf-8`
58    :>json number cluster.n: Replicas. The number of copies of every document.
59    :>json number cluster.q: Shards. The number of range partitions.
60    :>json number cluster.r: Read quorum. The number of consistent copies
61      of a document that need to be read before a successful reply.
62    :>json number cluster.w: Write quorum. The number of copies of a document
63      that need to be written before a successful reply.
64    :>json boolean compact_running: Set to ``true`` if the database compaction
65      routine is operating on this database.
66    :>json string db_name: The name of the database.
67    :>json number disk_format_version: The version of the physical format used
68      for the data when it is stored on disk.
69    :>json number doc_count: A count of the documents in the specified
70      database.
71    :>json number doc_del_count: Number of deleted documents
72    :>json string instance_start_time: Always ``"0"``. (Returned for legacy
73      reasons.)
74    :>json string purge_seq: An opaque string that describes the purge state
75      of the database. Do not rely on this string for counting the number
76      of purge operations.
77    :>json number sizes.active: The size of live data inside the database, in
78      bytes.
79    :>json number sizes.external: The uncompressed size of database contents
80      in bytes.
81    :>json number sizes.file: The size of the database file on disk in bytes.
82      Views indexes are not included in the calculation.
83    :>json string update_seq: An opaque string that describes the state
84      of the database. Do not rely on this string for counting the number
85      of updates.
86    :>json boolean props.partitioned: (optional) If present and true, this
87      indicates that the database is partitioned.
88    :code 200: Request completed successfully
89    :code 404: Requested database not found
90
91    **Request**:
92
93    .. code-block:: http
94
95        GET /receipts HTTP/1.1
96        Accept: application/json
97        Host: localhost:5984
98
99    **Response**:
100
101    .. code-block:: http
102
103        HTTP/1.1 200 OK
104        Cache-Control: must-revalidate
105        Content-Length: 258
106        Content-Type: application/json
107        Date: Mon, 12 Aug 2013 01:38:57 GMT
108        Server: CouchDB (Erlang/OTP)
109
110        {
111            "cluster": {
112                "n": 3,
113                "q": 8,
114                "r": 2,
115                "w": 2
116            },
117            "compact_running": false,
118            "db_name": "receipts",
119            "disk_format_version": 6,
120            "doc_count": 6146,
121            "doc_del_count": 64637,
122            "instance_start_time": "0",
123            "props": {},
124            "purge_seq": 0,
125            "sizes": {
126                "active": 65031503,
127                "external": 66982448,
128                "file": 137433211
129            },
130            "update_seq": "292786-g1AAAAF..."
131        }
132
133.. http:put:: /{db}
134    :synopsis: Creates a new database
135
136    Creates a new database. The database name ``{db}`` must be composed by
137    following next rules:
138
139    -  Name must begin with a lowercase letter (``a-z``)
140
141    -  Lowercase characters (``a-z``)
142
143    -  Digits (``0-9``)
144
145    -  Any of the characters ``_``, ``$``, ``(``, ``)``, ``+``, ``-``, and
146       ``/``.
147
148    If you're familiar with `Regular Expressions`_, the rules above could be
149    written as ``^[a-z][a-z0-9_$()+/-]*$``.
150
151    :param db: Database name
152    :query integer q: Shards, aka the number of range partitions. Default is
153      8, unless overridden in the :config:option:`cluster config <cluster/q>`.
154    :query integer n: Replicas. The number of copies of the database in the
155      cluster. The default is 3, unless overridden in the
156      :config:option:`cluster config <cluster/n>` .
157    :query boolean partitioned: Whether to create a partitioned database.
158      Default is false.
159    :<header Accept: - :mimetype:`application/json`
160                     - :mimetype:`text/plain`
161    :>header Content-Type: - :mimetype:`application/json`
162                           - :mimetype:`text/plain; charset=utf-8`
163    :>header Location: Database URI location
164    :>json boolean ok: Operation status. Available in case of success
165    :>json string error: Error type. Available if response code is ``4xx``
166    :>json string reason: Error description. Available if response code is
167      ``4xx``
168    :code 201: Database created successfully (quorum is met)
169    :code 202: Accepted (at least by one node)
170    :code 400: Invalid database name
171    :code 401: CouchDB Server Administrator privileges required
172    :code 412: Database already exists
173
174    **Request**:
175
176    .. code-block:: http
177
178        PUT /db HTTP/1.1
179        Accept: application/json
180        Host: localhost:5984
181
182    **Response**:
183
184    .. code-block:: http
185
186        HTTP/1.1 201 Created
187        Cache-Control: must-revalidate
188        Content-Length: 12
189        Content-Type: application/json
190        Date: Mon, 12 Aug 2013 08:01:45 GMT
191        Location: http://localhost:5984/db
192        Server: CouchDB (Erlang/OTP)
193
194        {
195            "ok": true
196        }
197
198    If we repeat the same request to CouchDB, it will response with :code:`412`
199    since the database already exists:
200
201    **Request**:
202
203    .. code-block:: http
204
205        PUT /db HTTP/1.1
206        Accept: application/json
207        Host: localhost:5984
208
209    **Response**:
210
211    .. code-block:: http
212
213        HTTP/1.1 412 Precondition Failed
214        Cache-Control: must-revalidate
215        Content-Length: 95
216        Content-Type: application/json
217        Date: Mon, 12 Aug 2013 08:01:16 GMT
218        Server: CouchDB (Erlang/OTP)
219
220        {
221            "error": "file_exists",
222            "reason": "The database could not be created, the file already exists."
223        }
224
225    If an invalid database name is supplied, CouchDB returns response with
226    :code:`400`:
227
228    **Request**:
229
230    .. code-block:: http
231
232        PUT /_db HTTP/1.1
233        Accept: application/json
234        Host: localhost:5984
235
236    **Request**:
237
238    .. code-block:: http
239
240        HTTP/1.1 400 Bad Request
241        Cache-Control: must-revalidate
242        Content-Length: 194
243        Content-Type: application/json
244        Date: Mon, 12 Aug 2013 08:02:10 GMT
245        Server: CouchDB (Erlang/OTP)
246
247        {
248            "error": "illegal_database_name",
249            "reason": "Name: '_db'. Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed. Must begin with a letter."
250        }
251
252.. http:delete:: /{db}
253    :synopsis: Deletes an existing database
254
255    Deletes the specified database, and all the documents and attachments
256    contained within it.
257
258    .. note::
259        To avoid deleting a database, CouchDB will respond with the HTTP status
260        code 400 when the request URL includes a ?rev= parameter. This suggests
261        that one wants to delete a document but forgot to add the document id
262        to the URL.
263
264    :param db: Database name
265    :<header Accept: - :mimetype:`application/json`
266                     - :mimetype:`text/plain`
267    :>header Content-Type: - :mimetype:`application/json`
268                           - :mimetype:`text/plain; charset=utf-8`
269    :>json boolean ok: Operation status
270    :code 200: Database removed successfully (quorum is met and database is deleted by at least one node)
271    :code 202: Accepted (deleted by at least one of the nodes, quorum is not met yet)
272    :code 400: Invalid database name or forgotten document id by accident
273    :code 401: CouchDB Server Administrator privileges required
274    :code 404: Database doesn't exist or invalid database name
275
276    **Request**:
277
278    .. code-block:: http
279
280        DELETE /db HTTP/1.1
281        Accept: application/json
282        Host: localhost:5984
283
284    **Response**:
285
286    .. code-block:: http
287
288        HTTP/1.1 200 OK
289        Cache-Control: must-revalidate
290        Content-Length: 12
291        Content-Type: application/json
292        Date: Mon, 12 Aug 2013 08:54:00 GMT
293        Server: CouchDB (Erlang/OTP)
294
295        {
296            "ok": true
297        }
298
299.. http:post:: /{db}
300    :synopsis: Creates a new document with generated ID if _id is not specified
301
302    Creates a new document in the specified database, using the supplied JSON
303    document structure.
304
305    If the JSON structure includes the ``_id`` field, then the document will be
306    created with the specified document ID.
307
308    If the ``_id`` field is not specified, a new unique ID will be generated,
309    following whatever UUID algorithm is configured for that server.
310
311    :param db: Database name
312    :<header Accept: - :mimetype:`application/json`
313                     - :mimetype:`text/plain`
314    :<header Content-Type: :mimetype:`application/json`
315
316    :query string batch: Stores document in :ref:`batch mode
317      <api/doc/batch-writes>` Possible values: ``ok``. *Optional*
318
319    :>header Content-Type: - :mimetype:`application/json`
320                           - :mimetype:`text/plain; charset=utf-8`
321    :>header Location: Document's URI
322
323    :>json string id: Document ID
324    :>json boolean ok: Operation status
325    :>json string rev: Revision info
326
327    :code 201: Document created and stored on disk
328    :code 202: Document data accepted, but not yet stored on disk
329    :code 400: Invalid database name
330    :code 401: Write privileges required
331    :code 404: Database doesn't exist
332    :code 409: A Conflicting Document with same ID already exists
333
334    **Request**:
335
336    .. code-block:: http
337
338        POST /db HTTP/1.1
339        Accept: application/json
340        Content-Length: 81
341        Content-Type: application/json
342
343        {
344            "servings": 4,
345            "subtitle": "Delicious with fresh bread",
346            "title": "Fish Stew"
347        }
348
349    **Response**:
350
351    .. code-block:: http
352
353        HTTP/1.1 201 Created
354        Cache-Control: must-revalidate
355        Content-Length: 95
356        Content-Type: application/json
357        Date: Tue, 13 Aug 2013 15:19:25 GMT
358        Location: http://localhost:5984/db/ab39fe0993049b84cfa81acd6ebad09d
359        Server: CouchDB (Erlang/OTP)
360
361        {
362            "id": "ab39fe0993049b84cfa81acd6ebad09d",
363            "ok": true,
364            "rev": "1-9c65296036141e575d32ba9c034dd3ee"
365        }
366
367Specifying the Document ID
368==========================
369
370The document ID can be specified by including the ``_id`` field in the
371JSON of the submitted record. The following request will create the same
372document with the ID ``FishStew``.
373
374    **Request**:
375
376    .. code-block:: http
377
378        POST /db HTTP/1.1
379        Accept: application/json
380        Content-Length: 98
381        Content-Type: application/json
382
383        {
384            "_id": "FishStew",
385            "servings": 4,
386            "subtitle": "Delicious with fresh bread",
387            "title": "Fish Stew"
388        }
389
390    **Response**:
391
392    .. code-block:: http
393
394        HTTP/1.1 201 Created
395        Cache-Control: must-revalidate
396        Content-Length: 71
397        Content-Type: application/json
398        Date: Tue, 13 Aug 2013 15:19:25 GMT
399        ETag: "1-9c65296036141e575d32ba9c034dd3ee"
400        Location: http://localhost:5984/db/FishStew
401        Server: CouchDB (Erlang/OTP)
402
403        {
404            "id": "FishStew",
405            "ok": true,
406            "rev": "1-9c65296036141e575d32ba9c034dd3ee"
407        }
408
409.. _api/doc/batch-writes:
410
411Batch Mode Writes
412=================
413
414You can write documents to the database at a higher rate by using the batch
415option. This collects document writes together in memory (on a per-user basis)
416before they are committed to disk. This increases the risk of the documents not
417being stored in the event of a failure, since the documents are not written to
418disk immediately.
419
420Batch mode is not suitable for critical data, but may be ideal for applications
421such as log data, when the risk of some data loss due to a crash is acceptable.
422
423To use batch mode, append the ``batch=ok`` query argument to the URL of a
424:post:`/{db}`, :put:`/{db}/{docid}`, or :delete:`/{db}/{docid}` request. The
425CouchDB server will respond with an HTTP :statuscode:`202` response code
426immediately.
427
428.. note::
429    Creating or updating documents with batch mode doesn't guarantee that all
430    documents will be successfully stored on disk. For example, individual
431    documents may not be saved due to conflicts, rejection by
432    :ref:`validation function <vdufun>` or by other reasons, even if overall
433    the batch was successfully submitted.
434
435**Request**:
436
437.. code-block:: http
438
439    POST /db?batch=ok HTTP/1.1
440    Accept: application/json
441    Content-Length: 98
442    Content-Type: application/json
443
444    {
445        "_id": "FishStew",
446        "servings": 4,
447        "subtitle": "Delicious with fresh bread",
448        "title": "Fish Stew"
449    }
450
451**Response**:
452
453.. code-block:: http
454
455    HTTP/1.1 202 Accepted
456    Cache-Control: must-revalidate
457    Content-Length: 28
458    Content-Type: application/json
459    Date: Tue, 13 Aug 2013 15:19:25 GMT
460    Location: http://localhost:5984/db/FishStew
461    Server: CouchDB (Erlang/OTP)
462
463    {
464        "id": "FishStew",
465        "ok": true
466    }
467
468.. _Regular Expressions: http://en.wikipedia.org/wiki/Regular_expression
469