Return-Path: X-Original-To: apmail-couchdb-commits-archive@www.apache.org Delivered-To: apmail-couchdb-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 759E7CC91 for ; Fri, 28 Nov 2014 21:00:05 +0000 (UTC) Received: (qmail 97199 invoked by uid 500); 28 Nov 2014 21:00:04 -0000 Delivered-To: apmail-couchdb-commits-archive@couchdb.apache.org Received: (qmail 97039 invoked by uid 500); 28 Nov 2014 21:00:04 -0000 Mailing-List: contact commits-help@couchdb.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@couchdb.apache.org Delivered-To: mailing list commits@couchdb.apache.org Received: (qmail 96321 invoked by uid 99); 28 Nov 2014 21:00:03 -0000 Received: from tyr.zones.apache.org (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 28 Nov 2014 21:00:03 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id 880E18B6980; Fri, 28 Nov 2014 21:00:03 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit From: robertkowalski@apache.org To: commits@couchdb.apache.org Date: Fri, 28 Nov 2014 21:00:14 -0000 Message-Id: In-Reply-To: <73dbd4c3aedd405d98e87fed3b3c1cb9@git.apache.org> References: <73dbd4c3aedd405d98e87fed3b3c1cb9@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [12/47] couchdb commit: updated refs/heads/enable-csp-default to dbd38a1 http://git-wip-us.apache.org/repos/asf/couchdb/blob/cdac7299/share/doc/src/json-structure.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/json-structure.rst b/share/doc/src/json-structure.rst deleted file mode 100644 index addc5ac..0000000 --- a/share/doc/src/json-structure.rst +++ /dev/null @@ -1,641 +0,0 @@ -.. Licensed under the Apache License, Version 2.0 (the "License"); you may not -.. use this file except in compliance with the License. You may obtain a copy of -.. the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -.. License for the specific language governing permissions and limitations under -.. the License. - -======================== -JSON Structure Reference -======================== - -The following appendix provides a quick reference to all the JSON structures -that you can supply to CouchDB, or get in return to requests. - -All Database Documents -====================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| total_rows | Number of documents in the database/view | -+--------------------------------+---------------------------------------------+ -| offset | Offset where the document list started | -+--------------------------------+---------------------------------------------+ -| update_seq (optional) | Current update sequence for the database | -+--------------------------------+---------------------------------------------+ -| rows [array] | Array of document object | -+--------------------------------+---------------------------------------------+ - -Bulk Document Response -====================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| docs [array] | Bulk Docs Returned Documents | -+--------------------------------+---------------------------------------------+ -| id | Document ID | -+--------------------------------+---------------------------------------------+ -| error | Error type | -+--------------------------------+---------------------------------------------+ -| reason | Error string with extended reason | -+--------------------------------+---------------------------------------------+ - -Bulk Documents -============== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| all_or_nothing (optional) | Sets the database commit mode to use | -| | all-or-nothing semantics | -+--------------------------------+---------------------------------------------+ -| docs [array] | Bulk Documents Document | -+--------------------------------+---------------------------------------------+ -| _id (optional) | Document ID | -+--------------------------------+---------------------------------------------+ -| _rev (optional) | Revision ID (when updating an existing | -| | document) | -+--------------------------------+---------------------------------------------+ -| _deleted (optional) | Whether the document should be deleted | -+--------------------------------+---------------------------------------------+ - -Changes information for a database -================================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| last_seq | Last change sequence number | -+--------------------------------+---------------------------------------------+ -| results [array] | Changes made to a database | -+--------------------------------+---------------------------------------------+ -| seq | Update sequence number | -+--------------------------------+---------------------------------------------+ -| id | Document ID | -+--------------------------------+---------------------------------------------+ -| changes [array] | List of changes, field-by-field, for this | -| | document | -+--------------------------------+---------------------------------------------+ - -CouchDB Document -================ - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| _id (optional) | Document ID | -+--------------------------------+---------------------------------------------+ -| _rev (optional) | Revision ID (when updating an existing | -| | document) | -+--------------------------------+---------------------------------------------+ - -CouchDB Error Status -==================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| id | Document ID | -+--------------------------------+---------------------------------------------+ -| error | Error type | -+--------------------------------+---------------------------------------------+ -| reason | Error string with extended reason | -+--------------------------------+---------------------------------------------+ - -.. _dbinfo_object: - -CouchDB database information object -=================================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| db_name | The name of the database. | -+--------------------------------+---------------------------------------------+ -| committed_update_seq | The number of committed updates. | -+--------------------------------+---------------------------------------------+ -| doc_count | The number of documents in the database. | -+--------------------------------+---------------------------------------------+ -| doc_del_count | The number of deleted documents. | -+--------------------------------+---------------------------------------------+ -| compact_running | Set to true if the database compaction | -| | routine is operating on this database. | -+--------------------------------+---------------------------------------------+ -| disk_format_version | The version of the physical format used for | -| | the data when it is stored on hard disk. | -+--------------------------------+---------------------------------------------+ -| disk_size | Size in bytes of the data as stored on disk.| -| | View indexes are not included in the | -| | calculation. | -+--------------------------------+---------------------------------------------+ -| instance_start_time | Timestamp indicating when the database was | -| | opened, expressed in microseconds since the | -| | epoch. | -+--------------------------------+---------------------------------------------+ -| purge_seq | The number of purge operations on the | -| | database. | -+--------------------------------+---------------------------------------------+ -| update_seq | The current number of updates made in the | -| | database. | -+--------------------------------+---------------------------------------------+ - -Design Document -=============== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| _id | Design Document ID | -+--------------------------------+---------------------------------------------+ -| _rev | Design Document Revision | -+--------------------------------+---------------------------------------------+ -| views | View | -+--------------------------------+---------------------------------------------+ -| viewname | View Definition | -+--------------------------------+---------------------------------------------+ -| map | Map Function for View | -+--------------------------------+---------------------------------------------+ -| reduce (optional) | Reduce Function for View | -+--------------------------------+---------------------------------------------+ - -Design Document Information -=========================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| name | Name/ID of Design Document | -+--------------------------------+---------------------------------------------+ -| view_index | View Index | -+--------------------------------+---------------------------------------------+ -| compact_running | Indicates whether a compaction routine is | -| | currently running on the view | -+--------------------------------+---------------------------------------------+ -| disk_size | Size in bytes of the view as stored on disk | -+--------------------------------+---------------------------------------------+ -| language | Language for the defined views | -+--------------------------------+---------------------------------------------+ -| purge_seq | The purge sequence that has been processed | -+--------------------------------+---------------------------------------------+ -| signature | MD5 signature of the views for the design | -| | document | -+--------------------------------+---------------------------------------------+ -| update_seq | The update sequence of the corresponding | -| | database that has been indexed | -+--------------------------------+---------------------------------------------+ -| updater_running | Indicates if the view is currently being | -| | updated | -+--------------------------------+---------------------------------------------+ -| waiting_clients | Number of clients waiting on views from this| -| | design document | -+--------------------------------+---------------------------------------------+ -| waiting_commit | Indicates if there are outstanding commits | -| | to the underlying database that need to | -| | processed | -+--------------------------------+---------------------------------------------+ - -Document with Attachments -========================= - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| _id (optional) | Document ID | -+--------------------------------+---------------------------------------------+ -| _rev (optional) | Revision ID (when updating an existing | -| | document) | -+--------------------------------+---------------------------------------------+ -| _attachments (optional) | Document Attachment | -+--------------------------------+---------------------------------------------+ -| filename | Attachment information | -+--------------------------------+---------------------------------------------+ -| content_type | MIME Content type string | -+--------------------------------+---------------------------------------------+ -| data | File attachment content, Base64 encoded | -+--------------------------------+---------------------------------------------+ - -List of Active Tasks -==================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| tasks [array] | Active Tasks | -+--------------------------------+---------------------------------------------+ -| pid | Process ID | -+--------------------------------+---------------------------------------------+ -| status | Task status message | -+--------------------------------+---------------------------------------------+ -| task | Task name | -+--------------------------------+---------------------------------------------+ -| type | Operation Type | -+--------------------------------+---------------------------------------------+ - -.. _replication-settings: - -Replication Settings -==================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| source | Source database name or URL | -+--------------------------------+---------------------------------------------+ -| target | Target database name or URL | -+--------------------------------+---------------------------------------------+ -| create_target (optional) | Creates the target database | -+--------------------------------+---------------------------------------------+ -| continuous (optional) | Configure the replication to be continuous | -+--------------------------------+---------------------------------------------+ -| cancel (optional) | Cancels the replication | -+--------------------------------+---------------------------------------------+ -| doc_ids (optional) | Array of document IDs to be synchronized | -+--------------------------------+---------------------------------------------+ -| proxy (optional) | Address of a proxy server through which | -| | replication should occur | -+--------------------------------+---------------------------------------------+ -| since_seq (optional) | Sequence from which the replication should | -| | start | -+--------------------------------+---------------------------------------------+ -| filter (optional) | name of the filter function in the form of | -| | ``ddoc/myfilter`` | -+--------------------------------+---------------------------------------------+ -| query_params (optional) | Query parameter that are passed to the | -| | filter function; the value should be a | -| | document containing parameters as members | -+--------------------------------+---------------------------------------------+ -| use_checkpoints (optional) | Whether to use replication checkpoints | -| | or not | -+--------------------------------+---------------------------------------------+ -| checkpoint_interval (optional) | Specifies the checkpoint interval in ms. | -+--------------------------------+---------------------------------------------+ - -.. _replication-status: - -Replication Status -================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| ok | Replication status | -+--------------------------------+---------------------------------------------+ -| session_id | Unique session ID | -+--------------------------------+---------------------------------------------+ -| source_last_seq | Last sequence number read from the source | -| | database | -+--------------------------------+---------------------------------------------+ -| history [array] | Replication History | -+--------------------------------+---------------------------------------------+ -| session_id | Session ID for this replication operation | -+--------------------------------+---------------------------------------------+ -| recorded_seq | Last recorded sequence number | -+--------------------------------+---------------------------------------------+ -| docs_read | Number of documents read | -+--------------------------------+---------------------------------------------+ -| docs_written | Number of documents written to target | -+--------------------------------+---------------------------------------------+ -| doc_write_failures | Number of document write failures | -+--------------------------------+---------------------------------------------+ -| start_time | Date/Time replication operation started | -+--------------------------------+---------------------------------------------+ -| start_last_seq | First sequence number in changes stream | -+--------------------------------+---------------------------------------------+ -| end_time | Date/Time replication operation completed | -+--------------------------------+---------------------------------------------+ -| end_last_seq | Last sequence number in changes stream | -+--------------------------------+---------------------------------------------+ -| missing_checked | Number of missing documents checked | -+--------------------------------+---------------------------------------------+ -| missing_found | Number of missing documents found | -+--------------------------------+---------------------------------------------+ - -.. _request_object: - -Request object -============== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| body | Request body data as `string`. | -| | If the request method is `GET` this field | -| | contains the value ``"undefined"``. If the | -| | method is `DELETE` or `HEAD` the value is | -| | ``""`` (empty string). | -+--------------------------------+---------------------------------------------+ -| cookie | Cookies `object`. | -+--------------------------------+---------------------------------------------+ -| form | Form data `object`. | -| | Contains the decoded body as key-value | -| | pairs if the `Content-Type` header was | -| | ``application/x-www-form-urlencoded``. | -+--------------------------------+---------------------------------------------+ -| headers | Request headers `object`. | -+--------------------------------+---------------------------------------------+ -| id | Requested document id `string` if it was | -| | specified or ``null`` otherwise. | -+--------------------------------+---------------------------------------------+ -| info | :ref:`Database information ` | -+--------------------------------+---------------------------------------------+ -| method | Request method as `string` or `array`. | -| | String value is a method as one of: `HEAD`, | -| | `GET`, `POST`, `PUT`, `DELETE`, `OPTIONS`, | -| | and `TRACE`. Otherwise it will be | -| | represented as an array of char codes. | -+--------------------------------+---------------------------------------------+ -| path | List of requested path sections. | -+--------------------------------+---------------------------------------------+ -| peer | Request source IP address. | -+--------------------------------+---------------------------------------------+ -| query | URL query parameters `object`. | -| | Note that multiple keys are not supported | -| | and the last key value suppresses others. | -+--------------------------------+---------------------------------------------+ -| requested_path | List of actual requested path section. | -+--------------------------------+---------------------------------------------+ -| raw_path | Raw requested path `string`. | -+--------------------------------+---------------------------------------------+ -| secObj | :ref:`security_object`. | -+--------------------------------+---------------------------------------------+ -| userCtx | :ref:`userctx_object`. | -+--------------------------------+---------------------------------------------+ -| uuid | Generated UUID by a specified algorithm in | -| | the config file. | -+--------------------------------+---------------------------------------------+ - -.. code-block:: javascript - - { - "body": "undefined", - "cookie": { - "AuthSession": "cm9vdDo1MDZBRjQzRjrfcuikzPRfAn-EA37FmjyfM8G8Lw", - "m": "3234" - }, - "form": {}, - "headers": { - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", - "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", - "Accept-Encoding": "gzip,deflate,sdch", - "Accept-Language": "en-US,en;q=0.8", - "Connection": "keep-alive", - "Cookie": "m=3234:t|3247:t|6493:t|6967:t|34e2:|18c3:t|2c69:t|5acb:t|ca3:t|c01:t|5e55:t|77cb:t|2a03:t|1d98:t|47ba:t|64b8:t|4a01:t; AuthSession=cm9vdDo1MDZBRjQzRjrfcuikzPRfAn-EA37FmjyfM8G8Lw", - "Host": "127.0.0.1:5984", - "User-Agent": "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7" - }, - "id": "foo", - "info": { - "committed_update_seq": 2701412, - "compact_running": false, - "data_size": 7580843252, - "db_name": "mailbox", - "disk_format_version": 6, - "disk_size": 14325313673, - "doc_count": 2262757, - "doc_del_count": 560, - "instance_start_time": "1347601025628957", - "purge_seq": 0, - "update_seq": 2701412 - }, - "method": "GET", - "path": [ - "mailbox", - "_design", - "request", - "_show", - "dump", - "foo" - ], - "peer": "127.0.0.1", - "query": {}, - "raw_path": "/mailbox/_design/request/_show/dump/foo", - "requested_path": [ - "mailbox", - "_design", - "request", - "_show", - "dump", - "foo" - ], - "secObj": { - "admins": { - "names": [ - "Bob" - ], - "roles": [] - }, - "members": { - "names": [ - "Mike", - "Alice" - ], - "roles": [] - } - }, - "userCtx": { - "db": "mailbox", - "name": "Mike", - "roles": [ - "user" - ] - }, - "uuid": "3184f9d1ea934e1f81a24c71bde5c168" - } - - -.. _response_object: - -Response object -=============== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| code | HTTP status code `number`. | -+--------------------------------+---------------------------------------------+ -| json | JSON encodable `object`. | -| | Implicitly sets `Content-Type` header as | -| | ``application/json``. | -+--------------------------------+---------------------------------------------+ -| body | Raw response text `string`. | -| | Implicitly sets `Content-Type` header as | -| | ``text/html; charset=utf-8``. | -+--------------------------------+---------------------------------------------+ -| base64 | Base64 encoded `string`. | -| | Implicitly sets `Content-Type` header as | -| | ``application/binary``. | -+--------------------------------+---------------------------------------------+ -| headers | Response headers `object`. | -| | `Content-Type` header from this object | -| | overrides any implicitly assigned one. | -+--------------------------------+---------------------------------------------+ -| stop | `boolean` signal to stop iteration over | -| | view result rows (for list functions only) | -+--------------------------------+---------------------------------------------+ - -.. warning:: - The ``body``, ``base64`` and ``json`` object keys are overlapping each other - where the last one wins. Since most realizations of key-value objects do - not preserve the key order or if they are mixed, confusing situations can - occure. Try to use only one of them. - -.. note:: - Any custom property makes CouchDB raise an internal exception. - Furthermore, the `Response object` could be a simple string value which would - be implicitly wrapped into a ``{"body": ...}`` object. - - -Returned CouchDB Document with Detailed Revision Info -===================================================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| _id (optional) | Document ID | -+--------------------------------+---------------------------------------------+ -| _rev (optional) | Revision ID (when updating an existing | -| | document) | -+--------------------------------+---------------------------------------------+ -| _revs_info [array] | CouchDB document extended revision info | -+--------------------------------+---------------------------------------------+ -| rev | Full revision string | -+--------------------------------+---------------------------------------------+ -| status | Status of the revision | -+--------------------------------+---------------------------------------------+ - -Returned CouchDB Document with Revision Info -============================================ - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| _id (optional) | Document ID | -+--------------------------------+---------------------------------------------+ -| _rev (optional) | Revision ID (when updating an existing | -| | document) | -+--------------------------------+---------------------------------------------+ -| _revisions | CouchDB document revisions | -+--------------------------------+---------------------------------------------+ -| ids [array] | Array of valid revision IDs, in reverse | -| | order (latest first) | -+--------------------------------+---------------------------------------------+ -| start | Prefix number for the latest revision | -+--------------------------------+---------------------------------------------+ - -Returned Document with Attachments -================================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| _id (optional) | Document ID | -+--------------------------------+---------------------------------------------+ -| _rev (optional) | Revision ID (when updating an existing | -| | document) | -+--------------------------------+---------------------------------------------+ -| _attachments (optional) | Document attachment | -+--------------------------------+---------------------------------------------+ -| filename | Attachment | -+--------------------------------+---------------------------------------------+ -| stub | Indicates whether the attachment is a stub | -+--------------------------------+---------------------------------------------+ -| content_type | MIME Content type string | -+--------------------------------+---------------------------------------------+ -| length | Length (bytes) of the attachment data | -+--------------------------------+---------------------------------------------+ -| revpos | Revision where this attachment exists | -+--------------------------------+---------------------------------------------+ - -.. _security_object: - -Security Object -=============== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| admins | Roles/Users with admin privileges | -+--------------------------------+---------------------------------------------+ -| roles [array] | List of roles with parent privilege | -+--------------------------------+---------------------------------------------+ -| users [array] | List of users with parent privilege | -+--------------------------------+---------------------------------------------+ -| readers | Roles/Users with reader privileges | -+--------------------------------+---------------------------------------------+ -| roles [array] | List of roles with parent privilege | -+--------------------------------+---------------------------------------------+ -| users [array] | List of users with parent privilege | -+--------------------------------+---------------------------------------------+ - -.. code-block:: javascript - - { - "admins": { - "names": [ - "Bob" - ], - "roles": [] - }, - "members": { - "names": [ - "Mike", - "Alice" - ], - "roles": [] - } - } - - -.. _userctx_object: - -User Context Object -=================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| db | Database name in the context of the | -| | provided operation. | -+--------------------------------+---------------------------------------------+ -| name | User name. | -+--------------------------------+---------------------------------------------+ -| roles | List of user roles. | -+--------------------------------+---------------------------------------------+ - -.. code-block:: javascript - - { - "db": "mailbox", - "name": null, - "roles": [ - "_admin" - ] - } - - -.. _view_head_info_object: - -View Head Information -===================== - -+--------------------------------+---------------------------------------------+ -| Field | Description | -+================================+=============================================+ -| total_rows | Number of documents in the view | -+--------------------------------+---------------------------------------------+ -| offset | Offset where the document list started | -+--------------------------------+---------------------------------------------+ - -.. code-block:: javascript - - { - "total_rows": 42, - "offset": 3 - } http://git-wip-us.apache.org/repos/asf/couchdb/blob/cdac7299/share/doc/src/maintenance/compaction.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/maintenance/compaction.rst b/share/doc/src/maintenance/compaction.rst deleted file mode 100644 index f6d0240..0000000 --- a/share/doc/src/maintenance/compaction.rst +++ /dev/null @@ -1,193 +0,0 @@ -.. Licensed under the Apache License, Version 2.0 (the "License")you may not -.. use this file except in compliance with the License. You may obtain a copy of -.. the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -.. License for the specific language governing permissions and limitations under -.. the License. - -.. _compact: - -Compaction -========== - -The `compaction` operation is the way to reduce disk space usage by removing -unused and old data from database or view index files. This operation is a very -similar to the `vacuum` (`SQLite`_ ex.) available for other database management -systems. - -.. _SQLite: http://www.sqlite.org/lang_vacuum.html - -During compaction of the `target` CouchDB creates new file with the ``.compact`` -extension and transfers only actual data into. Because of this, CouchDB checks -first for the available disk space - it should be *twice greater* than the -compacted file's data. - -When all actual data is successfully transferred to the `compacted` file CouchDB -replaces the `target` with the `compacted` file. - - -.. _compact/db: - -Database Compaction -------------------- - -Database compaction compresses the database file by removing unused file -sections created during updates. Old documents revisions are replaced with -small amount of metadata called `tombstone` which are used for conflicts -resolution during replication. The number of stored revisions -(and their `tombstones`) can be configured by using the :get:`_revs_limit -` URL endpoint. - -Compaction is manually triggered operation per database and runs as a background -task. To start it for specific database there is need to send HTTP -:post:`/{db}/_compact` sub-resource of the target database:: - - curl -H "Content-Type: application/json" -X POST http://localhost:5984/my_db/_compact - -On success, HTTP status :statuscode:`202` is returned immediately: - -.. code-block:: http - - HTTP/1.1 202 Accepted - Cache-Control: must-revalidate - Content-Length: 12 - Content-Type: text/plain; charset=utf-8 - Date: Wed, 19 Jun 2013 09:43:52 GMT - Server: CouchDB (Erlang/OTP) - -.. code-block:: javascript - - {"ok":true} - -Although the request body is not used you must still specify -:header:`Content-Type` header with :mimetype:`application/json` value -for the request. If you don't, you will be aware about with HTTP status -:statuscode:`415` response: - -.. code-block:: http - - HTTP/1.1 415 Unsupported Media Type - Cache-Control: must-revalidate - Content-Length: 78 - Content-Type: application/json - Date: Wed, 19 Jun 2013 09:43:44 GMT - Server: CouchDB (Erlang/OTP) - - {"error":"bad_content_type","reason":"Content-Type must be application/json"} - -When the compaction is successful started and running it is possible to get -information about it via :ref:`database information resource `:: - - curl http://localhost:5984/my_db - -.. code-block:: http - - HTTP/1.1 200 OK - Cache-Control: must-revalidate - Content-Length: 246 - Content-Type: application/json - Date: Wed, 19 Jun 2013 16:51:20 GMT - Server: CouchDB (Erlang/OTP) - - { - "committed_update_seq": 76215, - "compact_running": true, - "data_size": 3787996, - "db_name": "my_db", - "disk_format_version": 6, - "disk_size": 17703025, - "doc_count": 5091, - "doc_del_count": 0, - "instance_start_time": "1371660751878859", - "purge_seq": 0, - "update_seq": 76215 - } - - -Note that ``compaction_running`` field is ``true`` indicating that compaction -is actually running. To track the compaction progress you may query the -:get:`_active_tasks ` resource:: - - curl http://localhost:5984/my_db - -.. code-block:: http - - HTTP/1.1 200 OK - Cache-Control: must-revalidate - Content-Length: 175 - Content-Type: application/json - Date: Wed, 19 Jun 2013 16:27:23 GMT - Server: CouchDB (Erlang/OTP) - - [ - { - "changes_done": 44461, - "database": "my_db", - "pid": "<0.218.0>", - "progress": 58, - "started_on": 1371659228, - "total_changes": 76215, - "type": "database_compaction", - "updated_on": 1371659241 - } - ] - - -.. _compact/views: - -Views Compaction ----------------- - -`Views` are also need compaction like databases, unlike databases views -are compacted by groups per `design document`. To start their compaction there -is need to send HTTP :post:`/{db}/_compact/{ddoc}` request:: - - curl -H "Content-Type: application/json" -X POST http://localhost:5984/dbname/_compact/designname - -.. code-block:: javascript - - {"ok":true} - -This compacts the view index from the current version of the specified design -document. The HTTP response code is :statuscode:`202` -(like :ref:`compaction for databases `) and a compaction background -task will be created. - - -.. _compact/views/cleanup: - -Views cleanup -^^^^^^^^^^^^^ - -View indexes on disk are named after their `MD5` hash of the view definition. -When you change a view, old indexes remain on disk. To clean up all outdated -view indexes (files named after the MD5 representation of views, that does not -exist anymore) you can trigger a :ref:`view cleanup `:: - - curl -H "Content-Type: application/json" -X POST http://localhost:5984/dbname/_view_cleanup - -.. code-block:: javascript - - {"ok":true} - - -.. _compact/auto: - -Automatic Compaction --------------------- - -While both :ref:`database ` and :ref:`views ` -compactions are required be manually triggered, it is also possible to configure -automatic compaction, so that compaction of databases and views is automatically -triggered based on various criteria. Automatic compaction is configured in -CouchDB's :ref:`configuration files `. - -The :config:option:`daemons/compaction_daemon` is responsible for triggering -the compaction. It is automatically started, but disabled by default. -The criteria for triggering the compactions is configured in the -:config:section:`compactions` section. http://git-wip-us.apache.org/repos/asf/couchdb/blob/cdac7299/share/doc/src/maintenance/index.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/maintenance/index.rst b/share/doc/src/maintenance/index.rst deleted file mode 100644 index b0072fe..0000000 --- a/share/doc/src/maintenance/index.rst +++ /dev/null @@ -1,21 +0,0 @@ -.. Licensed under the Apache License, Version 2.0 (the "License")you may not -.. use this file except in compliance with the License. You may obtain a copy of -.. the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -.. License for the specific language governing permissions and limitations under -.. the License. - - -=================== -CouchDB Maintenance -=================== - -.. toctree:: - - compaction - performance http://git-wip-us.apache.org/repos/asf/couchdb/blob/cdac7299/share/doc/src/maintenance/performance.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/maintenance/performance.rst b/share/doc/src/maintenance/performance.rst deleted file mode 100644 index b4f9d59..0000000 --- a/share/doc/src/maintenance/performance.rst +++ /dev/null @@ -1,293 +0,0 @@ -.. Licensed under the Apache License, Version 2.0 (the "License"); you may not -.. use this file except in compliance with the License. You may obtain a copy of -.. the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -.. License for the specific language governing permissions and limitations under -.. the License. - - -.. _performance: - -=========== -Performance -=========== - -With up to tens of thousands of documents you will generally find CouchDB to -perform well no matter how you write your code. Once you start getting into -the millions of documents you need to be a lot more careful. - - -Disk I/O -======== - -File Size ---------- - -The smaller your file size, the less `I/O` operations there will be, -the more of the file can be cached by CouchDB and the operating system, -the quicker it is to replicate, backup etc. Consequently you should carefully -examine the data you are storing. For example it would be silly to use keys -that are hundreds of characters long, but your program would be hard to -maintain if you only used single character keys. Carefully consider data -that is duplicated by putting it in views. - - -Disk and File System Performance --------------------------------- - -Using faster disks, striped RAID arrays and modern file systems can all speed -up your CouchDB deployment. However, there is one option that can increase -the responsiveness of your CouchDB server when disk performance is a -bottleneck. From the Erlang documentation for the file module: - - On operating systems with thread support, it is possible to let file - operations be performed in threads of their own, allowing other Erlang - processes to continue executing in parallel with the file operations. - See the `command line flag +A in erl(1)`_. - -Setting this argument to a number greater than zero can keep your CouchDB -installation responsive even during periods of heavy disk utilization. The -easiest way to set this option is through the ``ERL_FLAGS`` environment -variable. For example, to give Erlang four threads with which to perform I/O -operations add the following to ``(prefix)/etc/defaults/couchdb`` -(or equivalent):: - - export ERL_FLAGS="+A 4" - - -.. _command line flag +A in erl(1): http://erlang.org/doc/man/erl.html - - -System Resource Limits -====================== - -One of the problems that administrators run into as their deployments become -large are resource limits imposed by the system and by the application -configuration. Raising these limits can allow your deployment to grow beyond -what the default configuration will support. - - -CouchDB Configuration Options ------------------------------ - -delayed_commits -^^^^^^^^^^^^^^^ - -The :config:option:`delayed commits ` allows to -achieve better write performance for some workloads while sacrificing a small -amount of durability. The setting causes CouchDB to wait up to a full second -before committing new data after an update. If the server crashes before -the header is written then any writes since the last commit are lost. Keep this -option enabled on your own risk. - -max_dbs_open -^^^^^^^^^^^^ - -In your :ref:`configuration ` (local.ini or similar) familiarize -yourself with the :config:option:`couchdb/max_dbs_open`: - -.. code-block:: ini - - [couchdb] - max_dbs_open = 100 - -This option places an upper bound on the number of databases that can be -open at one time. CouchDB reference counts database accesses internally and -will close idle databases when it must. Sometimes it is necessary to keep -more than the default open at once, such as in deployments where many databases -will be continuously replicating. - - -Erlang ------- - -Even if you've increased the maximum connections CouchDB will allow, -the Erlang runtime system will not allow more than 1024 connections by -default. Adding the following directive to ``(prefix)/etc/default/couchdb`` (or -equivalent) will increase this limit (in this case to 4096):: - - export ERL_MAX_PORTS=4096 - -CouchDB versions up to 1.1.x also create Erlang Term Storage (`ETS`_) tables for -each replication. If you are using a version of CouchDB older than 1.2 and -must support many replications, also set the ``ERL_MAX_ETS_TABLES`` variable. -The default is approximately 1400 tables. - -Note that on Mac OS X, Erlang will not actually increase the file descriptor -limit past 1024 (i.e. the system header–defined value of ``FD_SETSIZE``). See -`this tip for a possible workaround`_ and `this thread for a deeper -explanation`_. - -.. _ETS: http://www.erlang.org/doc/man/ets.html -.. _this tip for a possible workaround: http://erlang.org/pipermail/erlang-questions/2011-December/063119.html -.. _this thread for a deeper explanation: http://erlang.org/pipermail/erlang-questions/2011-October/061971.html - - -PAM and ulimit --------------- - -Finally, most \*nix operating systems impose various resource limits on every -process. If your system is set up to use the Pluggable Authentication Modules -(`PAM`_) system, increasing this limit is straightforward. For example, -creating a file named ``/etc/security/limits.d/100-couchdb.conf`` with the -following contents will ensure that CouchDB can open enough file descriptors -to service your increased maximum open databases and Erlang ports:: - - # - couchdb hard nofile 4096 - couchdb soft nofile 4096 - -If your system does not use PAM, a `ulimit` command is usually available for -use in a custom script to launch CouchDB with increased resource limits. -If necessary, feel free to increase this limits as long as your hardware can -handle the load. - -.. _PAM: http://www.linux-pam.org/ - - -Network -======= - -There is latency overhead making and receiving each request/response. -In general you should do your requests in batches. Most APIs have some -mechanism to do batches, usually by supplying lists of documents or keys in -the request body. Be careful what size you pick for the batches. The larger -batch requires more time your client has to spend encoding the items into JSON -and more time is spent decoding that number of responses. Do some benchmarking -with your own configuration and typical data to find the sweet spot. -It is likely to be between one and ten thousand documents. - -If you have a fast I/O system then you can also use concurrency - have -multiple requests/responses at the same time. This mitigates the latency -involved in assembling JSON, doing the networking and decoding JSON. - -As of CouchDB 1.1.0, users often report lower write performance of documents -compared to older releases. The main reason is that this release ships with -the more recent version of the HTTP server library Mochiweb, which by default -sets the TCP socket option `SO_NODELAY`_ to false. This means that small data -sent to the TCP socket, like the reply to a document write request (or reading -a very small document), will not be sent immediately to the network - TCP will -buffer it for a while hoping that it will be asked to send more data through -the same socket and then send all the data at once for increased performance. -This TCP buffering behaviour can be disabled via -:config:option:`httpd/socket_options`: - -.. code-block:: ini - - [httpd] - socket_options = [{nodelay, true}] - -.. _SO_NODELAY: http://en.wikipedia.org/wiki/Nagle%27s_algorithm - -.. seealso:: - - Bulk :ref:`load ` and :ref:`store ` API. - - -CouchDB -======= - -DELETE operation ----------------- - -When you :method:`DELETE` a document the database will create a new -revision which contains the ``_id`` and ``_rev`` fields as well as -the `_deleted` flag. This revision will remain even after a `database -compaction` so that the deletion can be replicated. Deleted documents, like -non-deleted documents, can affect view build times, :method:`PUT` and -:method:`DELETE` requests time and size of database on disk, since they -increase the size of the B+Tree's. You can see the number of deleted documents -in :get:`database information `. If your use case creates lots of -deleted documents (for example, if you are storing short-term data like logfile -entries, message queues, etc), you might want to periodically switch to a new -database and delete the old one (once the entries in it have all expired). - - -Document's ID -------------- - -The db file size is derived from your document and view sizes but also on a -multiple of your ``_id`` sizes. Not only is the ``_id`` present in the document, -but it and parts of it are duplicated in the binary tree structure CouchDB uses -to navigate the file to find the document in the first place. As a real world -example for one user switching from 16 byte ids to 4 byte ids made a database -go from 21GB to 4GB with 10 million documents (the raw JSON text when from -2.5GB to 2GB). - -Inserting with sequential (and at least sorted) ids is faster than random ids. -Consequently you should consider generating ids yourself, allocating them -sequentially and using an encoding scheme that consumes fewer bytes. -For example, something that takes 16 hex digits to represent can be done in -4 base 62 digits (10 numerals, 26 lower case, 26 upper case). - - -Views -===== - -Views Generation ----------------- - -Views with the Javascript query server are extremely slow to generate when -there are a non-trivial number of documents to process. The generation process -won't even saturate a single CPU let alone your I/O. The cause is the latency -involved in the CouchDB server and separate `couchjs` query server, dramatically -indicating how important it is to take latency out of your implementation. - -You can let view access be "stale" but it isn't practical to determine when -that will occur giving you a quick response and when views will be updated -which will take a long time. (A 10 million document database took about 10 -minutes to load into CouchDB but about 4 hours to do view generation). - -View information isn't replicated - it is rebuilt on each database so you -can't do the view generation on a separate sever. - - -Builtin Reduce Functions ------------------------- - -If you’re using a very simple view function that only performs a sum or count -reduction, you can call native Erlang implementations of them by simply -writing ``_sum`` or ``_count`` in place of your function declaration. -This will speed up things dramatically, as it cuts down on IO between CouchDB -and the :ref:`JavaScript query server `. For example, as -`mentioned on the mailing list`_, the time for outputting an (already indexed -and cached) view with about 78,000 items went down from 60 seconds to 4 seconds. - -Before: - -.. code-block:: javascript - - { - "_id": "_design/foo", - "views": { - "bar": { - "map": "function (doc) { emit(doc.author, 1); }", - "reduce": "function (keys, values, rereduce) { return sum(values); }" - } - } - } - -After: - -.. code-block:: javascript - - { - "_id": "_design/foo", - "views": { - "bar": { - "map": "function (doc) { emit(doc.author, 1); }", - "reduce": "_sum" - } - } - } - -.. _mentioned on the mailing list: http://mail-archives.apache.org/mod_mbox/couchdb-user/201003.mbox/%3c5E07E00E-3D69-4A8C-ADA3-1B20CF0BA4C8@julianstahnke.com%3e - -.. seealso:: - - :ref:`reducefun/builtin` http://git-wip-us.apache.org/repos/asf/couchdb/blob/cdac7299/share/doc/src/query-server/erlang.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/query-server/erlang.rst b/share/doc/src/query-server/erlang.rst deleted file mode 100644 index 165a341..0000000 --- a/share/doc/src/query-server/erlang.rst +++ /dev/null @@ -1,139 +0,0 @@ -.. Licensed under the Apache License, Version 2.0 (the "License"); you may not -.. use this file except in compliance with the License. You may obtain a copy of -.. the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -.. License for the specific language governing permissions and limitations under -.. the License. - -.. default-domain:: js - -.. _query-server/erlang: - -Erlang -====== - -.. note:: - - The Erlang query server is disabled by default. - Read :ref:`configuration guide ` about - reasons why and how to enable it. - -.. function:: Emit(Id, Value) - - Emits `key`-`value` pairs to view indexer process. - - .. code-block:: erlang - - fun({Doc}) -> - <> = proplists:get_value(<<"_rev">>, Doc, null), - V = proplists:get_value(<<"_id">>, Doc, null), - Emit(<>, V) - end. - - -.. function:: FoldRows(Fun, Acc) - - Helper to iterate over all rows in a list function. - - :param Fun: Function object. - :param Acc: The value previously returned by `Fun`. - - .. code-block:: erlang - - fun(Head, {Req}) -> - Fun = fun({Row}, Acc) -> - Id = couch_util:get_value(<<"id">>, Row), - Send(list_to_binary(io_lib:format("Previous doc id: ~p~n", [Acc]))), - Send(list_to_binary(io_lib:format("Current doc id: ~p~n", [Id]))), - {ok, Id} - end, - FoldRows(Fun, nil), - "" - end. - - -.. function:: GetRow() - - Retrieves the next row from a related view result. - - .. code-block:: erlang - - %% FoldRows background implementation. - %% https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=blob;f=src/couchdb/couch_native_process.erl;hb=HEAD#l368 - %% - foldrows(GetRow, ProcRow, Acc) -> - case GetRow() of - nil -> - {ok, Acc}; - Row -> - case (catch ProcRow(Row, Acc)) of - {ok, Acc2} -> - foldrows(GetRow, ProcRow, Acc2); - {stop, Acc2} -> - {ok, Acc2} - end - end. - -.. function:: Log(Msg) - - :param Msg: Log a message at the `INFO` level. - - .. code-block:: erlang - - fun({Doc}) -> - <> = proplists:get_value(<<"_rev">>, Doc, null), - V = proplists:get_value(<<"_id">>, Doc, null), - Log(lists:flatten(io_lib:format("Hello from ~s doc!", [V]))), - Emit(<>, V) - end. - - After the map function has run, the following line can be found in - CouchDB logs (e.g. at `/var/log/couchdb/couch.log`): - - .. code-block:: text - - [Sun, 04 Nov 2012 11:33:58 GMT] [info] [<0.9144.2>] Hello from 8d300b86622d67953d102165dbe99467 doc! - - -.. function:: Send(Chunk) - - Sends a single string `Chunk` in response. - - .. code-block:: erlang - - fun(Head, {Req}) -> - Send("Hello,"), - Send(" "), - Send("Couch"), - "!" - end. - - The function above produces the following response: - - .. code-block:: text - - Hello, Couch! - - -.. function:: Start(Headers) - - :param Headers: Proplist of :ref:`response object`. - - Initialize :ref:`listfun` response. At this point, response code and headers - may be defined. For example, this function redirects to the CouchDB web site: - - .. code-block:: erlang - - fun(Head, {Req}) -> - Start({[{<<"code">>, 302}, - {<<"headers">>, {[ - {<<"Location">>, <<"http://couchdb.apache.org">>}] - }} - ]}), - "Relax!" - end. http://git-wip-us.apache.org/repos/asf/couchdb/blob/cdac7299/share/doc/src/query-server/index.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/query-server/index.rst b/share/doc/src/query-server/index.rst deleted file mode 100644 index 835ba1b..0000000 --- a/share/doc/src/query-server/index.rst +++ /dev/null @@ -1,40 +0,0 @@ -.. Licensed under the Apache License, Version 2.0 (the "License"); you may not -.. use this file except in compliance with the License. You may obtain a copy of -.. the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -.. License for the specific language governing permissions and limitations under -.. the License. - -.. _query-server: - -============ -Query Server -============ - -The `Query server` is an external process that communicates with CouchDB by JSON -protocol through stdio interface and processed all -:ref:`design functions ` calls: -:ref:`views `, :ref:`shows `, :ref:`lists ` and more. - -The default query server is written in -:ref:`JavaScript `, running via `Mozilla SpiderMonkey`_. -You can use other languages by setting a Query server key in the ``language`` -property of a design document or the `Content-Type` header of a -`temporary view`. Design documents that do not specify a ``language`` property -are assumed to be of type `javascript`, as are ad hoc queries that are POSTed to -:ref:`_temp_view ` without a `Content-Type` header. - -.. _Mozilla SpiderMonkey: https://developer.mozilla.org/en/docs/SpiderMonkey - -.. toctree:: - :maxdepth: 2 - - protocol - javascript - erlang - http://git-wip-us.apache.org/repos/asf/couchdb/blob/cdac7299/share/doc/src/query-server/javascript.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/query-server/javascript.rst b/share/doc/src/query-server/javascript.rst deleted file mode 100644 index 386f9c5..0000000 --- a/share/doc/src/query-server/javascript.rst +++ /dev/null @@ -1,288 +0,0 @@ -.. Licensed under the Apache License, Version 2.0 (the "License"); you may not -.. use this file except in compliance with the License. You may obtain a copy of -.. the License at -.. -.. http://www.apache.org/licenses/LICENSE-2.0 -.. -.. Unless required by applicable law or agreed to in writing, software -.. distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -.. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -.. License for the specific language governing permissions and limitations under -.. the License. - -.. default-domain:: js - -.. _query-server/js: - -JavaScript -========== - -.. note:: While every design function has access to all JavaScript objects, - the table below describes appropriate usage cases. For example, - you may use :func:`emit` in :ref:`listfun`, but :func:`getRow` is not permitted during :ref:`mapfun`. - -+--------------------------------+---------------------------------------------+ -| JS Function | Reasonable to use in design doc functions | -+================================+=============================================+ -| :func:`emit` | :ref:`mapfun` | -+--------------------------------+---------------------------------------------+ -| :func:`getRow` | :ref:`listfun` | -+--------------------------------+---------------------------------------------+ -| :data:`JSON` | any | -+--------------------------------+---------------------------------------------+ -| :func:`isArray` | any | -+--------------------------------+---------------------------------------------+ -| :func:`log` | any | -+--------------------------------+---------------------------------------------+ -| :func:`provides` | :ref:`showfun`, :ref:`listfun` | -+--------------------------------+---------------------------------------------+ -| :func:`registerType` | :ref:`showfun`, :ref:`listfun` | -+--------------------------------+---------------------------------------------+ -| :func:`require` | any, except :ref:`reducefun` | -+--------------------------------+---------------------------------------------+ -| :func:`send` | :ref:`listfun` | -+--------------------------------+---------------------------------------------+ -| :func:`start` | :ref:`listfun` | -+--------------------------------+---------------------------------------------+ -| :func:`sum` | any | -+--------------------------------+---------------------------------------------+ -| :func:`toJSON` | any | -+--------------------------------+---------------------------------------------+ - -Design functions context ------------------------- - -Each design function executes in a special context of predefined objects, -modules and functions: - - -.. function:: emit(key, value) - - Emits a `key`-`value` pair for further processing by CouchDB after the map - function is done. - - :param key: The view key - :param value: The `key`'s associated value - - .. code-block:: javascript - - function(doc){ - emit(doc._id, doc._rev); - } - - -.. function:: getRow() - - Extracts the next row from a related view result. - - :return: View result row - :rtype: object - - .. code-block:: javascript - - function(head, req){ - send('['); - row = getRow(); - if (row){ - send(toJSON(row)); - while(row = getRow()){ - send(','); - send(toJSON(row)); - } - } - return ']'; - } - - -.. data:: JSON - - `JSON2 `_ - object. - - -.. function:: isArray(obj) - - A helper function to check if the provided value is an `Array`. - - :param obj: Any Javascript value - :return: ``true`` if `obj` is `Array`-typed, ``false`` otherwise - :rtype: boolean - - -.. function:: log(message) - - Log a message to the CouchDB log (at the `INFO` level). - - :param message: Message to be logged - - .. code-block:: javascript - - function(doc){ - log('Procesing doc ' + doc['_id']); - emit(doc['_id'], null); - } - - After the map function has run, the following line can be found in CouchDB - logs (e.g. at `/var/log/couchdb/couch.log`): - - .. code-block:: text - - [Sat, 03 Nov 2012 17:38:02 GMT] [info] [<0.7543.0>] OS Process #Port<0.3289> Log :: Processing doc 8d300b86622d67953d102165dbe99467 - - -.. function:: provides(key, func) - - Registers callable handler for specified MIME key. - - :param key: MIME key previously defined by :func:`registerType` - :param func: MIME type handler - - -.. function:: registerType(key, *mimes) - - Registers list of MIME types by associated `key`. - - :param key: MIME types - :param mimes: MIME types enumeration - - Predefined mappings (`key`-`array`): - - - **all**: ``*/*`` - - **text**: ``text/plain; charset=utf-8``, ``txt`` - - **html**: ``text/html; charset=utf-8`` - - **xhtml**: ``application/xhtml+xml``, ``xhtml`` - - **xml**: ``application/xml``, ``text/xml``, ``application/x-xml`` - - **js**: ``text/javascript``, ``application/javascript``, - ``application/x-javascript`` - - **css**: ``text/css`` - - **ics**: ``text/calendar`` - - **csv**: ``text/csv`` - - **rss**: ``application/rss+xml`` - - **atom**: ``application/atom+xml`` - - **yaml**: ``application/x-yaml``, ``text/yaml`` - - **multipart_form**: ``multipart/form-data`` - - **url_encoded_form**: ``application/x-www-form-urlencoded`` - - **json**: ``application/json``, ``text/x-json`` - - -.. function:: require(path) - - Loads CommonJS module by a specified `path`. The path should not start with - a slash. - - :param path: A CommonJS module path started from design document root - :return: Exported statements - - -.. function:: send(chunk) - - Sends a single string `chunk` in response. - - :param chunk: Text chunk - - .. code-block:: javascript - - function(head, req){ - send('Hello,'); - send(' '); - send('Couch'); - return ! - } - - -.. function:: start(init_resp) - - Initiates chunked response. As an option, a custom - :ref:`response ` object may be sent at this point. - For `list`-functions only! - - .. note:: - - list functions may set the `HTTP response code` and `headers` by calling - this function. This function must be called before :func:`send`, - :func:`getRow` or a `return` statement; otherwise, the query server will - implicitly call this function with the empty object (``{}``). - - .. code-block:: javascript - - function(head, req){ - start({ - "code": 302, - "headers": { - "Location": "http://couchdb.apache.org" - } - }); - return "Relax!"; - } - - -.. function:: sum(arr) - - Sum `arr`'s items. - - :param arr: Array of numbers - :rtype: number - - -.. function:: toJSON(obj) - - Encodes `obj` to JSON string. This is an alias for the ``JSON.stringify`` - method. - - :param obj: JSON encodable object - :return: JSON string - -.. _commonjs: - -CommonJS Modules ----------------- - -Support for `CommonJS Modules `_ -(introduced in CouchDB 0.11.0) allows you to create modular design functions -without the need for duplication of functionality. - -Here's a CommonJS module that checks user permissions: - -.. code-block:: javascript - - function user_context(userctx, secobj) { - var is_admin = function() { - return userctx.indexOf('_admin') != -1; - } - return {'is_admin': is_admin} - } - - exports['user'] = user_context - -Each module has access to additional global variables: - -- **module** (`object`): Contains information about the stored module - - - **id** (`string`): The module id; a JSON path in ddoc context - - **current** (`code`): Compiled module code object - - **parent** (`object`): Parent frame - - **exports** (`object`): Export statements - -- **exports** (`object`): Shortcut to the ``module.exports`` object - -The CommonJS module can be added to a design document, like so: - -.. code-block:: javascript - - { - "views": { - "lib": { - "security": "function user_context(userctx, secobj) { ... }" - } - }, - "validate_doc_update": "function(newdoc, olddoc, userctx, secobj) { - user = require('lib/security').user(userctx, secobj); - return user.is_admin(); - }" - "_id": "_design/test" - } - -Modules paths are relative to the design document's ``views`` object, but -modules can only be loaded from the object referenced via ``lib``. The -``lib`` structure can still be used for view functions as well, by simply -storing view functions at e.g. ``views.lib.map``, ``views.lib.reduce``, etc.