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 80D4ADF65 for ; Wed, 12 Dec 2012 20:34:01 +0000 (UTC) Received: (qmail 38814 invoked by uid 500); 12 Dec 2012 20:34:00 -0000 Delivered-To: apmail-couchdb-commits-archive@couchdb.apache.org Received: (qmail 38667 invoked by uid 500); 12 Dec 2012 20:34:00 -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 38218 invoked by uid 99); 12 Dec 2012 20:33:59 -0000 Received: from tyr.zones.apache.org (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 12 Dec 2012 20:33:59 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id 3D5A881B9A5; Wed, 12 Dec 2012 20:33:59 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit From: dch@apache.org To: commits@couchdb.apache.org X-Mailer: ASF-Git Admin Mailer Subject: [8/34] Transmogrify Couchbase XML to .rst and support Sphinx Message-Id: <20121212203359.3D5A881B9A5@tyr.zones.apache.org> Date: Wed, 12 Dec 2012 20:33:59 +0000 (UTC) http://git-wip-us.apache.org/repos/asf/couchdb/blob/de115c3a/share/doc/src/config_reference.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/config_reference.rst b/share/doc/src/config_reference.rst new file mode 100644 index 0000000..b2e78cf --- /dev/null +++ b/share/doc/src/config_reference.rst @@ -0,0 +1,288 @@ +.. 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. + +Configuration options reference +=============================== + + +Configuration Groups +-------------------- + ++----------------------------------+-------------------------------------------+ +| Section | Description | ++==================================+===========================================+ +| attachments | Attachment options | ++----------------------------------+-------------------------------------------+ +| couchdb | CouchDB specific options | ++----------------------------------+-------------------------------------------+ +| couch_httpd_auth | HTTPD Authentication options | ++----------------------------------+-------------------------------------------+ +| daemons | Daemons and background processes | ++----------------------------------+-------------------------------------------+ +| httpd | HTTPD Server options | ++----------------------------------+-------------------------------------------+ +| httpd_db_handlers | Database Operation handlers | ++----------------------------------+-------------------------------------------+ +| httpd_design_handlers | Handlers for design document operations | ++----------------------------------+-------------------------------------------+ +| httpd_global_handlers | Handlers for global operations | ++----------------------------------+-------------------------------------------+ +| log | Logging options | ++----------------------------------+-------------------------------------------+ +| query_servers | Query Server options | ++----------------------------------+-------------------------------------------+ +| query_server_config | Query server options | ++----------------------------------+-------------------------------------------+ +| replicator | Replicator Options | ++----------------------------------+-------------------------------------------+ +| ssl | SSL (Secure Sockets Layer) Options | ++----------------------------------+-------------------------------------------+ +| stats | Statistics options | ++----------------------------------+-------------------------------------------+ +| uuids | UUID generation options | ++----------------------------------+-------------------------------------------+ + +attachments Configuration Options +--------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| compressible_types | compressible_types | ++--------------------------------------+---------------------------------------+ +| compression_level | compression_level | ++--------------------------------------+---------------------------------------+ + +couchdb Configuration Options +----------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| database_dir | database_dir | ++--------------------------------------+---------------------------------------+ +| delayed_commits | delayed_commits | ++--------------------------------------+---------------------------------------+ +| max_attachment_chunk_size | max_attachment_chunk_size | ++--------------------------------------+---------------------------------------+ +| max_dbs_open | max_dbs_open | ++--------------------------------------+---------------------------------------+ +| max_document_size | max_document_size | ++--------------------------------------+---------------------------------------+ +| os_process_timeout | os_process_timeout | ++--------------------------------------+---------------------------------------+ +| uri_file | uri_file | ++--------------------------------------+---------------------------------------+ +| util_driver_dir | util_driver_dir | ++--------------------------------------+---------------------------------------+ +| view_index_dir | view_index_dir | ++--------------------------------------+---------------------------------------+ + +daemons Configuration Options +----------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| auth_cache | auth_cache | ++--------------------------------------+---------------------------------------+ +| db_update_notifier | db_update_notifier | ++--------------------------------------+---------------------------------------+ +| external_manager | external_manager | ++--------------------------------------+---------------------------------------+ +| httpd | httpd | ++--------------------------------------+---------------------------------------+ +| httpsd | Enabled HTTPS service | ++--------------------------------------+---------------------------------------+ +| query_servers | query_servers | ++--------------------------------------+---------------------------------------+ +| stats_aggregator | stats_aggregator | ++--------------------------------------+---------------------------------------+ +| stats_collector | stats_collector | ++--------------------------------------+---------------------------------------+ +| uuids | uuids | ++--------------------------------------+---------------------------------------+ +| view_manager | view_manager | ++--------------------------------------+---------------------------------------+ + +httpd_db_handlers Configuration Options +--------------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| _changes | _changes | ++--------------------------------------+---------------------------------------+ +| _compact | _compact | ++--------------------------------------+---------------------------------------+ +| _design | _design | ++--------------------------------------+---------------------------------------+ +| _temp_view | _temp_view | ++--------------------------------------+---------------------------------------+ +| _view_cleanup | _view_cleanup | ++--------------------------------------+---------------------------------------+ + +couch_httpd_auth Configuration Options +-------------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| auth_cache_size | auth_cache_size | ++--------------------------------------+---------------------------------------+ +| authentication_db | authentication_db | ++--------------------------------------+---------------------------------------+ +| authentication_redirect | authentication_redirect | ++--------------------------------------+---------------------------------------+ +| require_valid_user | require_valid_user | ++--------------------------------------+---------------------------------------+ +| timeout | timeout | ++--------------------------------------+---------------------------------------+ + +httpd Configuration Options +--------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| allow_jsonp | allow_jsonp | ++--------------------------------------+---------------------------------------+ +| authentication_handlers | authentication_handlers | ++--------------------------------------+---------------------------------------+ +| bind_address | bind_address | ++--------------------------------------+---------------------------------------+ +| default_handler | default_handler | ++--------------------------------------+---------------------------------------+ +| max_connections | max_connections | ++--------------------------------------+---------------------------------------+ +| nodelay | Enable TCP_NODELAY | ++--------------------------------------+---------------------------------------+ +| port | port | ++--------------------------------------+---------------------------------------+ +| secure_rewrites | secure_rewrites | ++--------------------------------------+---------------------------------------+ +| vhost_global_handlers | vhost_global_handlers | ++--------------------------------------+---------------------------------------+ + +httpd_design_handlers Configuration Options +------------------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| _info | _info | ++--------------------------------------+---------------------------------------+ +| _list | _list | ++--------------------------------------+---------------------------------------+ +| _rewrite | _rewrite | ++--------------------------------------+---------------------------------------+ +| _show | _show | ++--------------------------------------+---------------------------------------+ +| _update | _update | ++--------------------------------------+---------------------------------------+ +| _view | _view | ++--------------------------------------+---------------------------------------+ + +httpd_global_handlers Configuration Options +------------------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| / | / | ++--------------------------------------+---------------------------------------+ +| _active_tasks | _active_tasks | ++--------------------------------------+---------------------------------------+ +| _all_dbs | _all_dbs | ++--------------------------------------+---------------------------------------+ +| _config | _config | ++--------------------------------------+---------------------------------------+ +| _log | _log | ++--------------------------------------+---------------------------------------+ +| _oauth | _oauth | ++--------------------------------------+---------------------------------------+ +| _replicate | _replicate | ++--------------------------------------+---------------------------------------+ +| _restart | _restart | ++--------------------------------------+---------------------------------------+ +| _session | _session | ++--------------------------------------+---------------------------------------+ +| _stats | _stats | ++--------------------------------------+---------------------------------------+ +| _utils | _utils | ++--------------------------------------+---------------------------------------+ +| _uuids | _uuids | ++--------------------------------------+---------------------------------------+ +| favicon.ico | favicon.ico | ++--------------------------------------+---------------------------------------+ + +log Configuration Options +------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| file | file | ++--------------------------------------+---------------------------------------+ +| include_sasl | include_sasl | ++--------------------------------------+---------------------------------------+ +| level | level | ++--------------------------------------+---------------------------------------+ + +query_servers Configuration Options +----------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| javascript | javascript | ++--------------------------------------+---------------------------------------+ + +query_server_config Configuration Options +----------------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| reduce_limit | reduce_limit | ++--------------------------------------+---------------------------------------+ + +replicator Configuration Options +-------------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| max_http_pipeline_size | max_http_pipeline_size | ++--------------------------------------+---------------------------------------+ +| max_http_sessions | max_http_sessions | ++--------------------------------------+---------------------------------------+ + +stats Configuration Options +--------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| rate | rate | ++--------------------------------------+---------------------------------------+ +| samples | samples | ++--------------------------------------+---------------------------------------+ + +uuids Configuration Options +--------------------------- + ++--------------------------------------+---------------------------------------+ +| Option | Description | ++======================================+=======================================+ +| algorithm | algorithm | ++--------------------------------------+---------------------------------------+ http://git-wip-us.apache.org/repos/asf/couchdb/blob/de115c3a/share/doc/src/configuring.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/configuring.rst b/share/doc/src/configuring.rst new file mode 100644 index 0000000..58240d7 --- /dev/null +++ b/share/doc/src/configuring.rst @@ -0,0 +1,148 @@ +.. 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. + +.. _configuring: + +=================== +Configuring CouchDB +=================== + +.. todo:: Configuring CouchDB + +CouchDB Configuration Files +=========================== + +.. todo:: CouchDB Configuration Files + +Configuration File Locations +============================ + +CouchDB reads files from the following locations, in the following +order. + +1. ``PREFIX/default.ini`` + +2. ``PREFIX/default.d/*`` + +3. ``PREFIX/local.ini`` + +4. ``PREFIX/local.d/*`` + +Settings in successive documents override the settings in earlier +entries. For example, setting the ``bind_address`` parameter in +``local.ini`` would override any setting in ``default.ini``. + +.. warning:: + The ``default.ini`` file may be overwritten during an upgrade or + re-installation, so localised changes should be made to the + ``local.ini`` file or files within the ``local.d`` directory. + +.. _update-notifications: + +Update Notifications +==================== + +.. todo:: Update Notifications + + +MochiWeb Server Options +======================= + +Server options for the MochiWeb component of CouchDB can be added to the +configuration files. Settings should be added to the ``server_options`` +option of the ``[httpd]`` section of ``local.ini``. For example: + +.. code-block:: ini + + [httpd] + server_options = [{backlog, 128}, {acceptor_pool_size, 16}] + +Socket Options Configuration Setting +==================================== + +The socket options for the listening socket in CouchDB can now be set +within the CouchDB configuration file. The setting should be added to +the ``[httpd]`` section of the file using the option name +``socket_options``. The specification is as a list of tuples. For +example: + +.. code-block:: ini + + [httpd] + socket_options = [{recbuf, 262144}, {sndbuf, 262144}, {nodelay, true}] + +The options supported are a subset of full options supported by the +TCP/IP stack. A list of the supported options are provided in the +`Erlang inet`_ documentation. + +.. _Erlang inet: http://www.erlang.org/doc/man/inet.html#setopts-2 + +``vhosts`` definitions +====================== + +Similar to the rewrites section of a ``_design`` document, the +``vhosts`` system uses variables in the form of ``:varname`` or wildcards in +the form of asterisks. The variable results can be output into the +resulting path as they are in the rewriter. + + +Configuring Server Administrators +================================= + +A default CouchDB install provides admin-level access to all connecting users. +This configuration is known as ``Admin Party``, and is not recommended for +in-production usage. You can crash the party simply by creating the first +admin account. CouchDB server administrators and passwords are not stored +in the ``_users`` database, but in the ``local.ini`` file, which should be +appropriately secured and readable only by system administrators. + +.. code-block:: ini + + [admins] + ;admin = mysecretpassword + admin = -hashed-6d3c30241ba0aaa4e16c6ea99224f915687ed8cd,7f4a3e05e0cbc6f48a0035e3508eef90 + architect = -pbkdf2-43ecbd256a70a3a2f7de40d2374b6c3002918834,921a12f74df0c1052b3e562a23cd227f,10000 + +Administrators can be added directly to the ``[admins]`` section, and when +CouchDB is restarted, the passwords will be salted and encrypted. By using +the HTTP, administrator accounts may be created immediately without needing +a restart, nor of storing the plaintext password temporarily. The HTTP +``_config/admins`` endpoint supports querying, deleting or creating new +administrator accounts: + +.. code-block:: bash + + shell> GET /_config/admins HTTP/1.1 + Accept: application/json + Host: localhost:5984 + + HTTP/1.1 200 OK + Cache-Control: must-revalidate + Content-Length: 196 + Content-Type: application/json + Date: Fri, 30 Nov 2012 11:37:18 GMT + Server: CouchDB/1.3.0 (Erlang OTP/R15B02) + +.. code-block:: json + + { + "admin": "-hashed-6d3c30241ba0aaa4e16c6ea99224f915687ed8cd,7f4a3e05e0cbc6f48a0035e3508eef90", + "architect": "-pbkdf2-43ecbd256a70a3a2f7de40d2374b6c3002918834,921a12f74df0c1052b3e562a23cd227f,10000" + } + +Further details are available in ``security_``, including configuring the +work factor for ``PBKDF2``, and the algorithm itself at +`PBKDF2 (RFC-2898) `_. + +.. versionadded:: + 1.3.0 ``PBKDF2`` server-side hashed salted password support added, + now as a synchronous call for the ``_config/admins`` API. http://git-wip-us.apache.org/repos/asf/couchdb/blob/de115c3a/share/doc/src/ddocs.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/ddocs.rst b/share/doc/src/ddocs.rst new file mode 100644 index 0000000..368f49e --- /dev/null +++ b/share/doc/src/ddocs.rst @@ -0,0 +1,724 @@ +.. 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 + +.. _ddocs: + +=========== +Design Docs +=========== + +In this section we'll show how to write design documents, using the built-in +:ref:`JavaScript Query Server `. + +But before we start to write our first function, let's take a look at the list +of common objects that will be used during our code journey - we'll be using +them extensively within each function: + +- :ref:`Database information object ` +- :ref:`Request object ` +- :ref:`Response object ` +- :ref:`UserCtx object ` +- :ref:`Database Security object ` +- :ref:`Guide to JavaScript Query Server ` + +.. _viewfun: + +View functions +============== + +Views are the primary tool used for querying and reporting on CouchDB databases. + +.. _mapfun: + +Map functions +------------- + +.. function:: mapfun(doc) + + :param doc: Processed document object. + +Map functions should take a single argument as document object and optionally +emits paired values also known as `key` and `value`. Since JavaScript +doesn't support generators and ``yield`` statement it is emulated via :func:`emit`: + +.. code-block:: javascript + + function(doc){ + if (!doc.tags || !isArray(doc.tags) || !doc.type || doc.type != 'post'){ + return; + } + for (var idx in doc.tags){ + emit(doc.tags[idx].toLower(), 1); + } + } + +In this example the map function produces documents view by tag if they +has `tags` attribute as array and `type` attribute with "post" value. Note that +:func:`emit` function could be called multiple times, so the same document +will be available by several `keys`. + +Also keep in mind that each document is *sealed* to prevent situation when one +map function changes document state and the other one received a modified +version. + +For efficiency reasons, documents are passed to a group of map functions - +each document is processed by group of map functions from all views of +related design document. This means that if you trigger index update for one +view in ddoc, all others will get updated too. + +Since `1.1.0` release `map` function supports +:ref:`CommonJS ` modules and access to :func:`require` function. + +.. _reducefun: + +Reduce and rereduce functions +----------------------------- + +.. function:: redfun(keys, values[, rereduce]) + + :param keys: Array of pairs docid-key for related map function result. + Always ``null`` if rereduce is running (has ``true`` value). + :param values: Array of map function result values. + :param rereduce: Boolean sign of rereduce run. + + :return: Reduces `values` + +Reduce functions takes two required arguments of keys and values lists - the +result of the related map function - and optional third one which indicates if +`rereduce` mode is active or not. `Rereduce` is using for additional reduce +values list, so when it is ``true`` there is no information about related `keys` +(first argument is ``null``). + +Note, that if produced result by `reduce` function is longer than initial +values list then a Query Server error will be raised. However, this behavior +could be disabled by setting ``reduce_limit`` config option to ``false``: + +.. code-block:: ini + + [query_server_config] + reduce_limit = false + +While disabling ``reduce_limit`` might be useful for debug proposes, remember, +that main task of reduce functions is to *reduce* mapped result, not to make it +even bigger. Generally, your reduce function should converge rapidly to a single +value - which could be an array or similar object. + +Also CouchDB has three built-in reduce functions. These are implemented in +Erlang and run right inside CouchDB, so they are much faster than the equivalent +JavaScript functions: ``_sum``, ``_count`` and ``_stats``. Their equivalents in +JavaScript below: + +.. code-block:: javascript + + // could be replaced by _sum + function(keys, values){ + sum(values); + } + + // could be replaced by _count + function(keys, values, rereduce){ + if (rereduce){ + return sum(values); + } else { + return values.length; + } + } + + // could be replaced by _stats + function(keys, values, rereduce){ + return { + 'sum': sum(values), + 'min': Math.min.apply(null, values), + 'max': Math.max.apply(null, values), + 'count': values.length, + 'sumsqr': (function(){ + _sumsqr = 0; + for(var idx in values){ + _sumsqr += values[idx] * values[idx]; + } + return _sumsqr; + })(), + } + } + +.. note:: **Why don't reduce functions support CommonJS modules?** + + While `map` functions have limited access to stored modules through + :func:`require` function there is no such feature for `reduce` functions. + The reason lies deep inside in mechanism how `map` and `reduce` functions + are processed by Query Server. Let's take a look on `map` functions first: + + #. CouchDB sends all `map` functions for processed design document to + Query Server. + #. Query Server handles them one by one, compiles and puts them onto an + internal stack. + #. After all `map` functions had been processed, CouchDB will send the + remaining documents to index one by one. + #. The Query Server receives the document object and applies it to every function + from the stack. The emitted results are then joined into a single array and sent + back to CouchDB. + + Now let's see how `reduce` functions are handled: + + #. CouchDB sends *as single command* list of available `reduce` functions + with result list of key-value pairs that was previously received as + result of `map` functions work. + #. Query Server compiles reduce functions and applies them to key-value + lists. Reduced result sends back to CouchDB. + + As you may note, `reduce` functions been applied in single shot while + `map` ones are applied in an iterative way per each document. This means that + it's possible for `map` functions to precompile CommonJS libraries and use them + during the entire view processing, but for `reduce` functions it will be + compiled again and again for each view result reduction, which will lead to + performance degradation (`reduce` function are already does hard work to make + large result smaller). + + +.. _showfun: + +Show functions +============== + +.. function:: showfun(doc, req) + + :param doc: Processed document, may be omitted. + :param req: :ref:`Request object `. + + :return: :ref:`Response object ` + :rtype: object or string + +Show functions are used to represent documents in various formats, commonly as +HTML page with nicer formatting. They can also be used to run server-side functions +without requiring a pre-existing document. + +Basic example of show function could be: + +.. code-block:: javascript + + function(doc, req){ + if (doc){ + return "Hello from " + doc._id + "!"; + } else { + return "Hello, world!"; + } + } + +Also, there is more simple way to return json encoded data: + +.. code-block:: javascript + + function(doc, req){ + return { + 'json': { + 'id': doc['_id'], + 'rev': doc['_rev'] + } + } + } + + +and even files (this one is CouchDB logo): + +.. code-block:: javascript + + function(doc, req){ + return { + 'headers': { + 'Content-Type' : 'image/png', + }, + 'base64': ''.concat( + 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAsV', + 'BMVEUAAAD////////////////////////5ur3rEBn////////////////wDBL/', + 'AADuBAe9EB3IEBz/7+//X1/qBQn2AgP/f3/ilpzsDxfpChDtDhXeCA76AQH/v7', + '/84eLyWV/uc3bJPEf/Dw/uw8bRWmP1h4zxSlD6YGHuQ0f6g4XyQkXvCA36MDH6', + 'wMH/z8/yAwX64ODeh47BHiv/Ly/20dLQLTj98PDXWmP/Pz//39/wGyJ7Iy9JAA', + 'AADHRSTlMAbw8vf08/bz+Pv19jK/W3AAAAg0lEQVR4Xp3LRQ4DQRBD0QqTm4Y5', + 'zMxw/4OleiJlHeUtv2X6RbNO1Uqj9g0RMCuQO0vBIg4vMFeOpCWIWmDOw82fZx', + 'vaND1c8OG4vrdOqD8YwgpDYDxRgkSm5rwu0nQVBJuMg++pLXZyr5jnc1BaH4GT', + 'LvEliY253nA3pVhQqdPt0f/erJkMGMB8xucAAAAASUVORK5CYII=') + } + } + +But what if you need to represent data in different formats via a single function? +Functions :func:`registerType` and :func:`provides` are your the best friends in +that question: + +.. code-block:: javascript + + function(doc, req){ + provides('json', function(){ + return {'json': doc} + }); + provides('html', function(){ + return '
' + toJSON(doc) + '
' + }) + provides('xml', function(){ + return { + 'headers': {'Content-Type': 'application/xml'}, + 'body' : ''.concat( + '\n', + '', + (function(){ + escape = function(s){ + return s.replace(/"/g, '"') + .replace(/>/g, '>') + .replace(/</g, '<') + .replace(/&/g, '&'); + }; + var content = ''; + for(var key in doc){ + if(!doc.hasOwnProperty(key)) continue; + var value = escape(toJSON(doc[key])); + var key = escape(key); + content += ''.concat( + '<' + key + '>', + value + '' + ) + } + return content; + })(), + '' + ) + } + }) + registerType('text-json', 'text/json') + provides('text-json', function(){ + return toJSON(doc); + }) + } + +This function may return `html`, `json` , `xml` or our custom `text json` format +representation of same document object with same processing rules. Probably, +the `xml` provider in our function needs more care to handle nested objects +correctly, and keys with invalid characters, but you've got the idea! + +.. seealso:: + + CouchDB Wiki: + - `Showing Documents `_ + + CouchDB Guide: + - `Show Functions `_ + + +.. _listfun: + +List functions +============== + +.. function:: listfun(head, req) + + :param head: :ref:`view_head_info_object` + :param req: :ref:`Request object `. + + :return: Last chunk. + :rtype: string + +While :ref:`showfun` are used to customize document presentation, :ref:`listfun` +are used for same purpose, but against :ref:`viewfun` results. + +The next list function formats view and represents it as a very simple HTML page: + +.. code-block:: javascript + + function(head, req){ + start({ + 'headers': { + 'Content-Type': 'text/html' + } + }); + send(''); + send('') + while(row = getRow()){ + send(''.concat( + '', + '', + '', + '', + '' + )); + } + send('
IDKeyValue
' + toJSON(row.id) + '' + toJSON(row.key) + '' + toJSON(row.value) + '
'); + } + +Templates and styles could obviously be used to present data in a nicer +fashion, but this is an excellent starting point. Note that you may also +use :func:`registerType` and :func:`provides` functions in the same +way as for :ref:`showfun`! + +.. seealso:: + + CouchDB Wiki: + - `Listing Views with CouchDB 0.10 and later `_ + + CouchDB Guide: + - `Transforming Views with List Functions `_ + + +.. _updatefun: + +Update functions +================ + +.. function:: updatefun(doc, req) + + :param doc: Update function target document. + :param req: :ref:`request_object` + + :returns: Two-element array: the first element is the (updated or new) + document, which is committed to the database. If the first element + is ``null`` no document will be committed to the database. + If you are updating an existing, it should already have an ``_id`` + set, and if you are creating a new document, make sure to set its + ``_id`` to something, either generated based on the input or the + ``req.uuid`` provided. The second element is the response that will + be sent back to the caller. + +Update handlers are functions that clients can request to invoke server-side +logic that will create or update a document. This feature allows a range of use +cases such as providing a server-side last modified timestamp, updating +individual fields in a document without first getting the latest revision, etc. + +When the request to an update handler includes a document ID in the URL, the +server will provide the function with the most recent version of that document. +You can provide any other values needed by the update handler function via the +``POST``/``PUT`` entity body or query string parameters of the request. + +The basic example that demonstrates all use-cases of update handlers below: + +.. code-block:: javascript + + function(doc, req){ + if (!doc){ + if ('id' in req){ + // create new document + return [{'_id': req['id']}, 'New World'] + } + // change nothing in database + return [null, 'Empty World'] + } + doc['world'] = 'hello'; + doc['edited_by'] = req['userCtx']['name'] + return [doc, 'Edited World!'] + } + +.. seealso:: + + CouchDB Wiki: + - `Document Update Handlers `_ + + +.. _filterfun: + +Filter functions +================ + +.. function:: filterfun(doc, req) + + :param doc: Processed document object. + :param req: :ref:`request_object` + :return: Boolean value: ``true`` means that `doc` passes the filter rules, + ``false`` that not. + +Filter functions are mostly acts like :ref:`showfun` and :ref:`listfun`: they +formats, but more correctly to say, they *filters* :ref:`changes feed`. + +Classic filters +--------------- + +By default the changes feed emits all database documents changes. But if you're +waiting for some special changes, processing all documents is inefficient. + +Filters are special design document functions that allows changes feed to emit +only specific documents that pass filter rules. + +Lets assume that our database is a mailbox and we need to to handle only new mails +(documents with status `new`) events. Assuming that, our filter function +will looks like next one: + +.. code-block:: javascript + + function(doc, req){ + // we need only `mail` documents + if (doc.type != 'mail'){ + return false; + } + // we're interested only in `new` ones + if (doc.status != 'new'){ + return false; + } + return true; // passed! + } +  +Filter functions must return ``true`` in fact if document passed all defined +rules. Now, if you apply this function to changes feed it will emit only changes +about "new mails":: + + GET /somedatabase/_changes?filter=mailbox/new_mail HTTP/1.1 + +.. code-block:: javascript + + {"results":[ + {"seq":1,"id":"df8eca9da37dade42ee4d7aa3401f1dd","changes":[{"rev":"1-c2e0085a21d34fa1cecb6dc26a4ae657"}]}, + {"seq":7,"id":"df8eca9da37dade42ee4d7aa34024714","changes":[{"rev":"1-29d748a6e87b43db967fe338bcb08d74"}]}, + ], + "last_seq":27} + +Note, that ``last_seq`` number is 27, but we'd received only two records. +Seems like any other changes was about documents that hasn't passed our filter. + +Probably, we also need to filter changes feed of our mailbox not only by single +status value: we're also interested in statuses like "spam" to update +spam-filter heuristic rules, "outgoing" to let mail daemon actually send mails +and so on. Creating a lot of similar functions that actually does similar work +isn't good idea - so we need dynamic filter to go. + +If you have noted, filter functions takes second argument as +:ref:`request ` object - it allows to create dynamic filters +based on query parameters, :ref:`user context ` and more. + +The dynamic version of our filter now will be next: + +.. code-block:: javascript + + function(doc, req){ + // we need only `mail` documents + if (doc.type != 'mail'){ + return false; + } + // we're interested only in requested status + if (doc.status != req.query.status){ + return false; + } + return true; // passed! + } + +and now we have pass `status` query parameter in request to let filter match +only required documents:: + + GET /somedatabase/_changes?filter=mailbox/by_status&status=new HTTP/1.1 + +.. code-block:: javascript + + {"results":[ + {"seq":1,"id":"df8eca9da37dade42ee4d7aa3401f1dd","changes":[{"rev":"1-c2e0085a21d34fa1cecb6dc26a4ae657"}]}, + {"seq":7,"id":"df8eca9da37dade42ee4d7aa34024714","changes":[{"rev":"1-29d748a6e87b43db967fe338bcb08d74"}]}, + ], + "last_seq":27} + +and we can change filter behavior with easy:: + + GET /somedatabase/_changes?filter=mailbox/by_status&status=spam HTTP/1.1 + +.. code-block:: javascript + + {"results":[ + {"seq":11,"id":"8960e91220798fc9f9d29d24ed612e0d","changes":[{"rev":"3-cc6ff71af716ddc2ba114967025c0ee0"}]}, + ], + "last_seq":27} + + +Combining filters with `continuous` feed allows to create powerful event-driven +systems. + +View filters +------------ + +View filters are the same as above, with one small difference: they use +views `map` function instead to `filter` one to process the changes feed. Each +time when a key-value pair could be emitted, a change is returned. This allows +to avoid creating filter functions that are mostly does same works as views. + +To use them just specify `_view` value for ``filter`` parameter and +`designdoc/viewname` for ``view`` one:: + + GET /somedatabase/_changes?filter=_view&view=dname/viewname HTTP/1.1 + +.. note:: + + Since view filters uses `map` functions as filters, they can't show any + dynamic behavior since :ref:`request object` is not + available. + +.. seealso:: + + CouchDB Guide: + - `Guide to filter change notification `_ + + CouchDB Wiki: + - `Filtered replication `_ + + +.. _vdufun: + +Validate document update functions +================================== + +.. function:: validatefun(newDoc, oldDoc, userCtx, secObj) + + :param newDoc: New version of document that will be stored. + :param oldDoc: Previous version of document that is already stored. + :param userCtx: :ref:`userctx_object` + :param secObj: :ref:`security_object` + + :throws: ``forbidden`` error to gracefully prevent document storing. + +To perform validate operations on document saving there is a special design +function type called `validate_doc_update`. + +Instead of thousands words take a look at the next example of validate +function - this function is used in ``_design/_auth`` ddoc from `_users` +database to control users documents required field set and modification +permissions: + +.. code-block:: javascript + + function(newDoc, oldDoc, userCtx, secObj) { + if (newDoc._deleted === true) { + // allow deletes by admins and matching users + // without checking the other fields + if ((userCtx.roles.indexOf('_admin') !== -1) || + (userCtx.name == oldDoc.name)) { + return; + } else { + throw({forbidden: 'Only admins may delete other user docs.'}); + } + } + + if ((oldDoc && oldDoc.type !== 'user') || newDoc.type !== 'user') { + throw({forbidden : 'doc.type must be user'}); + } // we only allow user docs for now + + if (!newDoc.name) { + throw({forbidden: 'doc.name is required'}); + } + + if (!newDoc.roles) { + throw({forbidden: 'doc.roles must exist'}); + } + + if (!isArray(newDoc.roles)) { + throw({forbidden: 'doc.roles must be an array'}); + } + + if (newDoc._id !== ('org.couchdb.user:' + newDoc.name)) { + throw({ + forbidden: 'Doc ID must be of the form org.couchdb.user:name' + }); + } + + if (oldDoc) { // validate all updates + if (oldDoc.name !== newDoc.name) { + throw({forbidden: 'Usernames can not be changed.'}); + } + } + + if (newDoc.password_sha && !newDoc.salt) { + throw({ + forbidden: 'Users with password_sha must have a salt.' + + 'See /_utils/script/couch.js for example code.' + }); + } + + var is_server_or_database_admin = function(userCtx, secObj) { + // see if the user is a server admin + if(userCtx.roles.indexOf('_admin') !== -1) { + return true; // a server admin + } + + // see if the user a database admin specified by name + if(secObj && secObj.admins && secObj.admins.names) { + if(secObj.admins.names.indexOf(userCtx.name) !== -1) { + return true; // database admin + } + } + + // see if the user a database admin specified by role + if(secObj && secObj.admins && secObj.admins.roles) { + var db_roles = secObj.admins.roles; + for(var idx = 0; idx < userCtx.roles.length; idx++) { + var user_role = userCtx.roles[idx]; + if(db_roles.indexOf(user_role) !== -1) { + return true; // role matches! + } + } + } + + return false; // default to no admin + } + + if (!is_server_or_database_admin(userCtx, secObj)) { + if (oldDoc) { // validate non-admin updates + if (userCtx.name !== newDoc.name) { + throw({ + forbidden: 'You may only update your own user document.' + }); + } + // validate role updates + var oldRoles = oldDoc.roles.sort(); + var newRoles = newDoc.roles.sort(); + + if (oldRoles.length !== newRoles.length) { + throw({forbidden: 'Only _admin may edit roles'}); + } + + for (var i = 0; i < oldRoles.length; i++) { + if (oldRoles[i] !== newRoles[i]) { + throw({forbidden: 'Only _admin may edit roles'}); + } + } + } else if (newDoc.roles.length > 0) { + throw({forbidden: 'Only _admin may set roles'}); + } + } + + // no system roles in users db + for (var i = 0; i < newDoc.roles.length; i++) { + if (newDoc.roles[i][0] === '_') { + throw({ + forbidden: + 'No system roles (starting with underscore) in users db.' + }); + } + } + + // no system names as names + if (newDoc.name[0] === '_') { + throw({forbidden: 'Username may not start with underscore.'}); + } + + var badUserNameChars = [':']; + + for (var i = 0; i < badUserNameChars.length; i++) { + if (newDoc.name.indexOf(badUserNameChars[i]) >= 0) { + throw({forbidden: 'Character `' + badUserNameChars[i] + + '` is not allowed in usernames.'}); + } + } + } + +.. note:: + + The ``return`` statement used only for function, it has no impact on + the validation process. + +.. seealso:: + + CouchDB Guide: + - `Validation Functions `_ + + CouchDB Wiki: + - `Document Update Validation `_ http://git-wip-us.apache.org/repos/asf/couchdb/blob/de115c3a/share/doc/src/errors.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/errors.rst b/share/doc/src/errors.rst new file mode 100644 index 0000000..431ff91 --- /dev/null +++ b/share/doc/src/errors.rst @@ -0,0 +1,37 @@ +.. 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. + +Error Messages +============== + +The errors reported when CouchDB is unable to read a required file have +been updated so that explicit information about the files and problem +can now be identified from the error message. The errors report file +permission access either when reading or writing to configuration and +database files. + +The error is raised both through the log file and the error message +returned through the API call as a JSON error message. For example, when +setting configuration values: + +.. code-block:: bash + + shell> curl -X PUT http://couchdb:5984/_config/couchdb/delayed_commits \ + -H 'X-Couch-Persist: true' -d '"false"' + {"error":"file_permission_error","reason":"/etc/couchdb/local.ini"} + +Errors will always be reported using the ``file_permission_error`` error +type. + +During startup permissions errors on key files are also reported in the +log with a descriptive error message and file location so that +permissions can be fixed before restart. http://git-wip-us.apache.org/repos/asf/couchdb/blob/de115c3a/share/doc/src/http-proxying.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/http-proxying.rst b/share/doc/src/http-proxying.rst new file mode 100644 index 0000000..cff2404 --- /dev/null +++ b/share/doc/src/http-proxying.rst @@ -0,0 +1,94 @@ +.. 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. + +.. _http-proxying: + +HTTP Proxying +============= + +The HTTP proxy feature makes it easy to map and redirect different +content through your CouchDB URL. The proxy works by mapping a pathname +and passing all content after that prefix through to the configured +proxy address. + +Configuration of the proxy redirect is handled through the +``[httpd_global_handlers]`` section of the CouchDB configuration file +(typically ``local.ini``). The format is: + +.. code-block:: ini + + [httpd_global_handlers] + PREFIX = {couch_httpd_proxy, handle_proxy_req, <<"DESTINATION">>} + + +Where: + +- ``PREFIX`` + + Is the string that will be matched. The string can be any valid + qualifier, although to ensure that existing database names are not + overridden by a proxy configuration, you can use an underscore + prefix. + +- ``DESTINATION`` + + The fully-qualified URL to which the request should be sent. The + destination must include the ``http`` prefix. The content is used + verbatim in the original request, so you can also forward to servers + on different ports and to specific paths on the target host. + +The proxy process then translates requests of the form: + +.. code-block:: text + + http://couchdb:5984/PREFIX/path + +To: + +.. code-block:: text + + DESTINATION/path + +.. note:: + Everything after ``PREFIX`` including the required forward slash + will be appended to the ``DESTINATION``. + +The response is then communicated back to the original client. + +For example, the following configuration: + +.. code-block:: ini + + _google = {couch_httpd_proxy, handle_proxy_req, <<"http://www.google.com">>} + +Would forward all requests for ``http://couchdb:5984/_google`` to the +Google website. + +The service can also be used to forward to related CouchDB services, +such as Lucene: + +.. code-block:: ini + + [httpd_global_handlers] + _fti = {couch_httpd_proxy, handle_proxy_req, <<"http://127.0.0.1:5985">>} + +.. note:: + The proxy service is basic. If the request is not identified by the + ``DESTINATION``, or the remainder of the ``PATH`` specification is + incomplete, the original request URL is interpreted as if the + ``PREFIX`` component of that URL does not exist. + + For example, requesting ``http://couchdb:5984/_intranet/media`` when + ``/media`` on the proxy destination does not exist, will cause the + request URL to be interpreted as ``http://couchdb:5984/media``. Care + should be taken to ensure that both requested URLs and destination + URLs are able to cope. http://git-wip-us.apache.org/repos/asf/couchdb/blob/de115c3a/share/doc/src/index.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst new file mode 100644 index 0000000..ad3a90d --- /dev/null +++ b/share/doc/src/index.rst @@ -0,0 +1,52 @@ +.. 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. + +Introduction +============ + +|Apache CouchDB(TM)|_ is a document database built for the web. + +If you would like to help document the project, please send a note to the +`developer mailing list `_. + +This is a work in progress. + +Contents +======== + +.. toctree:: + :maxdepth: 2 + :numbered: + + intro + api-basics + range + pretty_urls + configuring + ssl + os-daemons + http-proxying + config_reference + replication + ddocs + query-servers + commonjs + errors + changes + release + api/reference + json-structure + changelog + +.. This is how you get a TM sign into a link. Haha. Seriously. +.. |Apache CouchDB(TM)| unicode:: Apache U+0020 CouchDB U+2122 +.. _Apache CouchDB(TM): http://couchdb.apache.org/ http://git-wip-us.apache.org/repos/asf/couchdb/blob/de115c3a/share/doc/src/intro.rst ---------------------------------------------------------------------- diff --git a/share/doc/src/intro.rst b/share/doc/src/intro.rst new file mode 100644 index 0000000..b5930d3 --- /dev/null +++ b/share/doc/src/intro.rst @@ -0,0 +1,309 @@ +.. 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. + +============ +Introduction +============ + +There are two interfaces to CouchDB, the built-in Futon web-based +interface and the CouchDB API accessed through the HTTP REST interface. +The former is the simplest way to view and monitor your CouchDB +installation and perform a number of basic database and system +operations. More information on using the Futon interface can be found +in :ref:`using-futon`. + +The primary way to interact with the CouchDB API is to use a client +library or other interface that provides access to the underlying +functionality through your chosen language or platform. However, since +the API is supported through HTTP REST, you can interact with your +CouchDB with any solution that supports the HTTP protocol. + +There are a number of different tools that talk the HTTP protocol and +allow you to set and configure the necessary information. One tool for +this that allows for access from the command-line is ``curl``. See +:ref:`using-curl`. + +.. _using-futon: + +Using Futon +=========== + +Futon is a native web-based interface built into CouchDB. It provides a +basic interface to the majority of the functionality, including the +ability to create, update, delete and view documents and views, provides +access to the configuration parameters, and an interface for initiating +replication. + +The default view is the Overview page which provides you with a list of +the databases. The basic structure of the page is consistent regardless +of the section you are in. The main panel on the left provides the main +interface to the databases, configuration or replication systems. The +side panel on the right provides navigation to the main areas of Futon +interface: + +.. figure:: ../images/futon-overview.png + :align: center + :alt: Futon Overview + + Futon Overview + +The main sections are: + +- Overview + + The main overview page, which provides a list of the databases and + provides the interface for querying the database and creating and + updating documents. See :ref:`futon-management`. + +- Configuration + + An interface into the configuration of your CouchDB installation. The + interface allows you to edit the different configurable parameters. + For more details on configuration, see :ref:`configuring`. + +- Replicator + + An interface to the replication system, enabling you to initiate + replication between local and remote databases. See + :ref:`futon-replication`. + +- Status + + Displays a list of the running background tasks on the server. + Background tasks include view index building, compaction and + replication. The Status page is an interface to the + :ref:`Active Tasks ` API call. + +- Verify Installation + + The Verify Installation allows you to check whether all of the + components of your CouchDB installation are correctly installed. + +- Test Suite + + The Test Suite section allows you to run the built-in test suite. + This executes a number of test routines entirely within your browser + to test the API and functionality of your CouchDB installation. If + you select this page, you can run the tests by using the Run All + button. This will execute all the tests, which may take some time. + +.. _futon-management: + +Managing Databases and Documents +-------------------------------- + +You can manage databases and documents within Futon using the main +Overview section of the Futon interface. + +To create a new database, click the Create Database ELLIPSIS button. You +will be prompted for the database name, as shown in the figure below. + +.. figure:: ../images/futon-createdb.png + :align: center + :alt: Creating a Database + + Creating a Database + +Once you have created the database (or selected an existing one), you +will be shown a list of the current documents. If you create a new +document, or select an existing document, you will be presented with the +edit document display. + +Editing documents within Futon requires selecting the document and then +editing (and setting) the fields for the document individually before +saving the document back into the database. + +For example, the figure below shows the editor for a single document, a +newly created document with a single ID, the document ``_id`` field. + +.. figure:: ../images/futon-editdoc.png + :align: center + :alt: Editing a Document + + Editing a Document + +To add a field to the document: + +1. Click Add Field. + +2. In the fieldname box, enter the name of the field you want to create. + For example, “company”. + +3. Click the green tick next to the field name to confirm the field name + change. + +4. Double-click the corresponding Value cell. + +5. Enter a company name, for example “Example”. + +6. Click the green tick next to the field value to confirm the field + value. + +7. The document is still not saved as this point. You must explicitly + save the document by clicking the Save Document button at the top of + the page. This will save the document, and then display the new + document with the saved revision information (the ``_rev`` field). + + .. figure:: ../images/futon-editeddoc.png + :align: center + :alt: Edited Document + + Edited Document + +The same basic interface is used for all editing operations within Futon. +You *must* remember to save the individual element (fieldname, value) +using the green tick button, before then saving the document. + +.. _futon-replication: + +Configuring Replication +----------------------- + +When you click the Replicator option within the Tools menu you are +presented with the Replicator screen. This allows you to start +replication between two databases by filling in or select the +appropriate options within the form provided. + +.. figure:: ../images/futon-replform.png + :align: center + :alt: Replication Form + + Replication Form + +To start a replication process, either the select the local database or +enter a remote database name into the corresponding areas of the form. +Replication occurs from the database on the left to the database on the +right. + +If you are specifying a remote database name, you must specify the full +URL of the remote database (including the host, port number and database +name). If the remote instance requires authentication, you can specify +the username and password as part of the URL, for example +``http://username:pass@remotehost:5984/demo``. + +To enable continuous replication, click the Continuous checkbox. + +To start the replication process, click the Replicate button. The +replication process should start and will continue in the background. If +the replication process will take a long time, you can monitor the +status of the replication using the Status option under the Tools menu. + +Once replication has been completed, the page will show the information +returned when the replication process completes by the API. + +The Replicator tool is an interface to the underlying replication API. +For more information, see :ref:`replicate`. For more information on +replication, see :ref:`replication`. + +.. _using-curl: + +Using ``curl`` +============== + +The ``curl`` utility is a command line tool available on Unix, Linux, +Mac OS X and Windows and many other platforms. ``curl`` provides easy +access to the HTTP protocol (among others) directly from the +command-line and is therefore an ideal way of interacting with CouchDB +over the HTTP REST API. + +For simple ``GET`` requests you can supply the URL of the request. For +example, to get the database information: + +.. code-block:: bash + + shell> curl http://127.0.0.1:5984 + +This returns the database information (formatted in the output below for +clarity): + +.. code-block:: json + + { + "couchdb" : "Welcome", + "version" : "|version|", + } + +.. note:: For some URLs, especially those that include special characters such + as ampersand, exclamation mark, or question mark, you should quote + the URL you are specifying on the command line. For example: + + .. code-block:: bash + + shell> curl 'http://couchdb:5984/_uuids?count=5' + +You can explicitly set the HTTP command using the ``-X`` command line +option. For example, when creating a database, you set the name of the +database in the URL you send using a PUT request: + +.. code-block:: bash + + shell> curl -X PUT http://127.0.0.1:5984/demo + {"ok":true} + +But to obtain the database information you use a ``GET`` request (with +the return information formatted for clarity): + +.. code-block:: bash + + shell> curl -X GET http://127.0.0.1:5984/demo + { + "compact_running" : false, + "doc_count" : 0, + "db_name" : "demo", + "purge_seq" : 0, + "committed_update_seq" : 0, + "doc_del_count" : 0, + "disk_format_version" : 5, + "update_seq" : 0, + "instance_start_time" : "1306421773496000", + "disk_size" : 79 + } + +For certain operations, you must specify the content type of request, +which you do by specifying the ``Content-Type`` header using the ``-H`` +command-line option: + +.. code-block:: bash + + shell> curl -H 'Content-Type: application/json' http://127.0.0.1:5984/_uuids + +You can also submit 'payload' data, that is, data in the body of the +HTTP request using the ``-d`` option. This is useful if you need to +submit JSON structures, for example document data, as part of the +request. For example, to submit a simple document to the ``demo`` +database: + +.. code-block:: bash + + shell> curl -H 'Content-Type: application/json' \ + -X POST http://127.0.0.1:5984/demo \ + -d '{"company": "Example, Inc."}' + {"ok":true,"id":"8843faaf0b831d364278331bc3001bd8", + "rev":"1-33b9fbce46930280dab37d672bbc8bb9"} + +In the above example, the argument after the ``-d`` option is the JSON +of the document we want to submit. + +The document can be accessed by using the automatically generated +document ID that was returned: + +.. code-block:: bash + + shell> curl -X GET http://127.0.0.1:5984/demo/8843faaf0b831d364278331bc3001bd8 + {"_id":"8843faaf0b831d364278331bc3001bd8", + "_rev":"1-33b9fbce46930280dab37d672bbc8bb9", + "company":"Example, Inc."} + +The API samples in the :ref:`api-basics` show the HTTP command, URL and any +payload information that needs to be submitted (and the expected return +value). All of these examples can be reproduced using ``curl`` with the +command-line examples shown above.