You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by kx...@apache.org on 2013/07/24 14:24:38 UTC

[01/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Updated Branches:
  refs/heads/1781-reorganize-and-improve-docs 1171ec48e -> fa11c25d5 (forced update)


Update base configuration group.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/14d1da44
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/14d1da44
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/14d1da44

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 14d1da4423149df9b3a9f043573a17f10e75a63b
Parents: af75771
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 17 08:45:33 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:36 2013 +0400

----------------------------------------------------------------------
 share/doc/src/config/couchdb.rst | 7 ++++---
 share/doc/src/config/index.rst   | 2 +-
 2 files changed, 5 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/14d1da44/share/doc/src/config/couchdb.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/couchdb.rst b/share/doc/src/config/couchdb.rst
index 6266bf1..56bdb6f 100644
--- a/share/doc/src/config/couchdb.rst
+++ b/share/doc/src/config/couchdb.rst
@@ -12,14 +12,15 @@
 
 .. highlight:: ini
 
+==================
+Base Configuration
+==================
+
 .. _config/couchdb:
 
 ``[couchdb]`` :: Base CouchDB Options
 =====================================
 
-These options are under ``[couchdb]`` section.
-
-
 .. _config/couchdb/attachment_stream_buffer_size:
 
 ``attachment_stream_buffer_size`` :: Attachment streaming buffer

http://git-wip-us.apache.org/repos/asf/couchdb/blob/14d1da44/share/doc/src/config/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/index.rst b/share/doc/src/config/index.rst
index 5e5d4ef..6b2281c 100644
--- a/share/doc/src/config/index.rst
+++ b/share/doc/src/config/index.rst
@@ -20,6 +20,7 @@ Configuring CouchDB
    :maxdepth: 2
 
    intro
+   couchdb
    http
    auth
    compaction
@@ -28,7 +29,6 @@ Configuring CouchDB
    proxying
 
    attachments
-   couchdb
    daemons
    log
    replicator


[50/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add missed license header.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/fa11c25d
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/fa11c25d
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/fa11c25d

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: fa11c25d543f66ce85e6e1b81abc23270d12fc03
Parents: 0c22cf6
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 16:20:18 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 16:20:18 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/database/security.rst   | 13 +++++++++++++
 share/doc/src/api/database/temp-views.rst | 13 +++++++++++++
 2 files changed, 26 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/fa11c25d/share/doc/src/api/database/security.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/security.rst b/share/doc/src/api/database/security.rst
index 8f323f9..ff0fb69 100644
--- a/share/doc/src/api/database/security.rst
+++ b/share/doc/src/api/database/security.rst
@@ -1,3 +1,16 @@
+.. 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.
+
+
 .. _api/db/security:
 .. _api/db/security.get:
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/fa11c25d/share/doc/src/api/database/temp-views.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/temp-views.rst b/share/doc/src/api/database/temp-views.rst
index 7700317..893a258 100644
--- a/share/doc/src/api/database/temp-views.rst
+++ b/share/doc/src/api/database/temp-views.rst
@@ -1,3 +1,16 @@
+.. 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.
+
+
 .. _api/db/temp_view:
 .. _api/db/temp_view.post:
 


[13/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add comparison of replication protocol with Git.

Thanks Jason Smith for the post:
http://stackoverflow.com/a/4766398/965635


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/c199cd9b
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/c199cd9b
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/c199cd9b

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: c199cd9b6392689213a7b85e722ebf9daa7cd476
Parents: 59b7d7f
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 22:49:35 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/replications/conflicts.rst | 85 +++++++++++++++++++++++++++
 1 file changed, 85 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/c199cd9b/share/doc/src/replications/conflicts.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/conflicts.rst b/share/doc/src/replications/conflicts.rst
index bcd948d..404d256 100644
--- a/share/doc/src/replications/conflicts.rst
+++ b/share/doc/src/replications/conflicts.rst
@@ -699,3 +699,88 @@ size, but CouchDB discards them. If you are constantly updating a document,
 the size of a git repo would grow forever. It is possible (with some effort)
 to use "history rewriting" to make git forget commits earlier than a particular
 one.
+
+
+What is the CouchDB replication protocol? Is it like Git?
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+**Key points**
+
+**If you know Git, then you know how Couch replication works.** Replicating is
+*very* similar to pushing or pulling with distributed source managers like Git.
+
+**CouchDB replication does not have its own protocol.** A replicator simply
+connects to two DBs as a client, then reads from one and writes to the other.
+Push replication is reading the local data and updating the remote DB;
+pull replication is vice versa.
+
+* **Fun fact 1**: The replicator is actually an independent Erlang application,
+  in its own process. It connects to both couches, then reads records from one
+  and writes them to the other.
+* **Fun fact 2**: CouchDB has no way of knowing who is a normal client and who
+  is a replicator (let alone whether the replication is push or pull).
+  It all looks like client connections. Some of them read records. Some of them
+  write records.
+
+**Everything flows from the data model**
+
+The replication algorithm is trivial, uninteresting. A trained monkey could
+design it. It's simple because the cleverness is the data model, which has these
+useful characteristics:
+
+#. Every record in CouchDB is completely independent of all others. That sucks
+   if you want to do a JOIN or a transaction, but it's awesome if you want to
+   write a replicator. Just figure out how to replicate one record, and then
+   repeat that for each record.
+#. Like Git, records have a linked-list revision history. A record's revision ID
+   is the checksum of its own data. Subsequent revision IDs are checksums of:
+   the new data, plus the revision ID of the previous.
+
+#. In addition to application data (``{"name": "Jason", "awesome": true}``),
+   every record stores the evolutionary timeline of all previous revision IDs
+   leading up to itself.
+
+   - Exercise: Take a moment of quiet reflection. Consider any two different
+     records, A and B. If A's revision ID appears in B's timeline, then B
+     definitely evolved from A. Now consider Git's fast-forward merges.
+     Do you hear that? That is the sound of your mind being blown.
+
+#. Git isn't really a linear list. It has forks, when one parent has multiple
+   children. CouchDB has that too.
+
+   - Exercise: Compare two different records, A and B. A's revision ID does not
+     appear in B's timeline; however, one revision ID, C, is in both A's and B's
+     timeline. Thus A didn't evolve from B. B didn't evolve from A. But rather,
+     A and B have a common ancestor C. In Git, that is a "fork." In CouchDB,
+     it's a "conflict."
+
+   - In Git, if both children go on to develop their timelines independently,
+     that's cool. Forks totally support that.
+   - In CouchDB, if both children go on to develop their timelines
+     independently, that cool too. Conflicts totally support that.
+   - **Fun fact 3**: CouchDB "conflicts" do not correspond to Git "conflicts."
+     A Couch conflict is a divergent revision history, what Git calls a "fork."
+     For this reason the CouchDB community pronounces "conflict" with a silent
+     `n`: "co-flicked."
+
+#. Git also has merges, when one child has multiple parents. CouchDB *sort* of
+   has that too.
+
+   - **In the data model, there is no merge.** The client simply marks one
+     timeline as deleted and continues to work with the only extant timeline.
+   - **In the application, it feels like a merge.** Typically, the client merges
+     the *data* from each timeline in an application-specific way.
+     Then it writes the new data to the timeline. In Git, this is like copying
+     and pasting the changes from branch A into branch B, then commiting to
+     branch B and deleting branch A. The data was merged, but there was no
+     `git merge`.
+   - These behaviors are different because, in Git, the timeline itself is
+     important; but in CouchDB, the data is important and the timeline is
+     incidental—it's just there to support replication. That is one reason why
+     CouchDB's built-in revisioning is inappropriate for storing revision data
+     like a wiki page.
+
+**Final notes**
+
+At least one sentence in this writeup (possibly this one) is complete BS.
+


[37/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Mention glazier project for Windows install.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/3abdf0e2
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/3abdf0e2
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/3abdf0e2

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 3abdf0e2a128f0e7b4a41318e0e7e3569bbb2017
Parents: c9c775c
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 04:50:17 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/src/install/windows.rst | 5 +++++
 1 file changed, 5 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/3abdf0e2/share/doc/src/install/windows.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/windows.rst b/share/doc/src/install/windows.rst
index 0e8af94..1ecdb5b 100644
--- a/share/doc/src/install/windows.rst
+++ b/share/doc/src/install/windows.rst
@@ -217,3 +217,8 @@ To check that everything has worked, point your web browser to::
     http://127.0.0.1:5984/_utils/index.html
 
 From here you should run the verification tests in Firefox.
+
+
+.. seealso::
+
+   `Glazier: Automate building of CouchDB from source on Windows <https://github.com/dch/glazier>`_


[43/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Init CouchApp's articles group.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/f2a31b58
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/f2a31b58
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/f2a31b58

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: f2a31b589e9a5e54f7f68207b7f15a054f7244f6
Parents: 5450407
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 11:18:19 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 11:18:19 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am      |   9 +-
 share/doc/src/couchapp/ddocs.rst | 753 ++++++++++++++++++++++++++++++++++
 share/doc/src/couchapp/index.rst |  28 ++
 share/doc/src/ddocs.rst          | 753 ----------------------------------
 share/doc/src/index.rst          |   2 +-
 5 files changed, 788 insertions(+), 757 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/f2a31b58/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 322b9db..18f1c41 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -83,6 +83,8 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
+    html/_sources/couchapp/ddocs.txt \
+    html/_sources/couchapp/index.txt \
     html/_sources/fauxton/addons.txt \
     html/_sources/fauxton/index.txt \
     html/_sources/fauxton/install.txt \
@@ -102,7 +104,6 @@ html_files = \
     html/_sources/replications/replicator.txt \
     html/_sources/changelog.txt \
     html/_sources/contributing.txt \
-    html/_sources/ddocs.txt \
     html/_sources/index.txt \
     html/_sources/intro.txt \
     html/_sources/json-structure.txt \
@@ -167,6 +168,8 @@ html_files = \
     html/config/services.html \
     html/config/intro.html \
     html/config/proxying.html \
+    html/couchapp/ddocs.html \
+    html/couchapp/intdex.html \
     html/fauxton/addons.html \
     html/fauxton/index.html \
     html/fauxton/install.html \
@@ -185,7 +188,6 @@ html_files = \
     html/replications/protocol.html \
     html/replications/replicator.html \
     html/changelog.html \
-    html/ddocs.html \
     html/index.html \
     html/intro.html \
     html/json-structure.html \
@@ -249,6 +251,8 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
+    ../src/couchapp/ddocs.rst \
+    ../src/couchapp/index.rst \
     ../src/fauxton/addons.rst \
     ../src/fauxton/index.rst \
     ../src/fauxton/install.rst \
@@ -268,7 +272,6 @@ src_files = \
     ../src/replication/replicator.rst \
     ../src/changelog.rst \
     ../src/contributing.rst \
-    ../src/ddocs.rst \
     ../src/index.rst \
     ../src/intro.rst \
     ../src/json-structure.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/f2a31b58/share/doc/src/couchapp/ddocs.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/ddocs.rst b/share/doc/src/couchapp/ddocs.rst
new file mode 100644
index 0000000..01d3d69
--- /dev/null
+++ b/share/doc/src/couchapp/ddocs.rst
@@ -0,0 +1,753 @@
+.. 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 Functions
+================
+
+In this section we'll show how to write design documents, using the built-in
+:ref:`JavaScript Query Server <query-server/js>`.
+
+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 <dbinfo_object>`
+- :ref:`Request object <request_object>`
+- :ref:`Response object <response_object>`
+- :ref:`UserCtx object <userctx_object>`
+- :ref:`Database Security object <security_object>`
+- :ref:`Guide to JavaScript Query Server <query-server/js>`
+
+.. _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 accept a single document as the argument and (optionally) :func:`emit`
+key/value pairs that are stored in a view.
+
+.. code-block:: javascript
+
+    function (doc) {
+      if (doc.type === 'post' && doc.tags && Array.isArray(doc.tags)) {
+        doc.tags.forEach(function (tag) {
+          emit(tag.toLowerCase(), 1);
+        });
+      }
+    }
+
+In this example a key/value pair is emitted for each value in the `tags` array
+of a document with a `type` of "post". Note that :func:`emit` may be called many
+times for a single document, so the same document may be available by several
+different 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 <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(){
+          var sumsqr = 0;
+
+          values.forEach(function (value) {
+            sumsqr += value * value;
+          });
+
+          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 <request_object>`.
+
+   :return: :ref:`Response object <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 '<pre>' + toJSON(doc) + '</pre>'
+      })
+      provides('xml', function(){
+        return {
+          'headers': {'Content-Type': 'application/xml'},
+          'body' : ''.concat(
+            '<?xml version="1.0" encoding="utf-8"?>\n',
+            '<doc>',
+            (function(){
+              escape = function(s){
+                return s.replace(/&quot;/g, '"')
+                        .replace(/&gt;/g, '>')
+                        .replace(/&lt;/g, '<')
+                        .replace(/&amp;/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
+                  '</' + key + '>'
+                )
+              }
+              return content;
+            })(),
+            '</doc>'
+          )
+        }
+      })
+      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 <http://wiki.apache.org/couchdb/Formatting_with_Show_and_List#Showing_Documents>`_
+
+   CouchDB Guide:
+     - `Show Functions <http://guide.couchdb.org/editions/1/en/show.html>`_
+
+
+.. _listfun:
+
+List functions
+==============
+
+.. function:: listfun(head, req)
+
+   :param head: :ref:`view_head_info_object`
+   :param req: :ref:`Request object <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('<html><body><table>');
+      send('<tr><th>ID</th><th>Key</th><th>Value</th></tr>')
+      while(row = getRow()){
+        send(''.concat(
+          '<tr>',
+          '<td>' + toJSON(row.id) + '</td>',
+          '<td>' + toJSON(row.key) + '</td>',
+          '<td>' + toJSON(row.value) + '</td>',
+          '</tr>'
+        ));
+      }
+      send('</table></body></html>');
+    }
+
+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 <http://wiki.apache.org/couchdb/Formatting_with_Show_and_List#Listing_Views_with_CouchDB_0.10_and_later>`_
+
+   CouchDB Guide:
+    - `Transforming Views with List Functions <http://guide.couchdb.org/draft/transforming.html>`_
+
+
+.. _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 <http://wiki.apache.org/couchdb/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<changes>`.
+
+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 <request_object>` object - it allows to create dynamic filters
+based on query parameters, :ref:`user context <userctx_object>` 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.
+
+.. _viewfilter:
+
+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<request_object>` is not
+   available.
+
+.. seealso::
+
+   CouchDB Guide:
+    - `Guide to filter change notification <http://guide.couchdb.org/draft/notifications.html#filters>`_
+
+   CouchDB Wiki:
+    - `Filtered replication <http://wiki.apache.org/couchdb/Replication#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.
+   :throws: ``unauthorized`` error to prevent storage and allow the user to
+            re-auth.
+
+A design document may contain a function named `validate_doc_update`
+which can be used to prevent invalid or unauthorized document update requests
+from being stored.  The function is passed the new document from the update
+request, the current document stored in the database, a :ref:`userctx_object`
+containing information about the user writing the document (if present), and
+a :ref:`security_object` with lists of database security roles.
+
+Validation functions typically examine the structure of the new document to
+ensure that required fields are present and to verify that the requesting user
+should be allowed to make changes to the document properties.  For example,
+an application may require that a user must be authenticated in order to create
+a new document or that specific document fields be present when a document
+is updated. The validation function can abort the pending document write
+by throwing one of two error objects:
+
+.. code-block:: javascript
+
+  // user is not authorized to make the change but may re-authenticate
+  throw({ unauthorized: 'Error message here.' });
+  
+  // change is not allowed
+  throw({ forbidden: 'Error message here.' });
+
+Document validation is optional, and each design document in the database may
+have at most one validation function.  When a write request is received for
+a given database, the validation function in each design document in that
+database is called in an unspecified order.  If any of the validation functions
+throw an error, the write will not succeed.
+
+**Example**: The ``_design/_auth`` ddoc from `_users` database uses a validation
+function to ensure that documents contain some required fields and are only
+modified by a user with the ``_admin`` role:
+
+.. 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 <http://guide.couchdb.org/editions/1/en/validation.html>`_
+
+   CouchDB Wiki:
+    - `Document Update Validation <http://wiki.apache.org/couchdb/Document_Update_Validation>`_

http://git-wip-us.apache.org/repos/asf/couchdb/blob/f2a31b58/share/doc/src/couchapp/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/index.rst b/share/doc/src/couchapp/index.rst
new file mode 100644
index 0000000..8df4d91
--- /dev/null
+++ b/share/doc/src/couchapp/index.rst
@@ -0,0 +1,28 @@
+.. 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.
+
+========
+CouchApp
+========
+
+`CouchApps`_ are web applications served directly from CouchDB, mostly driven by
+JavaScript and HTML5. If you can fit your application into those constraints,
+then you get CouchDB's scalability and flexibility "for free" (and deploying
+your app is as simple as replicating it to the production server).
+
+.. _CouchApps: http://couchapp.org/
+
+.. toctree::
+   :maxdepth: 2
+
+   ddocs
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/f2a31b58/share/doc/src/ddocs.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/ddocs.rst b/share/doc/src/ddocs.rst
deleted file mode 100644
index 2c1a490..0000000
--- a/share/doc/src/ddocs.rst
+++ /dev/null
@@ -1,753 +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
-
-.. _ddocs:
-
-===========
-Design Docs
-===========
-
-In this section we'll show how to write design documents, using the built-in
-:ref:`JavaScript Query Server <query-server/js>`.
-
-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 <dbinfo_object>`
-- :ref:`Request object <request_object>`
-- :ref:`Response object <response_object>`
-- :ref:`UserCtx object <userctx_object>`
-- :ref:`Database Security object <security_object>`
-- :ref:`Guide to JavaScript Query Server <query-server/js>`
-
-.. _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 accept a single document as the argument and (optionally) :func:`emit`
-key/value pairs that are stored in a view.
-
-.. code-block:: javascript
-
-    function (doc) {
-      if (doc.type === 'post' && doc.tags && Array.isArray(doc.tags)) {
-        doc.tags.forEach(function (tag) {
-          emit(tag.toLowerCase(), 1);
-        });
-      }
-    }
-
-In this example a key/value pair is emitted for each value in the `tags` array
-of a document with a `type` of "post". Note that :func:`emit` may be called many
-times for a single document, so the same document may be available by several
-different 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 <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(){
-          var sumsqr = 0;
-
-          values.forEach(function (value) {
-            sumsqr += value * value;
-          });
-
-          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 <request_object>`.
-
-   :return: :ref:`Response object <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 '<pre>' + toJSON(doc) + '</pre>'
-      })
-      provides('xml', function(){
-        return {
-          'headers': {'Content-Type': 'application/xml'},
-          'body' : ''.concat(
-            '<?xml version="1.0" encoding="utf-8"?>\n',
-            '<doc>',
-            (function(){
-              escape = function(s){
-                return s.replace(/&quot;/g, '"')
-                        .replace(/&gt;/g, '>')
-                        .replace(/&lt;/g, '<')
-                        .replace(/&amp;/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
-                  '</' + key + '>'
-                )
-              }
-              return content;
-            })(),
-            '</doc>'
-          )
-        }
-      })
-      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 <http://wiki.apache.org/couchdb/Formatting_with_Show_and_List#Showing_Documents>`_
-
-   CouchDB Guide:
-     - `Show Functions <http://guide.couchdb.org/editions/1/en/show.html>`_
-
-
-.. _listfun:
-
-List functions
-==============
-
-.. function:: listfun(head, req)
-
-   :param head: :ref:`view_head_info_object`
-   :param req: :ref:`Request object <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('<html><body><table>');
-      send('<tr><th>ID</th><th>Key</th><th>Value</th></tr>')
-      while(row = getRow()){
-        send(''.concat(
-          '<tr>',
-          '<td>' + toJSON(row.id) + '</td>',
-          '<td>' + toJSON(row.key) + '</td>',
-          '<td>' + toJSON(row.value) + '</td>',
-          '</tr>'
-        ));
-      }
-      send('</table></body></html>');
-    }
-
-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 <http://wiki.apache.org/couchdb/Formatting_with_Show_and_List#Listing_Views_with_CouchDB_0.10_and_later>`_
-
-   CouchDB Guide:
-    - `Transforming Views with List Functions <http://guide.couchdb.org/draft/transforming.html>`_
-
-
-.. _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 <http://wiki.apache.org/couchdb/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<changes>`.
-
-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 <request_object>` object - it allows to create dynamic filters
-based on query parameters, :ref:`user context <userctx_object>` 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.
-
-.. _viewfilter:
-
-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<request_object>` is not
-   available.
-
-.. seealso::
-
-   CouchDB Guide:
-    - `Guide to filter change notification <http://guide.couchdb.org/draft/notifications.html#filters>`_
-
-   CouchDB Wiki:
-    - `Filtered replication <http://wiki.apache.org/couchdb/Replication#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.
-   :throws: ``unauthorized`` error to prevent storage and allow the user to
-            re-auth.
-
-A design document may contain a function named `validate_doc_update`
-which can be used to prevent invalid or unauthorized document update requests
-from being stored.  The function is passed the new document from the update
-request, the current document stored in the database, a :ref:`userctx_object`
-containing information about the user writing the document (if present), and
-a :ref:`security_object` with lists of database security roles.
-
-Validation functions typically examine the structure of the new document to
-ensure that required fields are present and to verify that the requesting user
-should be allowed to make changes to the document properties.  For example,
-an application may require that a user must be authenticated in order to create
-a new document or that specific document fields be present when a document
-is updated. The validation function can abort the pending document write
-by throwing one of two error objects:
-
-.. code-block:: javascript
-
-  // user is not authorized to make the change but may re-authenticate
-  throw({ unauthorized: 'Error message here.' });
-  
-  // change is not allowed
-  throw({ forbidden: 'Error message here.' });
-
-Document validation is optional, and each design document in the database may
-have at most one validation function.  When a write request is received for
-a given database, the validation function in each design document in that
-database is called in an unspecified order.  If any of the validation functions
-throw an error, the write will not succeed.
-
-**Example**: The ``_design/_auth`` ddoc from `_users` database uses a validation
-function to ensure that documents contain some required fields and are only
-modified by a user with the ``_admin`` role:
-
-.. 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 <http://guide.couchdb.org/editions/1/en/validation.html>`_
-
-   CouchDB Wiki:
-    - `Document Update Validation <http://wiki.apache.org/couchdb/Document_Update_Validation>`_

http://git-wip-us.apache.org/repos/asf/couchdb/blob/f2a31b58/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index 6c80120..c95da25 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -31,7 +31,7 @@ Contents
     install/index
     config/index
     replication/index
-    ddocs
+    couchapp/index
     query-server/index
     fauxton/index
     api/index


[40/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Import INSTALL.* docs from project root.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/2c3d449e
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/2c3d449e
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/2c3d449e

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 2c3d449ee1c592ed8a8ee94c6beaa4c6ca3510ad
Parents: aa86c0b
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 04:47:05 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am       |   9 +
 share/doc/src/index.rst           |   1 +
 share/doc/src/install/index.rst   |  26 +++
 share/doc/src/install/unix.rst    | 328 +++++++++++++++++++++++++++++++++
 share/doc/src/install/windows.rst | 219 ++++++++++++++++++++++
 5 files changed, 583 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c3d449e/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 1650fec..abb9097 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -83,6 +83,9 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
+    html/_source/install/index.html \
+    html/_source/install/unix.html \
+    html/_source/install/windows.html \
     html/_sources/query-server/index.txt \
     html/_sources/query-server/erlang.txt \
     html/_sources/query-server/javascript.txt \
@@ -158,6 +161,9 @@ html_files = \
     html/config/services.html \
     html/config/intro.html \
     html/config/proxying.html \
+    html/install/index.html \
+    html/install/unix.html \
+    html/install/windows.html \
     html/query-server/index.html \
     html/query-server/erlang.html \
     html/query-server/javascript.html \
@@ -231,6 +237,9 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
+    ../src/install/index.rst \
+    ../src/install/unix.rst \
+    ../src/install/windows.rst \
     ../src/query-server/index.rst \
     ../src/query-server/erlang.rst \
     ../src/query-server/javascript.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c3d449e/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index b6fca04..adabec1 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -28,6 +28,7 @@ Contents
     :numbered:
 
     intro
+    install/index
     config/index
     replication/index
     ddocs

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c3d449e/share/doc/src/install/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/index.rst b/share/doc/src/install/index.rst
new file mode 100644
index 0000000..6d8082c
--- /dev/null
+++ b/share/doc/src/install/index.rst
@@ -0,0 +1,26 @@
+.. 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.
+
+
+.. _install:
+
+============
+Installation
+============
+
+.. toctree::
+   :maxdepth: 2
+
+   unix
+   windows
+
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c3d449e/share/doc/src/install/unix.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/unix.rst b/share/doc/src/install/unix.rst
new file mode 100644
index 0000000..5988d5c
--- /dev/null
+++ b/share/doc/src/install/unix.rst
@@ -0,0 +1,328 @@
+.. 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.
+
+
+.. _install/unix:
+
+=================================
+Installation on Unix-like systems
+=================================
+
+A high-level guide to Unix-like systems, inc. Mac OS X and Ubuntu.
+
+This document is the canonical source of installation information. However, many
+systems have gotchas that you need to be aware of. In addition, dependencies
+frequently change as distributions update their archives. If you're running into
+trouble, be sure to check out the wiki. If you have any tips to share, please
+also update the wiki so that others can benefit from your experience.
+
+.. seealso::
+
+   `Community installation guides`_
+
+.. _Community installation guides: http://wiki.apache.org/couchdb/Installation
+
+Troubleshooting
+---------------
+
+* There is a `troubleshooting guide`_.
+* There is a `wiki`_ for general documentation.
+* There are collection of `friendly mailing lists`_.
+
+Please work through these in order if you experience any problems.
+
+.. _troubleshooting guide: http://wiki.apache.org/couchdb/Troubleshooting
+.. _wiki: http://wiki.apache.org/couchdb
+.. _friendly mailing lists: http://couchdb.apache.org/community/lists.html
+
+Dependencies
+------------
+
+You should have the following installed:
+
+* `Erlang OTP (>=R13B04, <R16)  <http://erlang.org/>`_
+* `ICU                          <http://icu-project.org/>`_
+* `OpenSSL                      <http://www.openssl.org/>`_
+* `Mozilla SpiderMonkey (1.7)   <http://www.mozilla.org/js/spidermonkey/>`_
+* `GNU Make                     <http://www.gnu.org/software/make/>`_
+* `GNU Compiler Collection      <http://gcc.gnu.org/>`_
+* `libcurl                      <http://curl.haxx.se/libcurl/>`_
+* `help2man                     <http://www.gnu.org/s/help2man/>`_
+* `Python (>=2.7) for docs      <http://python.org/>`_
+* `Python Sphinx (>=1.1.3)      <http://pypi.python.org/pypi/Sphinx>`_
+
+It is recommended that you install Erlang OTP R13B-4 or above where possible.
+You will only need libcurl if you plan to run the JavaScript test suite. And
+help2man is only need if you plan on installing the CouchDB man pages.
+Python and Sphinx are only required for building the online documentation.
+
+Debian-based Systems
+~~~~~~~~~~~~~~~~~~~~
+
+You can install the dependencies by running::
+
+    sudo apt-get install build-essential
+    sudo apt-get install erlang-base-hipe
+    sudo apt-get install erlang-dev
+    sudo apt-get install erlang-manpages
+    sudo apt-get install erlang-eunit
+    sudo apt-get install erlang-nox
+    sudo apt-get install libicu-dev
+    sudo apt-get install libmozjs-dev
+    sudo apt-get install libcurl4-openssl-dev
+
+There are lots of Erlang packages. If there is a problem with your install, try
+a different mix. There is more information on the wiki. Additionally, you might
+want to install some of the optional Erlang tools which may also be useful.
+
+Be sure to update the version numbers to match your system's available packages.
+
+Unfortunately, it seems that installing dependencies on Ubuntu is troublesome.
+
+.. seealso::
+
+  * `Installing on Debian <http://wiki.apache.org/couchdb/Installing_on_Debian>`_
+  * `Installing on Ubuntu <http://wiki.apache.org/couchdb/Installing_on_Ubuntu>`_
+
+
+RedHat-based (Fedora, Centos, RHEL) Systems
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+You can install the dependencies by running::
+
+    sudo yum groupinstall "Development Tools"
+    sudo yum install autoconf
+    sudo yum install autoconf-archive
+    sudo yum install automake
+    sudo yum install libtool
+    sudo yum install perl-Test-Harness
+    sudo yum install erlang-etap
+    sudo yum install erlang-erts
+    sudo yum install erlang-os_mon
+    sudo yum install erlang-eunit
+    sudo yum install libicu-devel
+    sudo yum install js-devel
+    sudo yum install curl-devel
+
+While CouchDB builds against the default js-devel-1.7.0 included in some
+distributions, it's recommended to use a more recent js-devel-1.8.5.
+
+Mac OS X
+~~~~~~~~
+
+You can install the build tools by running::
+
+    open /Applications/Installers/Xcode\ Tools/XcodeTools.mpkg
+
+You can install the other dependencies by running::
+
+    brew install autoconf
+    brew install autoconf-archive
+    brew install automake
+    brew install libtool
+    brew install erlang
+    brew install icu4c
+    brew install spidermonkey
+    brew install curl
+
+You may want to link ICU so that CouchDB can find the header files automatically::
+
+    brew link icu4c
+
+The same is true for recent versions of Erlang::
+
+    brew link erlang
+
+You will need `Homebrew`_ installed to use the `brew` command.
+
+Some versions of Mac OS X ship a problematic OpenSSL library. If you're
+experiencing troubles with CouchDB crashing intermittently with a segmentation
+fault or a bus error, you will need to install your own version of OpenSSL. See
+the troubleshooting guide, mentioned above, for more information.
+
+.. _Homebrew: http://mxcl.github.com/homebrew/
+
+Installing
+----------
+
+Once you have satisfied the dependencies you should run::
+
+    ./configure
+
+This script will configure CouchDB to be installed into `/usr/local` by default.
+
+If you wish to customise the installation, pass `--help` to this script.
+
+If everything was successful you should see the following message::
+
+    You have configured Apache CouchDB, time to relax.
+
+Relax.
+
+To install CouchDB you should run::
+
+    make && sudo make install
+
+You only need to use `sudo` if you're installing into a system directory.
+
+Try `gmake` if `make` is giving you any problems.
+
+If everything was successful you should see the following message::
+
+    You have installed Apache CouchDB, time to relax.
+
+Relax.
+
+First Run
+---------
+
+You can start the CouchDB server by running::
+
+    sudo -i -u couchdb couchdb
+
+This uses the `sudo` command to run the `couchdb` command as the `couchdb` user.
+
+When CouchDB starts it should eventually display the following message::
+
+    Apache CouchDB has started, time to relax.
+
+Relax.
+
+To check that everything has worked, point your web browser to::
+
+    http://127.0.0.1:5984/_utils/index.html
+
+From here you should run the test suite in Firefox.
+
+Security Considerations
+-----------------------
+
+You should create a special `couchdb` user for CouchDB.
+
+On many Unix-like systems you can run::
+
+    adduser --system \
+            --home /usr/local/var/lib/couchdb \
+            --no-create-home \
+            --shell /bin/bash \
+            --group --gecos \
+            "CouchDB Administrator" couchdb
+
+On Mac OS X you can use the `Workgroup Manager`_ to create users.
+
+You must make sure that:
+
+* The user has a working POSIX shell
+* The user's home directory is `/usr/local/var/lib/couchdb`
+
+You can test this by:
+
+* Trying to log in as the `couchdb` user
+* Running `pwd` and checking the present working directory
+
+Change the ownership of the CouchDB directories by running::
+
+    chown -R couchdb:couchdb /usr/local/etc/couchdb
+    chown -R couchdb:couchdb /usr/local/var/lib/couchdb
+    chown -R couchdb:couchdb /usr/local/var/log/couchdb
+    chown -R couchdb:couchdb /usr/local/var/run/couchdb
+
+Change the permission of the CouchDB directories by running::
+
+    chmod 0770 /usr/local/etc/couchdb
+    chmod 0770 /usr/local/var/lib/couchdb
+    chmod 0770 /usr/local/var/log/couchdb
+    chmod 0770 /usr/local/var/run/couchdb
+
+.. _Workgroup Manager: http://www.apple.com/support/downloads/serveradmintools1047.html
+
+
+Running as a Daemon
+-------------------
+
+SysV/BSD-style Systems
+~~~~~~~~~~~~~~~~~~~~~~
+
+You can use the `couchdb` init script to control the CouchDB daemon.
+
+On SysV-style systems, the init script will be installed into::
+
+    /usr/local/etc/init.d
+
+On BSD-style systems, the init script will be installed into::
+
+    /usr/local/etc/rc.d
+
+We use the `[init.d|rc.d]` notation to refer to both of these directories.
+
+You can control the CouchDB daemon by running::
+
+    /usr/local/etc/[init.d|rc.d]/couchdb [start|stop|restart|status]
+
+If you wish to configure how the init script works, you can edit::
+
+    /usr/local/etc/default/couchdb
+
+Comment out the `COUCHDB_USER` setting if you're running as a non-superuser.
+
+To start the daemon on boot, copy the init script to::
+
+    /etc/[init.d|rc.d]
+
+You should then configure your system to run the init script automatically.
+
+You may be able to run::
+
+    sudo update-rc.d couchdb defaults
+
+If this fails, consult your system documentation for more information.
+
+A `logrotate` configuration is installed into::
+
+    /usr/local/etc/logrotate.d/couchdb
+
+Consult your `logrotate` documentation for more information.
+
+It is critical that the CouchDB logs are rotated so as not to fill your disk.
+
+Mac OS X
+~~~~~~~~
+
+You can use the `launchctl` command to control the CouchDB daemon.
+
+You can load the configuration by running::
+
+    sudo launchctl load \
+         /usr/local/Library/LaunchDaemons/org.apache.couchdb.plist
+
+You can stop the CouchDB daemon by running::
+
+    sudo launchctl unload \
+         /usr/local/Library/LaunchDaemons/org.apache.couchdb.plist
+
+You can start CouchDB by running::
+
+    sudo launchctl start org.apache.couchdb
+
+You can restart CouchDB by running::
+
+    sudo launchctl stop org.apache.couchdb
+
+You can edit the launchd configuration by running::
+
+    open /usr/local/Library/LaunchDaemons/org.apache.couchdb.plist
+
+To start the daemon on boot, copy the configuration file to::
+
+    /Library/LaunchDaemons
+
+Consult your system documentation for more information.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c3d449e/share/doc/src/install/windows.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/windows.rst b/share/doc/src/install/windows.rst
new file mode 100644
index 0000000..0e8af94
--- /dev/null
+++ b/share/doc/src/install/windows.rst
@@ -0,0 +1,219 @@
+.. 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.
+
+
+.. _install/windows:
+
+=======================
+Installation on Windows
+=======================
+
+For a high-level guide to Microsoft Windows.
+
+Troubleshooting
+---------------
+
+* There is a `troubleshooting guide`_.
+* There is a `wiki`_ for general documentation.
+* And some `Windows-specific tips`_.
+* There are collection of `friendly mailing lists`_.
+
+Please work through these in order if you experience any problems.
+
+.. _troubleshooting guide: http://wiki.apache.org/couchdb/Troubleshooting
+.. _wiki: http://wiki.apache.org/couchdb
+.. _friendly mailing lists: http://couchdb.apache.org/community/lists.html
+.. _Windows-specific tips: http://wiki.apache.org/couchdb/Quirks_on_Windows
+
+Dependencies
+------------
+
+You should have the following installed:
+
+* `Erlang OTP (>=R14B01, <R16)   <http://erlang.org/>`_
+* `ICU        (>=4.*)            <http://icu-project.org/>`_
+* `OpenSSL    (>0.9.8r)          <http://www.openssl.org/>`_
+* `Mozilla SpiderMonkey (=1.8.5) <http://www.mozilla.org/js/spidermonkey/>`_
+* `Cygwin                        <http://www.cygwin.com/>`_
+* `Microsoft SDK 7.0 or 7.1      <http://www.microsoft.com/en-us/download/details.aspx?id=8279>`_
+* `libcurl    (>=7.20)           <http://curl.haxx.se/libcurl/>`_
+* `help2man                      <http://www.gnu.org/s/help2man/>`_
+* `Python (>=2.7) for docs       <http://python.org/>`_
+* `Python Sphinx (>=1.1.3)       <http://pypi.python.org/pypi/Sphinx>`_
+
+You will only need libcurl if you plan to run the JavaScript test suite. And
+help2man is only need if you plan on installing the CouchDB man pages.
+Python and Sphinx are only required for building the online documentation.
+
+General Notes
+-------------
+
+* When installing Cygwin, be sure to select all the `development` tools.
+
+* When installing Erlang, you must build it from source.
+
+* The CouchDB build requires a number of the Erlang build scripts.
+
+* All dependent libraries should be built with the same version of
+  Microsoft SDK.
+
+* Do not try to link against libraries built with, or included in,
+  Cygwin or MingW. They are not compatible with the Erlang/OTP or CouchDB
+  build scripts.
+
+* ICU version 4.6 and later will build cleanly using MSBuild.
+
+* Python and Sphinx are optional for building the online documentation.
+  Use cygwin-provided Python and install Sphinx via easy_install or pip.
+  Further information is here http://pypi.python.org/pypi/setuptools#id4
+
+Setting Up Cygwin
+-----------------
+
+Before starting any Cygwin terminals, run::
+
+    set CYGWIN=nontsec
+
+To set up your environment, run::
+
+    [VS_BIN]/vcvars32.bat
+
+Replace ``[VS_BIN]`` with the path to your Visual Studio `bin` directory.
+
+You must check that:
+
+* The ``which link`` command points to the Microsoft linker.
+
+* The ``which cl`` command points to the Microsoft compiler.
+
+* The ``which mc`` command points to the Microsoft message compiler.
+
+* The ``which mt`` command points to the Microsoft manifest tool.
+
+* The ``which nmake`` command points to the Microsoft make tool.
+
+If you do not do this, the build may fail due to Cygwin ones found in `/usr/bin`
+being used instead.
+
+Building Erlang
+---------------
+
+You must include Win32 OpenSSL, built statically from source. Use
+exactly the same version as required by the Erlang/OTP build process.
+
+However, you can skip the GUI tools by running::
+
+   echo "skipping gs" > lib/gs/SKIP
+
+   echo "skipping ic" > lib/ic/SKIP
+
+   echo "skipping jinterface" > lib/jinterface/SKIP
+
+Follow the rest of the Erlang instructions as described.
+
+After running::
+
+   ./otp_build release -a
+
+You should run::
+
+   ./release/win32/Install.exe -s
+
+This will set up the release/win32/bin directory correctly. The CouchDB
+installation scripts currently write their data directly into this
+location.
+
+To set up your environment for building CouchDB, run::
+
+    eval `./otp_build env_win32`
+
+To set up the `ERL_TOP` environment variable, run::
+
+    export ERL_TOP=[ERL_TOP]
+
+Replace ``[ERL_TOP]`` with the Erlang source directory name.
+
+Remember to use `/cygdrive/c/` instead of `c:/` as the directory prefix.
+
+To set up your path, run::
+
+    export PATH=$ERL_TOP/release/win32/erts-5.8.5/bin:$PATH
+
+If everything was successful, you should be ready to build CouchDB.
+
+Relax.
+
+Building CouchDB
+----------------
+
+Note that `win32-curl` is only required if you wish to run the developer
+tests.
+
+The documentation step may be skipped using ``--disable-docs`` if you wish.
+
+Once you have satisfied the dependencies you should run::
+
+    ./configure \
+        --with-js-include=/cygdrive/c/path_to_spidermonkey_include \
+        --with-js-lib=/cygdrive/c/path_to_spidermonkey_lib \
+        --with-win32-icu-binaries=/cygdrive/c/path_to_icu_binaries_root \
+        --with-erlang=$ERL_TOP/release/win32/usr/include \
+        --with-win32-curl=/cygdrive/c/path/to/curl/root/directory \
+        --with-openssl-bin-dir=/cygdrive/c/openssl/bin \
+        --with-msvc-redist-dir=/cygdrive/c/dir/with/vcredist_platform_executable \
+        --disable-init \
+        --disable-launchd \
+        --prefix=$ERL_TOP/release/win32
+
+This command could take a while to complete.
+
+If everything was successful you should see the following message::
+
+    You have configured Apache CouchDB, time to relax.
+
+Relax.
+
+To install CouchDB you should run::
+
+    make install
+
+If everything was successful you should see the following message::
+
+    You have installed Apache CouchDB, time to relax.
+
+Relax.
+
+To build the .exe installer package, you should run::
+
+    make dist
+
+Alternatively, you may run CouchDB directly from the build tree, but
+to avoid any contamination do not run `make dist` after this.
+
+First Run
+---------
+
+You can start the CouchDB server by running::
+
+    $ERL_TOP/release/win32/bin/couchdb.bat
+
+When CouchDB starts it should eventually display the following message::
+
+    Apache CouchDB has started, time to relax.
+
+Relax.
+
+To check that everything has worked, point your web browser to::
+
+    http://127.0.0.1:5984/_utils/index.html
+
+From here you should run the verification tests in Firefox.


[24/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Describe authentication methods and their API.

COUCHDB-1544


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/fab08a26
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/fab08a26
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/fab08a26

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: fab08a26274677a519b29fd122291d9f2228e5ec
Parents: 6e1ceed
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 11:55:27 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/authn.rst | 437 ++++++++++++++++++++++++++++++++++++++-
 1 file changed, 427 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/fab08a26/share/doc/src/api/authn.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/authn.rst b/share/doc/src/api/authn.rst
index 7635c1c..083a262 100644
--- a/share/doc/src/api/authn.rst
+++ b/share/doc/src/api/authn.rst
@@ -16,8 +16,6 @@
 Authentication Methods
 ======================
 
-.. todo:: Authentication Methods
-
 The CouchDB Authentication methods provide an interface for obtaining
 session and authorization data.
 
@@ -26,14 +24,6 @@ A list of the available methods and URL paths are provided below:
 +--------+-------------------------+-------------------------------------------+
 | Method | Path                    | Description                               |
 +========+=========================+===========================================+
-| GET    | /_oauth/access_token    | TBC                                       |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_oauth/authorize       | TBC                                       |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /_oauth/authorize       | TBC                                       |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_oauth/request_token   | TBC                                       |
-+--------+-------------------------+-------------------------------------------+
 | GET    | /_session               | Returns cookie based login user           |
 |        |                         | information                               |
 +--------+-------------------------+-------------------------------------------+
@@ -41,3 +31,430 @@ A list of the available methods and URL paths are provided below:
 +--------+-------------------------+-------------------------------------------+
 | DELETE | /_session               | Logout cookie based user                  |
 +--------+-------------------------+-------------------------------------------+
+
+.. note:: We're also strongly recommend you to
+   :ref:`setup SSL <config/ssl>` to improve all authentication methods security.
+
+
+.. _api/auth/basic:
+
+Basic Authentication
+====================
+
+`Basic authentication`_ (:rfc:`2617`) is a quick and simple way to be
+authenticated by CouchDB. The main flaw of this simplicity is the need to send
+user credentials with each request which may be insecure and hurts operations
+performance (since CouchDB must compute password hash with every request):
+
+.. code-block:: http
+
+    GET / HTTP/1.1
+    Authorization: Basic cm9vdDpyZWxheA==
+    Host: localhost:5984
+    Accept: application/json
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
+    Date: Mon, 03 Dec 2012 00:44:47 GMT
+    Content-Type: application/json
+    Content-Length: 177
+    Cache-Control: must-revalidate
+
+.. code-block:: javascript
+
+    {
+      "couchdb":"Welcome",
+      "uuid":"0a959b9b8227188afc2ac26ccdf345a6",
+      "version":"1.3.0",
+      "vendor": {
+        "version":"1.3.0",
+        "name":"The Apache Software Foundation"
+      }
+    }
+
+.. _Basic authentication: http://en.wikipedia.org/wiki/Basic_access_authentication
+
+
+.. _api/auth/cookie:
+
+Cookie Authentication
+=====================
+
+For cookie authentication (:rfc:`2109`) CouchDB generates a one-time token that
+the client can use for next requests to CouchDB. When CouchDB sees non expired
+the token in a subsequent request, it will authenticate user by this token
+without requesting the password again. By default, cookies are valid for
+10 minutes, but it's :ref:`adjustable <config/couch_httpd_auth/timeout>`.
+Also it's possible to make cookies
+:ref:`persistent <config/couch_httpd_auth/allow_persistent_cookies>`
+
+To obtain the first token and thus authenticate a user for the first time, the
+`username` and `password` must be sent to the
+:ref:`_session API <api/auth/session>`.
+
+.. _api/auth/session:
+.. _api/auth/session.post:
+
+``POST /_session``
+------------------
+
+* **Method**: ``POST /_session``
+* **Request**: User credentials
+* **Response**: User information
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: next
+
+    * **Description**: Enforces redirect after successful login
+    * **Optional**: yes
+    * **Value**: Relative path from server root
+
+* **HTTP Headers**
+
+  * **Header**: ``Content-Type``
+
+    * **Description**: Credentials data format
+    * **Optional**: no
+    * **Value**: ``application/x-www-form-urlencoded``
+
+* **Return Codes**:
+
+  * **200**:
+    Successfully authenticated
+
+  * **302**:
+    Redirect after successful authentication
+
+  * **401**:
+    Username or password wasn't recognized
+
+Initiates new session for specified user credentials by providing `Cookie`
+value. Credentials should be defined in ``application/x-www-form-urlencoded``
+format with `name` and `password` fields.
+
+.. code-block:: http
+
+    POST /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Content-Length: 24
+    Content-Type: application/x-www-form-urlencoded
+
+.. code-block:: text
+
+    name=root&password=relax
+
+In case of success will be returned next response:
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Set-Cookie: AuthSession=cm9vdDo1MEJCRkYwMjq0LO0ylOIwShrgt8y-UkhI-c6BGw; Version=1; Path=/; HttpOnly
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
+    Date: Mon, 03 Dec 2012 01:23:14 GMT
+    Content-Type: application/json
+    Content-Length: 43
+    Cache-Control: must-revalidate
+
+.. code-block:: javascript
+
+    {"ok":true,"name":null,"roles":["_admin"]}
+
+If ``next`` query parameter was provided the response will trigger redirection
+to the specified location in case of successful authentication:
+
+.. code-block:: http
+
+    GET /_session?next=/blog/_design/sofa/_rewrite/recent-posts HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+
+.. code-block:: http
+
+    HTTP/1.1 302 Moved Temporarily
+    Set-Cookie: AuthSession=cm9vdDo1MEJDMDEzRTp7Vu5GKCkTxTVxwXbpXsBARQWnhQ; Version=1; Path=/; HttpOnly
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
+    Location: http://localhost:5984/blog/_design/sofa/_rewrite/recent-posts
+    Date: Mon, 03 Dec 2012 01:32:46 GMT
+    Content-Type: application/json
+    Content-Length: 43
+    Cache-Control: must-revalidate
+
+.. code-block:: javascript
+
+    {"ok":true,"name":null,"roles":["_admin"]}
+
+
+.. _api/auth/session.get:
+
+``GET /_session``
+-----------------
+
+* **Method**: ``GET /_session``
+* **Request**: None
+* **Response**: User information
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: basic
+
+    * **Description**: Accept `Basic Auth` by requesting this resource
+    * **Optional**: yes
+    * **Value**: ``true``
+
+* **Return Codes**:
+
+  * **200**:
+    Successfully authenticated.
+
+  * **401**:
+    Username or password wasn't recognized.
+
+Returns complete information about authenticated user:
+
+.. code-block:: http
+
+    GET /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Cookie: AuthSession=cm9vdDo1MEJDMDQxRDpqb-Ta9QfP9hpdPjHLxNTKg_Hf9w
+
+.. code-block:: javascript
+
+    {
+        "info": {
+            "authenticated": "cookie",
+            "authentication_db": "_users",
+            "authentication_handlers": [
+                "oauth",
+                "cookie",
+                "default"
+            ]
+        },
+        "ok": true,
+        "userCtx": {
+            "name": "root",
+            "roles": [
+                "_admin"
+            ]
+        }
+    }
+
+This information contains :ref:`userctx_object`, authentication method and
+available ones and authentication database.
+
+.. _api/auth/session.delete:
+
+``DELETE /_session``
+--------------------
+
+* **Method**: ``DELETE /_session``
+* **Request**: None
+* **Response**: Status
+* **Admin Privileges Required**: no
+
+* **Return Codes**:
+
+  * **200**:
+    Successfully close session.
+
+  * **401**:
+    Username or password wasn't recognized.
+
+Closes user's session. If everything is ok, the response is:
+
+.. code-block:: javascript
+
+    {"ok":true}
+
+
+.. _api/auth/proxy:
+
+Proxy Authentication
+====================
+
+.. note::
+   To use this authentication method make sure that the
+   ``{couch_httpd_auth, proxy_authentication_handler}`` value in added to
+   the list of the active
+   :ref:`authentication handlers <config/httpd/authentication_handlers>`:
+
+   .. code-block:: ini
+
+      [httpd]
+      authentication_handlers = {couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, proxy_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
+
+
+`Proxy authentication` is very useful in case when your application is already
+uses some external authentication service and you won't duplicate users and
+their roles in CouchDB.
+
+This authentication method allows creation of a :ref:`userctx_object` for
+remotely authenticated user. By default, the client just need to pass specific
+headers to CouchDB with related request:
+
+- :ref:`X-Auth-CouchDB-UserName <config/couch_httpd_auth/x_auth_username>`:
+  username;
+- :ref:`X-Auth-CouchDB-Roles <config/couch_httpd_auth/x_auth_roles>`:
+  list of user roles separated by a comma (``,``);
+- :ref:`X-Auth-CouchDB-Token <config/couch_httpd_auth/x_auth_token>`:
+  authentication token. Optional, but strongly recommended to
+  :ref:`force token be required <config/couch_httpd_auth/proxy_use_secret>`
+  to prevent requests from untrusted sources.
+
+.. code-block:: http
+
+    GET /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Content-Type: application/json; charset=utf-8
+    X-Auth-CouchDB-Roles: users,blogger
+    X-Auth-CouchDB-UserName: foo
+
+CouchDB sends the response:
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Cache-Control: must-revalidate
+    Content-Length: 190
+    Content-Type: application/json
+    Date: Fri, 14 Jun 2013 10:16:03 GMT
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B03)
+
+.. code-block:: javascript
+
+    {
+        "info": {
+            "authenticated": "proxy",
+            "authentication_db": "_users",
+            "authentication_handlers": [
+                "oauth",
+                "cookie",
+                "proxy",
+                "default"
+            ]
+        },
+        "ok": true,
+        "userCtx": {
+            "name": "foo",
+            "roles": [
+                "users",
+                "blogger"
+            ]
+        }
+    }
+
+
+Note, that you don't need to request :ref:`session <api/auth/session>` resource
+to be authenticated by this method if all required HTTP headers are provided.
+
+
+.. _api/auth/oauth:
+
+OAuth Authentication
+====================
+
+CouchDB supports OAuth 1.0 authentication (:rfc:`5849`). OAuth provides a method
+for clients to access server resources  without sharing real credentials
+(username and password).
+
+First, :ref:`configure oauth <config/oauth>`, by setting consumer and token
+with their secrets and binding token to real CouchDB username.
+
+Probably, it's not good idea to work with plain curl, let use some scripting
+language like Python:
+
+.. code-block:: python
+
+  #!/usr/bin/env python2
+  from oauth import oauth # pip install oauth
+  import httplib
+
+  URL = 'http://localhost:5984/_session'
+  CONSUMER_KEY = 'consumer1'
+  CONSUMER_SECRET = 'sekr1t'
+  TOKEN = 'token1'
+  SECRET = 'tokensekr1t'
+
+  consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
+  token = oauth.OAuthToken(TOKEN, SECRET)
+  req = oauth.OAuthRequest.from_consumer_and_token(
+      consumer,
+      token=token,
+      http_method='GET',
+      http_url=URL,
+      parameters={}
+  )
+  req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,token)
+
+  headers = req.to_header()
+  headers['Accept'] = 'application/json'
+
+  con = httplib.HTTPConnection('localhost', 5984)
+  con.request('GET', URL, headers=headers)
+  resp = con.getresponse()
+  print resp.read()
+
+or Ruby:
+
+.. code-block:: ruby
+
+  #!/usr/bin/env ruby
+
+  require 'oauth' # gem install oauth
+
+  URL = 'http://localhost:5984'
+  CONSUMER_KEY = 'consumer1'
+  CONSUMER_SECRET = 'sekr1t'
+  TOKEN = 'token1'
+  SECRET = 'tokensekr1t'
+
+  @consumer = OAuth::Consumer.new CONSUMER_KEY,
+                                  CONSUMER_SECRET,
+                                  {:site => URL}
+
+  @access_token = OAuth::AccessToken.new(@consumer, TOKEN, SECRET)
+
+  puts @access_token.get('/_session').body
+
+
+Both snippets produces similar request and response pair:
+
+.. code-block:: http
+
+    GET /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Authorization: OAuth realm="", oauth_nonce="81430018", oauth_timestamp="1374561749", oauth_consumer_key="consumer1", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="token1", oauth_signature="o4FqJ8%2B9IzUpXH%2Bk4rgnv7L6eTY%3D"
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Cache-Control : must-revalidate
+    Content-Length : 167
+    Content-Type : application/json
+    Date : Tue, 23 Jul 2013 06:51:15 GMT
+    Server : CouchDB/1.3.1 (Erlang OTP/R16B)
+
+.. code-block:: javascript
+
+  {
+    "ok": true,
+    "info": {
+      "authenticated": "oauth"
+      "authentication_db": "_users",
+      "authentication_handlers": ["oauth", "cookie", "default"]
+    },
+    "userCtx": {
+      "name": "couchdb_username",
+      "roles": []
+    }
+  }
+
+There we'd requested the :ref:`_session <api/auth/session>` resource to ensure
+that authentication was successful and target CouchDB username is correct.
+Change the target URL to request required resource.


[15/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Split query-servers article into the group.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/57e35fe9
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/57e35fe9
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/57e35fe9

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 57e35fe95563a921331894f3f057ca0fed03d2ea
Parents: 82478ae
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 23:09:03 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am               |  12 +-
 share/doc/src/config/query-servers.rst    |   4 +-
 share/doc/src/ddocs.rst                   |   4 +-
 share/doc/src/index.rst                   |   2 +-
 share/doc/src/query-server/erlang.rst     | 138 ++++++++
 share/doc/src/query-server/index.rst      |  38 +++
 share/doc/src/query-server/javascript.rst | 288 +++++++++++++++++
 share/doc/src/query-servers.rst           | 418 -------------------------
 8 files changed, 478 insertions(+), 426 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/57e35fe9/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index a8c8fca..a85db77 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -68,6 +68,9 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
+    html/_sources/query-server/index.txt \
+    html/_sources/query-server/erlang.txt \
+    html/_sources/query-server/javascript.txt \
     html/_sources/replications/conflicts.txt \
     html/_sources/replications/index.txt \
     html/_sources/replications/intro.txt \
@@ -80,7 +83,6 @@ html_files = \
     html/_sources/index.txt \
     html/_sources/intro.txt \
     html/_sources/json-structure.txt \
-    html/_sources/query-servers.txt \
     html/_static/ajax-loader.gif \
     html/_static/basic.css \
     html/_static/comment-bright.png \
@@ -127,6 +129,9 @@ html_files = \
     html/config/services.html \
     html/config/intro.html \
     html/config/proxying.html \
+    html/query-server/index.html \
+    html/query-server/erlang.html \
+    html/query-server/javascript.html \
     html/replications/conflicts.html \
     html/replications/index.html \
     html/replications/intro.html \
@@ -138,7 +143,6 @@ html_files = \
     html/index.html \
     html/intro.html \
     html/json-structure.html \
-    html/query-servers.html \
     html/objects.inv \
     html/genindex.html \
     html/search.html \
@@ -184,6 +188,9 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
+    ../src/query-server/index.rst \
+    ../src/query-server/erlang.rst \
+    ../src/query-server/javascript.rst \
     ../src/replication/conflicts.rst \
     ../src/replication/index.rst \
     ../src/replication/intro.rst \
@@ -196,7 +203,6 @@ src_files = \
     ../src/index.rst \
     ../src/intro.rst \
     ../src/json-structure.rst \
-    ../src/query-servers.rst \
     ../src/conf.py
 
 src_files_html = \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/57e35fe9/share/doc/src/config/query-servers.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/query-servers.rst b/share/doc/src/config/query-servers.rst
index 92d7ede..5462753 100644
--- a/share/doc/src/config/query-servers.rst
+++ b/share/doc/src/config/query-servers.rst
@@ -50,7 +50,7 @@ Where:
 - ``ARGS``: optionally, you may specify additional command line arguments for
   the executable ``PATH``.
 
-The default query server is written in :ref:`Javascript <queryserver_js>`,
+The default query server is written in :ref:`JavaScript <query-server/js>`,
 running via `Mozilla SpiderMonkey`_::
 
   [query_servers]
@@ -140,7 +140,7 @@ First, you'll need to edit your `local.ini` to include a
   erlang = {couch_native_process, start_link, []}
 
 To see these changes you will also need to restart the server.
-To test out using :ref:`Erlang views <queryserver_erlang>`, visit the
+To test out using :ref:`Erlang views <query-server/erlang>`, visit the
 `Futon` admin interface, create a new database and open a temporary view.
 You should now be able to select ``erlang`` from the language drop-down.
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/57e35fe9/share/doc/src/ddocs.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/ddocs.rst b/share/doc/src/ddocs.rst
index 0bb2c9d..45a3773 100644
--- a/share/doc/src/ddocs.rst
+++ b/share/doc/src/ddocs.rst
@@ -19,7 +19,7 @@ Design Docs
 ===========
 
 In this section we'll show how to write design documents, using the built-in
-:ref:`JavaScript Query Server <queryserver_js>`.
+:ref:`JavaScript Query Server <query-server/js>`.
 
 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
@@ -30,7 +30,7 @@ them extensively within each function:
 - :ref:`Response object <response_object>`
 - :ref:`UserCtx object <userctx_object>`
 - :ref:`Database Security object <security_object>`
-- :ref:`Guide to JavaScript Query Server <queryserver_js>`
+- :ref:`Guide to JavaScript Query Server <query-server/js>`
 
 .. _viewfun:
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/57e35fe9/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index 1ff3d40..2fcdb00 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -31,7 +31,7 @@ Contents
     config/index
     replication/index
     ddocs
-    query-servers
+    query-server/index
     changes
     api/index
     json-structure

http://git-wip-us.apache.org/repos/asf/couchdb/blob/57e35fe9/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
new file mode 100644
index 0000000..21f2399
--- /dev/null
+++ b/share/doc/src/query-server/erlang.rst
@@ -0,0 +1,138 @@
+.. 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/erlang:
+
+Erlang
+======
+
+.. note::
+
+   The Erlang query server is disabled by default.
+   Read :ref:`configuration guide <config/native_query_servers>` 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}) ->
+        <<K,_/binary>> = proplists:get_value(<<"_rev">>, Doc, null),
+        V = proplists:get_value(<<"_id">>, Doc, null),
+        Emit(<<K>>, 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}) ->
+        <<K,_/binary>> = 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(<<K>>, 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<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/57e35fe9/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
new file mode 100644
index 0000000..8112549
--- /dev/null
+++ b/share/doc/src/query-server/index.rst
@@ -0,0 +1,38 @@
+.. 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
+============
+
+The `Query server` is an external process that communicates with CouchDB by JSON
+protocol through stdio interface and processed all
+:ref:`design functions <ddocs>` calls:
+:ref:`views <viewfun>`, :ref:`shows <showfun>`, :ref:`lists <listfun>` and more.
+
+The default query server is written in
+:ref:`JavaScript <query-server/js>`, 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 <api/db/temp_view>` without a `Content-Type` header.
+
+.. _Mozilla SpiderMonkey: https://developer.mozilla.org/en/docs/SpiderMonkey
+
+.. toctree::
+   :maxdepth: 2
+
+   javascript
+   erlang
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/57e35fe9/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
new file mode 100644
index 0000000..16590d6
--- /dev/null
+++ b/share/doc/src/query-server/javascript.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.
+
+.. 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 <https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=blob;f=share/server/json2.js>`_
+   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 <response_object>` 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 <http://wiki.commonjs.org/wiki/Modules/1.1.1>`_
+(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.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/57e35fe9/share/doc/src/query-servers.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/query-servers.rst b/share/doc/src/query-servers.rst
deleted file mode 100644
index 82a3c0e..0000000
--- a/share/doc/src/query-servers.rst
+++ /dev/null
@@ -1,418 +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 Servers
-=============
-
-.. _queryserver_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 <https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=blob;f=share/server/json2.js>`_
-   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 <response_object>` 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 <http://wiki.commonjs.org/wiki/Modules/1.1.1>`_
-(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.
-
-.. _queryserver_erlang:
-
-Erlang
-======
-
-.. note::
-
-   The Erlang query server is disabled by default.
-   Read :ref:`configuration guide <config/native_query_servers>` 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}) ->
-        <<K,_/binary>> = proplists:get_value(<<"_rev">>, Doc, null),
-        V = proplists:get_value(<<"_id">>, Doc, null),
-        Emit(<<K>>, 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}) ->
-        <<K,_/binary>> = 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(<<K>>, 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<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.


[29/50] [abbrv] Split API articles into small files focused on specific problem.

Posted by kx...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/all-docs.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/all-docs.rst b/share/doc/src/api/database/all-docs.rst
new file mode 100644
index 0000000..06aa5b8
--- /dev/null
+++ b/share/doc/src/api/database/all-docs.rst
@@ -0,0 +1,244 @@
+.. 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.
+
+
+.. _api/db/all_docs:
+.. _api/db/all_docs.get:
+
+``GET /db/_all_docs``
+=====================
+
+* **Method**: ``GET /db/_all_docs``
+* **Request**: None
+* **Response**: JSON object containing document information, ordered by the
+  document ID
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: descending
+
+    * **Description**:  Return the documents in descending by key order
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: endkey
+
+    * **Description**:  Stop returning records when the specified key is reached
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: endkey_docid
+
+    * **Description**:  Stop returning records when the specified document ID is
+      reached
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: group
+
+    * **Description**:  Group the results using the reduce function to a group
+      or single row
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: group_level
+
+    * **Description**:  Specify the group level to be used
+    * **Optional**: yes
+    * **Type**: numeric
+
+  * **Argument**: include_docs
+
+    * **Description**:  Include the full content of the documents in the return
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: inclusive_end
+
+    * **Description**:  Specifies whether the specified end key should be
+      included in the result
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: true
+
+  * **Argument**: key
+
+    * **Description**:  Return only documents that match the specified key
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: limit
+
+    * **Description**:  Limit the number of the returned documents to the
+      specified number
+    * **Optional**: yes
+    * **Type**: numeric
+
+  * **Argument**: reduce
+
+    * **Description**:  Use the reduction function
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: true
+
+  * **Argument**: skip
+
+    * **Description**:  Skip this number of records before starting to return
+      the results
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 0
+
+  * **Argument**: stale
+
+    * **Description**:  Allow the results from a stale view to be used
+    * **Optional**: yes
+    * **Type**: string
+    * **Default**:
+    * **Supported Values**:
+
+      * **ok**: Allow stale views
+
+  * **Argument**: startkey
+
+    * **Description**:  Return records starting with the specified key
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: startkey_docid
+
+    * **Description**:  Return records starting with the specified document ID
+    * **Optional**: yes
+    * **Type**: string
+
+Returns a JSON structure of all of the documents in a given database.
+The information is returned as a JSON structure containing meta
+information about the return structure, and the list documents and basic
+contents, consisting the ID, revision and key. The key is generated from
+the document ID.
+
++----------------------------------+-------------------------------------------+
+| Field                            | Description                               |
++==================================+===========================================+
+| offset                           | Offset where the document list started    |
++----------------------------------+-------------------------------------------+
+| rows [array]                     | Array of document object                  |
++----------------------------------+-------------------------------------------+
+| total_rows                       | Number of documents in the database/view  |
++----------------------------------+-------------------------------------------+
+| update_seq                       | Current update sequence for the database  |
++----------------------------------+-------------------------------------------+
+
+By default the information returned contains only the document ID and
+revision. For example, the request:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_all_docs
+    Accept: application/json
+
+Returns the following structure:
+
+.. code-block:: javascript
+
+    {
+       "total_rows" : 18386,
+       "rows" : [
+          {
+             "value" : {
+                "rev" : "1-bc0d5aed1e339b1cc1f29578f3220a45"
+             },
+             "id" : "Aberffrawcake",
+             "key" : "Aberffrawcake"
+          },
+          {
+             "value" : {
+                "rev" : "3-68a20c89a5e70357c20148f8e82ca331"
+             },
+             "id" : "Adukiandorangecasserole-microwave",
+             "key" : "Adukiandorangecasserole-microwave"
+          },
+          {
+             "value" : {
+                "rev" : "3-9b2851ed9b6f655cc4eb087808406c60"
+             },
+             "id" : "Aioli-garlicmayonnaise",
+             "key" : "Aioli-garlicmayonnaise"
+          },
+          ...
+             ],
+       "offset" : 0
+    }
+
+The information is returned in the form of a temporary view of all the
+database documents, with the returned key consisting of the ID of the
+document. The remainder of the interface is therefore identical to the
+View query arguments and their behavior.
+
+.. _api/db/all_docs.post:
+
+``POST /db/_all_docs``
+======================
+
+* **Method**: ``POST /db/_all_docs``
+* **Request**: JSON of the document IDs you want included
+* **Response**: JSON of the returned view
+* **Admin Privileges Required**: no
+
+The ``POST`` to ``_all_docs`` allows to specify multiple keys to be
+selected from the database. This enables you to request multiple
+documents in a single request, in place of multiple
+:ref:`api/doc.get` requests.
+
+The request body should contain a list of the keys to be returned as an
+array to a ``keys`` object. For example:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_all_docs
+    User-Agent: MyApp/0.1 libwww-perl/5.837
+
+    {
+       "keys" : [
+          "Zingylemontart",
+          "Yogurtraita"
+       ]
+    }
+
+The return JSON is the all documents structure, but with only the
+selected keys in the output:
+
+.. code-block:: javascript
+
+    {
+       "total_rows" : 2666,
+       "rows" : [
+          {
+             "value" : {
+                "rev" : "1-a3544d296de19e6f5b932ea77d886942"
+             },
+             "id" : "Zingylemontart",
+             "key" : "Zingylemontart"
+          },
+          {
+             "value" : {
+                "rev" : "1-91635098bfe7d40197a1b98d7ee085fc"
+             },
+             "id" : "Yogurtraita",
+             "key" : "Yogurtraita"
+          }
+       ],
+       "offset" : 0
+    }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/bulk-docs.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/bulk-docs.rst b/share/doc/src/api/database/bulk-docs.rst
new file mode 100644
index 0000000..32253e6
--- /dev/null
+++ b/share/doc/src/api/database/bulk-docs.rst
@@ -0,0 +1,390 @@
+.. 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.
+
+
+.. _api/db/bulk_docs:
+.. _api/db/bulk_docs.post:
+
+``POST /db/_bulk_docs``
+=======================
+
+* **Method**: ``POST /db/_bulk_docs``
+* **Request**: JSON of the docs and updates to be applied
+* **Response**: JSON success statement
+* **Admin Privileges Required**: no
+
+* **HTTP Headers**:
+
+  * **Header**: ``X-Couch-Full-Commit``
+
+    * **Description**: Overrides server's commit policy.
+    * **Optional**: yes
+    * **Values**:
+
+      * **true**: Ensures that any non-committed changes are committed to
+        physical storage.
+      * **false**: Uses the delay commit in opposite to ``true`` value. CouchDB
+        responses quickly, but without any guarantees that all data are
+        successfully stored on disk.
+
+* **Return Codes**:
+
+  * **201**:
+    Document(s) have been created or updated
+
+The bulk document API allows you to create and update multiple documents
+at the same time within a single request. The basic operation is similar
+to creating or updating a single document, except that you batch the
+document structure and information and . When creating new documents the
+document ID is optional. For updating existing documents, you must
+provide the document ID, revision information, and new document values.
+
+For both inserts and updates the basic structure of the JSON is the
+same:
+
++----------------------------------+-------------------------------------------+
+| Field                            | Description                               |
++==================================+===========================================+
+| all_or_nothing (optional)        | Sets the database commit mode to use      |
+|                                  | all-or-nothing semantics                  |
++----------------------------------+-------------------------------------------+
+| docs [array]                     | Bulk Documents Document                   |
++----------------------------------+-------------------------------------------+
+|         _id (optional)           | List of changes, field-by-field, for this |
+|                                  | document                                  |
++----------------------------------+-------------------------------------------+
+|         _rev (optional)          | Document ID                               |
++----------------------------------+-------------------------------------------+
+|         _deleted (optional)      | Update sequence number                    |
++----------------------------------+-------------------------------------------+
+
+Inserting Documents in Bulk
+---------------------------
+
+To insert documents in bulk into a database you need to supply a JSON
+structure with the array of documents that you want to add to the
+database. Using this method you can either include a document ID, or
+allow the document ID to be automatically generated.
+
+For example, the following inserts three new documents, two with the
+supplied document IDs, and one which will have a document ID generated:
+
+.. code-block:: javascript
+
+    {
+       "docs" : [
+          {
+             "_id" : "FishStew",
+             "servings" : 4,
+             "subtitle" : "Delicious with fresh bread",
+             "title" : "Fish Stew"
+          },
+          {
+             "_id" : "LambStew",
+             "servings" : 6,
+             "subtitle" : "Delicious with scone topping",
+             "title" : "Lamb Stew"
+          },
+          {
+             "servings" : 8,
+             "subtitle" : "Delicious with suet dumplings",
+             "title" : "Beef Stew"
+          },
+       ]
+    }
+
+
+The return type from a bulk insertion will be 201, with the content of
+the returned structure indicating specific success or otherwise messages
+on a per-document basis.
+
+The return structure from the example above contains a list of the
+documents created, here with the combination and their revision IDs:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_bulk_docs
+    Content-Type: application/json
+
+    [
+       {
+          "id" : "FishStew",
+          "rev" : "1-9c65296036141e575d32ba9c034dd3ee",
+       },
+       {
+          "id" : "LambStew",
+          "rev" : "1-34c318924a8f327223eed702ddfdc66d",
+       },
+       {
+          "id" : "7f7638c86173eb440b8890839ff35433",
+          "rev" : "1-857c7cbeb6c8dd1dd34a0c73e8da3c44",
+       }
+    ]
+
+
+The content and structure of the returned JSON will depend on the transaction
+semantics being used for the bulk update; see :ref:`api/db/bulk_docs/semantics`
+for more information. Conflicts and validation errors when updating documents in
+bulk must be handled separately; see :ref:`api/db/bulk_docs/validation`.
+
+Updating Documents in Bulk
+--------------------------
+
+The bulk document update procedure is similar to the insertion
+procedure, except that you must specify the document ID and current
+revision for every document in the bulk update JSON string.
+
+For example, you could send the following request:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_bulk_docs
+    Content-Type: application/json
+
+    {
+       "docs" : [
+          {
+             "_id" : "FishStew",
+             "_rev" : "1-9c65296036141e575d32ba9c034dd3ee",
+             "servings" : 4,
+             "subtitle" : "Delicious with freshly baked bread",
+             "title" : "Fish Stew"
+          },
+          {
+             "_id" : "LambStew",
+             "_rev" : "1-34c318924a8f327223eed702ddfdc66d",
+             "servings" : 6,
+             "subtitle" : "Serve with a wholemeal scone topping",
+             "title" : "Lamb Stew"
+          },
+          {
+             "_id" : "7f7638c86173eb440b8890839ff35433"
+             "_rev" : "1-857c7cbeb6c8dd1dd34a0c73e8da3c44",
+             "servings" : 8,
+             "subtitle" : "Hand-made dumplings make a great accompaniment",
+             "title" : "Beef Stew"
+          }
+       ]
+    }
+
+The return structure is the JSON of the updated documents, with the new
+revision and ID information:
+
+.. code-block:: javascript
+
+    [
+       {
+          "id" : "FishStew",
+          "rev" : "2-e7af4c4e9981d960ecf78605d79b06d1"
+       },
+       {
+          "id" : "LambStew",
+          "rev" : "2-0786321986194c92dd3b57dfbfc741ce"
+       },
+       {
+          "id" : "7f7638c86173eb440b8890839ff35433",
+          "rev" : "2-bdd3bf3563bee516b96885a66c743f8e"
+       }
+    ]
+
+You can optionally delete documents during a bulk update by adding the
+``_deleted`` field with a value of ``true`` to each document ID/revision
+combination within the submitted JSON structure.
+
+The return type from a bulk insertion will be 201, with the content of
+the returned structure indicating specific success or otherwise messages
+on a per-document basis.
+
+The content and structure of the returned JSON will depend on the transaction
+semantics being used for the bulk update; see :ref:`api/db/bulk_docs/semantics`
+for more information. Conflicts and validation errors when updating documents in
+bulk must be handled separately; see :ref:`api/db/bulk_docs/validation`.
+
+.. _api/db/bulk_docs/semantics:
+
+Bulk Documents Transaction Semantics
+------------------------------------
+
+CouchDB supports two different modes for updating (or inserting)
+documents using the bulk documentation system. Each mode affects both
+the state of the documents in the event of system failure, and the level
+of conflict checking performed on each document. The two modes are:
+
+-  ``non-atomic``
+
+   The default mode is non-atomic, that is, CouchDB will only guarantee
+   that some of the documents will be saved when you send the request.
+   The response will contain the list of documents successfully inserted
+   or updated during the process. In the event of a crash, some of the
+   documents may have been successfully saved, and some will have been
+   lost.
+
+   In this mode, the response structure will indicate whether the
+   document was updated by supplying the new ``_rev`` parameter
+   indicating a new document revision was created. If the update failed,
+   then you will get an ``error`` of type ``conflict``. For example:
+
+   .. code-block:: javascript
+
+       [
+          {
+             "id" : "FishStew",
+             "error" : "conflict",
+             "reason" : "Document update conflict."
+          },
+          {
+             "id" : "LambStew",
+             "error" : "conflict",
+             "reason" : "Document update conflict."
+          },
+          {
+             "id" : "7f7638c86173eb440b8890839ff35433",
+             "error" : "conflict",
+             "reason" : "Document update conflict."
+          }
+       ]
+
+
+   In this case no new revision has been created and you will need to
+   submit the document update, with the correct revision tag, to update
+   the document.
+
+-  ``all-or-nothing``
+
+   In all-or-nothing mode, either all documents are written to the
+   database, or no documents are written to the database, in the event
+   of a system failure during commit.
+
+   In addition, the per-document conflict checking is not performed.
+   Instead a new revision of the document is created, even if the new
+   revision is in conflict with the current revision in the database.
+   The returned structure contains the list of documents with new
+   revisions:
+
+   .. code-block:: javascript
+
+       [
+          {
+             "id" : "FishStew",
+             "rev" : "2-e7af4c4e9981d960ecf78605d79b06d1"
+          },
+          {
+             "id" : "LambStew",
+             "rev" : "2-0786321986194c92dd3b57dfbfc741ce"
+          },
+          {
+             "id" : "7f7638c86173eb440b8890839ff35433",
+             "rev" : "2-bdd3bf3563bee516b96885a66c743f8e"
+          }
+       ]
+
+   When updating documents using this mode the revision of a document
+   included in views will be arbitrary. You can check the conflict
+   status for a document by using the ``conflicts=true`` query argument
+   when accessing the view. Conflicts should be handled individually to
+   ensure the consistency of your database.
+
+   To use this mode, you must include the ``all_or_nothing`` field (set
+   to true) within the main body of the JSON of the request.
+
+The effects of different database operations on the different modes are
+summarized below:
+
+* **Transaction Mode**: ``Non-atomic``
+
+  * **Transaction**: ``Insert``
+
+    * **Cause**: Requested document ID already exists
+    * **Resolution**: Resubmit with different document ID, or update the
+      existing document
+
+  * **Transaction**: ``Update``
+
+    * **Cause**: Revision missing or incorrect
+    * **Resolution**: Resubmit with correct revision
+
+* **Transaction Mode**: ``All-or-nothing``
+
+  * **Transaction**: ``Insert`` / ``Update``
+
+    * **Cause**: Additional revision inserted
+    * **Resolution**: Resolve conflicted revisions
+
+Replication of documents is independent of the type of insert or update.
+The documents and revisions created during a bulk insert or update are
+replicated in the same way as any other document. This can mean that if
+you make use of the all-or-nothing mode the exact list of documents,
+revisions (and their conflict state) may or may not be replicated to
+other databases correctly.
+
+.. _api/db/bulk_docs/validation:
+
+Bulk Document Validation and Conflict Errors
+--------------------------------------------
+
+The JSON returned by the ``_bulk_docs`` operation consists of an array
+of JSON structures, one for each document in the original submission.
+The returned JSON structure should be examined to ensure that all of the
+documents submitted in the original request were successfully added to
+the database.
+
+The exact structure of the returned information is:
+
++----------------------------------+-------------------------------------------+
+| Field                            | Description                               |
++==================================+===========================================+
+| docs [array]                     | Bulk Documents Document                   |
++----------------------------------+-------------------------------------------+
+|         id                       | Document ID                               |
++----------------------------------+-------------------------------------------+
+|         error                    | Error type                                |
++----------------------------------+-------------------------------------------+
+|         reason                   | Error string with extended reason         |
++----------------------------------+-------------------------------------------+
+
+When a document (or document revision) is not correctly committed to the
+database because of an error, you should check the ``error`` field to
+determine error type and course of action. Errors will be one of the
+following type:
+
+-  ``conflict``
+
+   The document as submitted is in conflict. If you used the default
+   bulk transaction mode then the new revision will not have been
+   created and you will need to re-submit the document to the database.
+   If you used ``all-or-nothing`` mode then you will need to manually
+   resolve the conflicted revisions of the document.
+
+   Conflict resolution of documents added using the bulk docs interface
+   is identical to the resolution procedures used when resolving
+   conflict errors during replication.
+
+-  ``forbidden``
+
+   Entries with this error type indicate that the validation routine
+   applied to the document during submission has returned an error.
+
+   For example, if your validation routine includes the following:
+
+   .. code-block:: javascript
+
+        throw({forbidden: 'invalid recipe ingredient'});
+
+   The error returned will be:
+
+   .. code-block:: javascript
+
+       {
+          "id" : "7f7638c86173eb440b8890839ff35433",
+          "error" : "forbidden",
+          "reason" : "invalid recipe ingredient"
+       }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/changes.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/changes.rst b/share/doc/src/api/database/changes.rst
new file mode 100644
index 0000000..30d2372
--- /dev/null
+++ b/share/doc/src/api/database/changes.rst
@@ -0,0 +1,144 @@
+.. 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.
+
+.. _changes:
+
+.. _api/db/changes:
+.. _api/db/changes.get:
+
+``GET /db/_changes``
+====================
+
+* **Method**: ``GET /db/_changes``
+* **Request**: None
+* **Response**: JSON success statement
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: doc_ids
+
+    * **Description**:  Specify the list of documents IDs to be filtered
+    * **Optional**: yes
+    * **Type**: json
+    * **Default**: none
+
+  * **Argument**: feed
+
+    * **Description**: Type of the :ref:`changes <changes>` feed
+    * **Optional**: yes
+    * **Type**: string
+    * **Default**: normal
+    * **Supported Values**:
+
+      * **continuous**: :ref:`Continuous <changes/continuous>` mode
+      * **eventsource**: :ref:`Event source <changes/eventsource>` mode
+      * **longpoll**: :ref:`Long polling <changes/longpoll>` mode
+      * **normal**: :ref:`Normal <changes/normal>` mode
+
+  * **Argument**: filter
+
+    * **Description**:  Filter function from a design document to get updates
+    * **Optional**: yes
+    * **Type**: string
+    * **Default**: none
+    * **Supported Values**:
+
+  * **Argument**: heartbeat
+
+    * **Description**:  Period after which an empty line is sent during longpoll
+      or continuous
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 60000
+    * **Quantity**: milliseconds
+
+  * **Argument**: include_docs
+
+    * **Description**:  Include the document with the result
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: limit
+
+    * **Description**:  Maximum number of rows rows to return
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: none
+
+  * **Argument**: since
+
+    * **Description**:  Start the results from changes immediately after the
+      specified sequence number
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 0
+
+Obtains a list of the changes made to the database. This can be used to
+monitor for update and modifications to the database for post processing
+or synchronization.
+
+.. seealso::
+
+   :ref:`Detailed description of available changes feed types <changes>`
+
+The return structure for ``normal`` and ``longpoll`` modes is a JSON
+array of changes objects, and the last update sequence number. The
+structure is described in the following table.
+
++----------------------------------+-------------------------------------------+
+| Field                            | Description                               |
++==================================+===========================================+
+| last_seq                         | Last change sequence number.              |
++----------------------------------+-------------------------------------------+
+| results [array]                  | Changes made to a database                |
++----------------------------------+-------------------------------------------+
+|         changes [array]          | List of changes, field-by-field, for this |
+|                                  | document                                  |
++----------------------------------+-------------------------------------------+
+|         id                       | Document ID                               |
++----------------------------------+-------------------------------------------+
+|         seq                      | Update sequence number                    |
++----------------------------------+-------------------------------------------+
+
+The return format for ``continuous`` mode the server sends a ``CRLF``
+(carriage-return, linefeed) delimited line for each change. Each line
+contains the `JSON object`_.
+
+You can also request the full contents of each document change (instead
+of just the change notification) by using the ``include_docs``
+parameter.
+
+Filtering
+---------
+
+You can filter the contents of the changes feed in a number of ways. The
+most basic way is to specify one or more document IDs to the query. This
+causes the returned structure value to only contain changes for the
+specified IDs. Note that the value of this query argument should be a
+JSON formatted array.
+
+You can also filter the ``_changes`` feed by defining a filter function
+within a design document. The specification for the filter is the same
+as for replication filters. You specify the name of the filter function
+to the ``filter`` parameter, specifying the design document name and
+filter name. For example:
+
+.. code-block:: http
+
+    GET /db/_changes?filter=design_doc/filtername
+
+The ``_changes`` feed can be used to watch changes to specific document
+ID's or the list of ``_design`` documents in a database. If the
+``filters`` parameter is set to ``_doc_ids`` a list of doc IDs can be
+passed in the ``doc_ids`` parameter as a JSON array. For more
+information, see :ref:`changes`.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/common.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/common.rst b/share/doc/src/api/database/common.rst
new file mode 100644
index 0000000..14c72ec
--- /dev/null
+++ b/share/doc/src/api/database/common.rst
@@ -0,0 +1,195 @@
+.. 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.
+
+.. _api/db.head:
+
+``HEAD /db``
+============
+
+* **Method**: ``HEAD /db``
+* **Request**: None
+* **Response**: None
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **200**:
+    Database exists.
+
+  * **404**:
+    Requested database not found.
+
+Returns the HTTP Headers containing a minimal amount of information
+about the specified database. Since the response body is empty this method
+is a lightweight way to check is database exists or not.
+
+.. _api/db.get:
+
+``GET /db``
+===========
+
+* **Method**: ``GET /db``
+* **Request**: None
+* **Response**: Information about the database in JSON format
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **404**:
+    The requested content could not be found. The returned content will include
+    further information, as a JSON object, if available.
+
+Gets information about the specified database. For example, to retrieve
+the information for the database ``recipe``:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes
+    Accept: application/json
+
+The JSON response contains meta information about the database. A sample
+of the JSON returned for an empty database is provided below:
+
+.. code-block:: javascript
+
+    {
+       "compact_running" : false,
+       "committed_update_seq" : 375048,
+       "disk_format_version" : 5,
+       "disk_size" : 33153123,
+       "doc_count" : 18386,
+       "doc_del_count" : 0,
+       "db_name" : "recipes",
+       "instance_start_time" : "1290700340925570",
+       "purge_seq" : 10,
+       "update_seq" : 375048
+    }
+
+
+The elements of the returned structure are shown in the table below:
+
++----------------------------------+-------------------------------------------+
+| Field                            | Description                               |
++==================================+===========================================+
+| committed_update_seq             | The number of committed update.           |
++----------------------------------+-------------------------------------------+
+| compact_running                  | Set to true if the database compaction    |
+|                                  | routine is operating on this database.    |
++----------------------------------+-------------------------------------------+
+| db_name                          | The name of the database.                 |
++----------------------------------+-------------------------------------------+
+| disk_format_version              | The version of the physical format used   |
+|                                  | for the data when it is stored on disk.   |
++----------------------------------+-------------------------------------------+
+| disk_size                        | Size in bytes of the data as stored on the|
+|                                  | disk. Views indexes are not included in   |
+|                                  | the calculation.                          |
++----------------------------------+-------------------------------------------+
+| doc_count                        | A count of the documents in the specified |
+|                                  | database.                                 |
++----------------------------------+-------------------------------------------+
+| doc_del_count                    | Number of deleted documents               |
++----------------------------------+-------------------------------------------+
+| instance_start_time              | Timestamp of 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 to the      |
+|                                  | database.                                 |
++----------------------------------+-------------------------------------------+
+
+.. _api/db.put:
+
+``PUT /db``
+===========
+
+* **Method**: ``PUT /db``
+* **Request**: None
+* **Response**: JSON success statement
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **400**:
+    Invalid database name
+
+  * **412**:
+    Database already exists
+
+Creates a new database. The database name must be composed of one or
+more of the following characters:
+
+-  Lowercase characters (``a-z``)
+
+-  Name must begin with a lowercase letter
+
+-  Digits (``0-9``)
+
+-  Any of the characters ``_``, ``$``, ``(``, ``)``, ``+``, ``-``, and
+   ``/``.
+
+Trying to create a database that does not meet these requirements will
+return an error quoting these restrictions.
+
+To create the database ``recipes``:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes
+    Content-Type: application/json
+
+The returned content contains the JSON status:
+
+.. code-block:: javascript
+
+    {
+       "ok" : true
+    }
+
+Anything should be treated as an error, and the problem should be taken
+form the HTTP response code.
+
+.. _api/db.delete:
+
+``DELETE /db``
+==============
+
+* **Method**: ``DELETE /db``
+* **Request**: None
+* **Response**: JSON success statement
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **200**:
+    Database has been deleted
+
+  * **404**:
+    The requested content could not be found. The returned content will include
+    further information, as a JSON object, if available.
+
+Deletes the specified database, and all the documents and attachments
+contained within it.
+
+To delete the database ``recipes`` you would send the request:
+
+.. code-block:: http
+
+    DELETE http://couchdb:5984/recipes
+    Content-Type: application/json
+
+If successful, the returned JSON will indicate success
+
+.. code-block:: javascript
+
+    {
+       "ok" : true
+    }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/compact.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/compact.rst b/share/doc/src/api/database/compact.rst
new file mode 100644
index 0000000..27a88c4
--- /dev/null
+++ b/share/doc/src/api/database/compact.rst
@@ -0,0 +1,168 @@
+.. 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.
+
+
+.. _api/db/compact:
+.. _api/db/compact.post:
+
+``POST /db/_compact``
+=====================
+
+* **Method**: ``POST /db/_compact``
+* **Request**: None
+* **Response**: JSON success statement
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **202**:
+    Compaction request has been accepted
+
+  * **404**:
+    The requested content could not be found. The returned content will include
+    further information, as a JSON object, if available.
+
+Request compaction of the specified database. Compaction compresses the
+disk database file by performing the following operations:
+
+-  Writes a new version of the database file, removing any unused
+   sections from the new version during write. Because a new file is
+   temporary created for this purpose, you will need twice the current
+   storage space of the specified database in order for the compaction
+   routine to complete.
+
+-  Removes old revisions of documents from the database, up to the
+   per-database limit specified by the ``_revs_limit`` database
+   parameter. See :ref:`api/db.get`.
+
+Compaction can only be requested on an individual database; you cannot
+compact all the databases for a CouchDB instance. The compaction process
+runs as a background process.
+
+You can determine if the compaction process is operating on a database
+by obtaining the database meta information, the ``compact_running``
+value of the returned database structure will be set to true. See
+:ref:`api/db.get`.
+
+You can also obtain a list of running processes to determine whether
+compaction is currently running. See :ref:`api/server/active_tasks`.
+
+.. _api/db/compact/ddoc:
+.. _api/db/compact/ddoc.post:
+
+``POST /db/_compact/design-doc``
+================================
+
+* **Method**: ``POST /db/_compact/design-doc``
+* **Request**: None
+* **Response**: JSON success statement
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **202**:
+    Compaction request has been accepted
+
+  * **404**:
+    The requested content could not be found. The returned content will include
+    further information, as a JSON object, if available.
+
+Compacts the view indexes associated with the specified design document.
+You can use this in place of the full database compaction if you know a
+specific set of view indexes have been affected by a recent database
+change.
+
+For example, to compact the views associated with the ``recipes`` design
+document:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_compact/recipes
+    Content-Type: application/json
+
+CouchDB will immediately return with a status indicating that the
+compaction request has been received (HTTP status code 202):
+
+.. code-block:: javascript
+
+    {
+       "ok" : true
+    }
+
+
+
+
+
+.. _api/db/ensure_full_commit:
+.. _api/db/ensure_full_commit.post:
+
+``POST /db/_ensure_full_commit``
+================================
+
+* **Method**: ``POST /db/_ensure_full_commit``
+* **Request**: None
+* **Response**: JSON success statement
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **202**:
+    Commit completed successfully
+
+  * **404**:
+    The requested content could not be found. The returned content will include
+    further information, as a JSON object, if available.
+
+
+Commits any recent changes to the specified database to disk. You should
+call this if you want to ensure that recent changes have been written.
+For example, to commit all the changes to disk for the database
+``recipes`` you would use:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_ensure_full_commit
+    Content-Type: application/json
+
+This returns a status message, containing the success message and the
+timestamp for when the CouchDB instance was started:
+
+.. code-block:: javascript
+
+    {
+      "ok" : true,
+      "instance_start_time" : "1288186189373361"
+    }
+
+
+.. _api/db/view_cleanup:
+.. _api/db/view_cleanup.post:
+
+``POST /db/_view_cleanup``
+==========================
+
+* **Method**: ``POST /db/_view_cleanup``
+* **Request**: None
+* **Response**: JSON success statement
+* **Admin Privileges Required**: yes
+
+Cleans up the cached view output on disk for a given view. For example:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_view_cleanup
+    Content-Type: application/json
+
+If the request is successful, a basic status message us returned:
+
+.. code-block:: javascript
+
+    {
+       "ok" : true
+    }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/index.rst b/share/doc/src/api/database/index.rst
new file mode 100644
index 0000000..8b2d429
--- /dev/null
+++ b/share/doc/src/api/database/index.rst
@@ -0,0 +1,113 @@
+.. 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.
+
+.. _api/db:
+
+================
+Database Methods
+================
+
+The Database methods provide an interface to an entire database withing
+CouchDB. These are database, rather than document, level requests.
+
+A list of the available methods and URL paths are provided below:
+
++--------+-------------------------+-------------------------------------------+
+| Method | Path                    | Description                               |
++========+=========================+===========================================+
+| HEAD   | /db                     | Checks database existence                 |
++--------+-------------------------+-------------------------------------------+
+| GET    | /db                     | Returns database information              |
++--------+-------------------------+-------------------------------------------+
+| PUT    | /db                     | Create a new database                     |
++--------+-------------------------+-------------------------------------------+
+| DELETE | /db                     | Delete an existing database               |
++--------+-------------------------+-------------------------------------------+
+| GET    | /db/_all_docs           | Returns a built-in view of all documents  |
+|        |                         | in this database                          |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_all_docs           | Returns certain rows from the built-in    |
+|        |                         | view of all documents                     |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_bulk_docs          | Insert multiple documents in to the       |
+|        |                         | database in a single request              |
++--------+-------------------------+-------------------------------------------+
+| GET    | /db/_changes            | Returns changes for the given database    |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_compact            | Starts a compaction for the database      |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_compact/design-doc | Starts a compaction for all the views in  |
+|        |                         | the selected design document              |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_ensure_full_commit | Makes sure all uncommitted changes are    |
+|        |                         | written and synchronized to the disk      |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_missing_revs       | Given a list of document revisions,       |
+|        |                         | returns the document revisions that do not|
+|        |                         | exist in the database                     |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_purge              | Purge some historical documents entirely  |
+|        |                         | from database history                     |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_revs_diff          | Given a list of document revisions,       |
+|        |                         | returns differences between the given     |
+|        |                         | revisions and ones that are in the        |
+|        |                         | database                                  |
++--------+-------------------------+-------------------------------------------+
+| GET    | /db/_revs_limit         | Gets the limit of historical revisions to |
+|        |                         | store for a single document in the        |
+|        |                         | database                                  |
++--------+-------------------------+-------------------------------------------+
+| PUT    | /db/_revs_limit         | Sets the limit of historical revisions to |
+|        |                         | store for a single document in the        |
+|        |                         | database                                  |
++--------+-------------------------+-------------------------------------------+
+| GET    | /db/_security           | Returns the special security object for   |
+|        |                         | the database                              |
++--------+-------------------------+-------------------------------------------+
+| PUT    | /db/_security           | Sets the special security object for the  |
+|        |                         | database                                  |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_temp_view          | Execute a given view function for all     |
+|        |                         | documents and return the result           |
++--------+-------------------------+-------------------------------------------+
+| POST   | /db/_view_cleanup       | Removes view files that are not used by   |
+|        |                         | any design document                       |
++--------+-------------------------+-------------------------------------------+
+
+For all the database methods, the database name within the URL path
+should be the database name that you wish to perform the operation on.
+For example, to obtain the meta information for the database
+``recipes``, you would use the HTTP request:
+
+.. code-block:: http
+
+    GET /recipes
+
+For clarity, the form below is used in the URL paths:
+
+.. code-block:: http
+
+    GET /db
+
+Where ``db`` is the name of any database.
+
+.. toctree::
+
+   common
+   all-docs
+   bulk-docs
+   changes
+   compact
+   security
+   temp-views
+   misc

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/misc.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/misc.rst b/share/doc/src/api/database/misc.rst
new file mode 100644
index 0000000..6355d2e
--- /dev/null
+++ b/share/doc/src/api/database/misc.rst
@@ -0,0 +1,179 @@
+.. 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.
+
+
+.. _api/db/purge:
+.. _api/db/purge.post:
+
+``POST /db/_purge``
+===================
+
+* **Method**: ``POST /db/_purge``
+* **Request**: JSON of the document IDs/revisions to be purged
+* **Response**: JSON structure with purged documents and purge sequence
+* **Admin Privileges Required**: no
+
+A database purge permanently removes the references to deleted documents
+from the database. Deleting a document within CouchDB does not actually
+remove the document from the database, instead, the document is marked as
+a deleted (and a new revision is created). This is to ensure that
+deleted documents are replicated to other databases as having been
+deleted. This also means that you can check the status of a document and
+identify that the document has been deleted.
+
+The purge operation removes the references to the deleted documents from
+the database. The purging of old documents is not replicated to other
+databases. If you are replicating between databases and have deleted a
+large number of documents you should run purge on each database.
+
+.. note::
+
+   Purging documents does not remove the space used by them on disk. To
+   reclaim disk space, you should run a database compact (see
+   :ref:`api/db/compact`), and compact views (see :ref:`api/db/compact/ddoc`).
+
+To perform a purge operation you must send a request including the JSON
+of the document IDs that you want to purge. For example:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_purge
+    Content-Type: application/json
+
+    {
+      "FishStew" : [
+        "17-b3eb5ac6fbaef4428d712e66483dcb79"
+        ]
+    }
+
+The format of the request must include the document ID and one or more
+revisions that must be purged.
+
+The response will contain the purge sequence number, and a list of the
+document IDs and revisions successfully purged.
+
+.. code-block:: javascript
+
+    {
+       "purged" : {
+          "FishStew" : [
+             "17-b3eb5ac6fbaef4428d712e66483dcb79"
+          ]
+       },
+       "purge_seq" : 11
+    }
+
+Updating Indexes
+----------------
+
+The number of purges on a database is tracked using a purge sequence.
+This is used by the view indexer to optimize the updating of views that
+contain the purged documents.
+
+When the indexer identifies that the purge sequence on a database has
+changed, it compares the purge sequence of the database with that stored
+in the view index. If the difference between the stored sequence and
+database is sequence is only 1, then the indexer uses a cached list of
+the most recently purged documents, and then removes these documents
+from the index individually. This prevents completely rebuilding the
+index from scratch.
+
+If the difference between the stored sequence number and current
+database sequence is greater than 1, then the view index is entirely
+rebuilt. This is an expensive operation as every document in the
+database must be examined.
+
+.. _api/db/missing_revs:
+.. _api/db/missing_revs.post:
+
+``POST /db/_missing_revs``
+==========================
+
+* **Method**: ``POST /db/_missing_revs``
+* **Request**: JSON list of document revisions
+* **Response**: JSON of missing revisions
+* **Admin Privileges Required**: no
+
+.. _api/db/revs_diff:
+.. _api/db/revs_diff.post:
+
+``POST /db/_revs_diff``
+=======================
+
+* **Method**: ``POST /db/_revs_diff``
+* **Request**: JSON list of document revisions
+* **Response**: JSON list of differences from supplied document/revision list
+* **Admin Privileges Required**: no
+
+
+
+.. _api/db/revs_limit:
+.. _api/db/revs_limit.get:
+
+``GET /db/_revs_limit``
+=======================
+
+* **Method**: ``GET /db/_revs_limit``
+* **Request**: None
+* **Response**: The current revision limit setting
+* **Admin Privileges Required**: no
+
+
+Gets the current ``revs_limit`` (revision limit) setting.
+
+For example to get the current limit:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_revs_limit
+    Content-Type: application/json
+
+The returned information is the current setting as a numerical scalar:
+
+.. code-block:: javascript
+
+    1000
+
+.. _api/db/revs_limit.put:
+
+``PUT /db/_revs_limit``
+=======================
+
+* **Method**: ``PUT /db/_revs_limit``
+* **Request**: A scalar integer of the revision limit setting
+* **Response**: Confirmation of setting of the revision limit
+* **Admin Privileges Required**: no
+
+Sets the maximum number of document revisions that will be tracked by
+CouchDB, even after compaction has occurred. You can set the revision
+limit on a database by using ``PUT`` with a scalar integer of the limit
+that you want to set as the request body.
+
+For example to set the revs limit to 100 for the ``recipes`` database:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/_revs_limit
+    Content-Type: application/json
+
+    100
+
+If the setting was successful, a JSON status object will be returned:
+
+.. code-block:: javascript
+
+    {
+       "ok" : true
+    }
+
+.. _JSON object: #table-couchdb-api-db_db-json-changes
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/security.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/security.rst b/share/doc/src/api/database/security.rst
new file mode 100644
index 0000000..8f323f9
--- /dev/null
+++ b/share/doc/src/api/database/security.rst
@@ -0,0 +1,99 @@
+.. _api/db/security:
+.. _api/db/security.get:
+
+``GET /db/_security``
+=====================
+
+* **Method**: ``GET /db/_security``
+* **Request**: None
+* **Response**: JSON of the security object
+* **Admin Privileges Required**: no
+
+Gets the current security object from the specified database. The
+security object consists of two compulsory elements, ``admins`` and
+``readers``, which are used to specify the list of users and/or roles
+that have admin and reader rights to the database respectively. Any
+additional fields in the security object are optional. The entire
+security object is made available to validation and other internal
+functions so that the database can control and limit functionality.
+
+To get the existing security object you would send the following
+request:
+
+.. code-block:: javascript
+
+    {
+       "admins" : {
+          "roles" : [],
+          "names" : [
+             "mc",
+             "slp"
+          ]
+       },
+       "readers" : {
+          "roles" : [],
+          "names" : [
+             "tim",
+             "brian"
+          ]
+       }
+    }
+
+Security object structure is:
+
+* **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
+
+.. note::
+   If the security object for a database has never been set, then the
+   value returned will be empty.
+
+.. _api/db/security.put:
+
+``PUT /db/_security``
+=====================
+
+* **Method**: ``PUT /db/_security``
+* **Request**: JSON specifying the admin and user security for the database
+* **Response**: JSON status message
+* **Admin Privileges Required**: no
+
+Sets the security object for the given database.For example, to set the
+security object for the ``recipes`` database:
+
+.. code-block:: javascript
+
+    PUT http://couchdb:5984/recipes/_security
+    Content-Type: application/json
+
+    {
+       "admins" : {
+          "roles" : [],
+          "names" : [
+             "mc",
+             "slp"
+          ]
+       },
+       "readers" : {
+          "roles" : [],
+          "names" : [
+             "tim",
+             "brian"
+          ]
+       }
+    }
+
+If the setting was successful, a JSON status object will be returned:
+
+.. code-block:: javascript
+
+    {
+       "ok" : true
+    }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database/temp-views.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/temp-views.rst b/share/doc/src/api/database/temp-views.rst
new file mode 100644
index 0000000..7700317
--- /dev/null
+++ b/share/doc/src/api/database/temp-views.rst
@@ -0,0 +1,55 @@
+.. _api/db/temp_view:
+.. _api/db/temp_view.post:
+
+``POST /db/_temp_view``
+=======================
+
+* **Method**: ``POST /db/_temp_view``
+* **Request**: JSON with the temporary view definition
+* **Response**: Temporary view result set
+* **Admin Privileges Required**: yes
+
+Creates (and executes) a temporary view based on the view function
+supplied in the JSON request. For example:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_temp_view
+    Content-Type: application/json
+
+    {
+       "map" : "function(doc) { if (doc.value > 9995) { emit(null, doc.value); } }"
+    }
+
+The resulting JSON response is the result from the execution of the
+temporary view:
+
+.. code-block:: javascript
+
+    {
+       "total_rows" : 3,
+       "rows" : [
+          {
+             "value" : 9998.41913029012,
+             "id" : "05361cc6aa42033878acc1bacb1f39c2",
+             "key" : null
+          },
+          {
+             "value" : 9998.94149934853,
+             "id" : "1f443f471e5929dd7b252417625ed170",
+             "key" : null
+          },
+          {
+             "value" : 9998.01511339154,
+             "id" : "1f443f471e5929dd7b252417629c102b",
+             "key" : null
+          }
+       ],
+       "offset" : 0
+    }
+
+The arguments also available to standard view requests also apply to
+temporary views, but the execution of the view may take some time as it
+relies on being executed at the time of the request. In addition to the
+time taken, they are also computationally very expensive to produce. You
+should use a defined view if you want to achieve the best performance.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/ddoc/common.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/ddoc/common.rst b/share/doc/src/api/ddoc/common.rst
new file mode 100644
index 0000000..eb3d740
--- /dev/null
+++ b/share/doc/src/api/ddoc/common.rst
@@ -0,0 +1,464 @@
+.. 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.
+
+
+.. _api/ddoc.get:
+
+``GET /db/_design/design-doc``
+==============================
+
+* **Method**: ``GET /db/_design/design-doc``
+* **Request**:  None
+* **Response**:  JSON of the existing design document
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Specify the revision to return
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: revs
+
+    * **Description**:  Return a list of the revisions for the document
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Supported Values**:
+
+        * **true**: Includes the revisions
+
+  * **Argument**: revs_info
+
+    * **Description**:  Return a list of detailed revision information for the
+      document
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Supported Values**:
+
+      * **true**: Includes the revisions
+
+Returns the specified design document, ``design-doc`` from the specified
+``db``. For example, to retrieve the design document ``recipes`` you
+would send the following request:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_design/recipes
+    Content-Type: application/json
+
+The returned string will be the JSON of the design document:
+
+.. code-block:: javascript
+
+    {
+       "_id" : "_design/recipes",
+       "_rev" : "5-39f56a392b86bbee57e2138921346406"
+       "language" : "javascript",
+       "views" : {
+          "by_recipe" : {
+             "map" : "function(doc) { if (doc.title != null) emit(doc.title, doc) }"
+          },
+       },
+    }
+
+A list of the revisions can be obtained by using the ``revs`` query
+argument, or an extended list of revisions using the ``revs_info`` query
+argument. This operates in the same way as for other documents. Fur
+further examples, see :ref:`api/doc.get`.
+
+.. _api/ddoc.put:
+
+``PUT /db/_design/design-doc``
+==============================
+
+* **Method**: ``PUT /db/_design/design-doc``
+* **Request**:  JSON of the design document
+* **Response**:  JSON status
+* **Admin Privileges Required**: no
+
+Upload the specified design document, ``design-doc``, to the specified
+database. The design document should follow the definition of a design
+document, as summarised in the following table.
+
+* **_id**:  Design Document ID
+* **_rev**:  Design Document Revision
+* **views**:  View
+
+  * **viewname**:  View Definition
+
+    * **map**:  Map Function for View
+    * **reduce (optional)**:  Reduce Function for View
+
+For more information on writing views, see :ref:`api/ddoc/view`.
+
+.. _api/ddoc.delete:
+
+``DELETE /db/_design/design-doc``
+=================================
+
+* **Method**: ``DELETE /db/_design/design-doc``
+* **Request**:  None
+* **Response**:  JSON of deleted design document
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Current revision of the document for validation
+    * **Optional**: yes
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``If-Match``
+
+    * **Description**: Current revision of the document for validation
+    * **Optional**: yes
+
+* **Return Codes**:
+
+  * **409**:
+    Supplied revision is incorrect or missing
+
+Delete an existing design document. Deleting a design document also
+deletes all of the associated view indexes, and recovers the
+corresponding space on disk for the indexes in question.
+
+To delete, you must specify the current revision of the design document
+using the ``rev`` query argument.
+
+For example:
+
+.. code-block:: http
+
+    DELETE http://couchdb:5984/recipes/_design/recipes?rev=2-ac58d589b37d01c00f45a4418c5a15a8
+    Content-Type: application/json
+
+The response contains the delete document ID and revision:
+
+.. code-block:: javascript
+
+    {
+       "id" : "recipe/_design/recipes"
+       "ok" : true,
+       "rev" : "3-7a05370bff53186cb5d403f861aca154",
+    }
+
+.. _api/ddoc.copy:
+
+``COPY /db/_design/design-doc``
+===============================
+
+* **Method**: ``COPY /db/_design/design-doc``
+* **Request**: None
+* **Response**: JSON of the new document and revision
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Revision to copy from
+    * **Optional**: yes
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``Destination``
+
+    * **Description**: Destination document (and optional revision)
+    * **Optional**: no
+
+The ``COPY`` command (non-standard HTTP) copies an existing design
+document to a new or existing document.
+
+The source design document is specified on the request line, with the
+``Destination`` HTTP Header of the request specifying the target
+document.
+
+Copying a Design Document
+-------------------------
+
+To copy the latest version of a design document to a new document you
+specify the base document and target document:
+
+.. code-block:: http
+
+    COPY http://couchdb:5984/recipes/_design/recipes
+    Content-Type: application/json
+    Destination: /recipes/_design/recipelist
+
+The above request copies the design document ``recipes`` to the new
+design document ``recipelist``. The response is the ID and revision of
+the new document.
+
+.. code-block:: javascript
+
+    {
+       "id" : "recipes/_design/recipelist"
+       "rev" : "1-9c65296036141e575d32ba9c034dd3ee",
+    }
+
+.. note::
+   Copying a design document does automatically reconstruct the view
+   indexes. These will be recreated, as with other views, the first
+   time the new view is accessed.
+
+Copying from a Specific Revision
+--------------------------------
+
+To copy *from* a specific version, use the ``rev`` argument to the query
+string:
+
+.. code-block:: http
+
+    COPY http://couchdb:5984/recipes/_design/recipes?rev=1-e23b9e942c19e9fb10ff1fde2e50e0f5
+    Content-Type: application/json
+    Destination: recipes/_design/recipelist
+
+The new design document will be created using the specified revision of
+the source document.
+
+Copying to an Existing Design Document
+--------------------------------------
+
+To copy to an existing document, you must specify the current revision
+string for the target document, using the ``rev`` parameter to the
+``Destination`` HTTP Header string. For example:
+
+.. code-block:: http
+
+    COPY http://couchdb:5984/recipes/_design/recipes
+    Content-Type: application/json
+    Destination: recipes/_design/recipelist?rev=1-9c65296036141e575d32ba9c034dd3ee
+
+The return value will be the new revision of the copied document:
+
+.. code-block:: javascript
+
+    {
+       "id" : "recipes/_design/recipes"
+       "rev" : "2-55b6a1b251902a2c249b667dab1c6692",
+    }
+
+.. _api/ddoc/attachment:
+.. _api/ddoc/attachment.get:
+
+``GET /db/_design/design-doc/attachment``
+=========================================
+
+* **Method**: ``GET /db/_design/design-doc/attachment``
+* **Request**: None
+* **Response**: Returns the attachment data
+* **Admin Privileges Required**: no
+
+Returns the file attachment ``attachment`` associated with the design
+document ``/_design_/design-doc``. The raw data of the associated
+attachment is returned (just as if you were accessing a static file. The
+returned HTTP ``Content-type`` will be the same as the content type set
+when the document attachment was submitted into the database.
+
+.. _api/ddoc/attachment.put:
+
+``PUT /db/_design/design-doc/attachment``
+=========================================
+
+* **Method**: ``PUT /db/_design/design-doc/attachment``
+* **Request**: Raw document data
+* **Response**: JSON document status
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Current document revision
+    * **Optional**: no
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``Content-Length``
+
+    * **Description**: Length (bytes) of the attachment being uploaded
+    * **Optional**: no
+
+  * **Header**: ``Content-Type``
+
+    * **Description**: MIME type for the uploaded attachment
+    * **Optional**: no
+
+  * **Header**: ``If-Match``
+
+    * **Description**: Current revision of the document for validation
+    * **Optional**: yes
+
+Upload the supplied content as an attachment to the specified design
+document (``/_design/design-doc``). The ``attachment`` name provided
+must be a URL encoded string. You must also supply either the ``rev``
+query argument or the ``If-Match`` HTTP header for validation, and the
+HTTP headers (to set the attachment content type). The content type is
+used when the attachment is requested as the corresponding content-type
+in the returned document header.
+
+For example, you could upload a simple text document using the following
+request:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/_design/recipes/view.css?rev=7-f7114d4d81124b223283f3e89eee043e
+    Content-Length: 39
+    Content-Type: text/plain
+
+    div.recipetitle {
+    font-weight: bold;
+    }
+
+Or by using the ``If-Match`` HTTP header:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/FishStew/basic
+    If-Match: 7-f7114d4d81124b223283f3e89eee043e
+    Content-Length: 39
+    Content-Type: text/plain
+
+    div.recipetitle {
+    font-weight: bold;
+    }
+
+The returned JSON contains the new document information:
+
+.. code-block:: javascript
+
+    {
+       "id" : "_design/recipes"
+       "ok" : true,
+       "rev" : "8-cb2b7d94eeac76782a02396ba70dfbf5",
+    }
+
+.. note::
+   Uploading an attachment updates the corresponding document revision.
+   Revisions are tracked for the parent document, not individual attachments.
+
+.. _api/ddoc/attachment.delete:
+
+``DELETE /db/_design/design-doc/attachment``
+============================================
+
+* **Method**: ``DELETE /db/_design/design-doc/attachment``
+* **Request**: None
+* **Response**: JSON status
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Current document revision
+    * **Optional**: no
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``If-Match``
+
+    * **Description**: Current revision of the document for validation
+    * **Optional**: yes
+
+* **Return Codes**:
+
+  * **200**:
+    Attachment deleted successfully
+  * **409**:
+    Supplied revision is incorrect or missing
+
+Deletes the attachment ``attachment`` to the specified
+``_design/design-doc``. You must supply the ``rev`` argument with the
+current revision to delete the attachment.
+
+For example to delete the attachment ``view.css`` from the design
+document ``recipes``:
+
+.. code-block:: http
+
+    DELETE http://couchdb:5984/recipes/_design/recipes/view.css?rev=9-3db559f13a845c7751d407404cdeaa4a
+
+The returned JSON contains the updated revision information for the
+parent document:
+
+.. code-block:: javascript
+
+    {
+       "id" : "_design/recipes"
+       "ok" : true,
+       "rev" : "10-f3b15bb408961f8dcc3d86c7d3b54c4c",
+    }
+
+
+.. _api/ddoc/info:
+.. _api/ddoc/info.get:
+
+``GET /db/_design/design-doc/_info``
+====================================
+
+* **Method**: ``GET /db/_design/design-doc/_info``
+* **Request**: None
+* **Response**: JSON of the design document information
+* **Admin Privileges Required**: no
+
+Obtains information about a given design document, including the index,
+index size and current status of the design document and associated
+index information.
+
+For example, to get the information for the ``recipes`` design document:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_design/recipes/_info
+    Content-Type: application/json
+
+This returns the following JSON structure:
+
+.. code-block:: javascript
+
+    {
+       "name" : "recipes"
+       "view_index" : {
+          "compact_running" : false,
+          "updater_running" : false,
+          "language" : "javascript",
+          "purge_seq" : 10,
+          "waiting_commit" : false,
+          "waiting_clients" : 0,
+          "signature" : "fc65594ee76087a3b8c726caf5b40687",
+          "update_seq" : 375031,
+          "disk_size" : 16491
+       },
+    }
+
+The individual fields in the returned JSON structure are detailed below:
+
+* **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

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/ddoc/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/ddoc/index.rst b/share/doc/src/api/ddoc/index.rst
new file mode 100644
index 0000000..a8049f4
--- /dev/null
+++ b/share/doc/src/api/ddoc/index.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.
+
+
+.. _api/ddoc:
+
+=======================
+Design Document Methods
+=======================
+
+In CouchDB, design documents provide the main interface for building a
+CouchDB application. The design document defines the views used to
+extract information from CouchDB through one or more views. Design
+documents are created within your CouchDB instance in the same way as
+you create database documents, but the content and definition of the
+documents is different. Design Documents are named using an ID defined
+with the design document URL path, and this URL can then be used to
+access the database contents.
+
+Views and lists operate together to provide automated (and formatted)
+output from your database.
+
+.. toctree::
+
+   common
+   views
+   render
+   rewrites

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/ddoc/render.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/ddoc/render.rst b/share/doc/src/api/ddoc/render.rst
new file mode 100644
index 0000000..f22f629
--- /dev/null
+++ b/share/doc/src/api/ddoc/render.rst
@@ -0,0 +1,126 @@
+.. 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.
+
+
+.. _api/ddoc/show:
+.. _api/ddoc/show.get:
+
+``GET /db/_design/design-doc/_show/show-name``
+===============================================
+
+.. todo:: GET /db/_design/design-doc/_show/show-name
+
+* **Method**: ``GET /db/_design/design-doc/_show/show-name``
+* **Request**:  None
+* **Response**:  Returns the result of the show
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: details
+
+    * **Description**:  Indicates whether details should be included
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: format
+
+    * **Description**:  Format of the returned information
+    * **Optional**: yes
+    * **Type**: string
+
+.. _api/ddoc/show/doc.post:
+
+``POST /db/_design/design-doc/_show/show-name/doc``
+===================================================
+
+.. todo:: POST /db/_design/design-doc/_show/show-name/doc
+
+* **Method**: ``POST /db/_design/design-doc/_show/show-name``
+* **Request**:  Custom data
+* **Response**:  Returns the result of the show
+* **Admin Privileges Required**: no
+
+.. _api/ddoc/list/ddoc:
+.. _api/ddoc/list/ddoc.get:
+
+``GET /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
+=========================================================================
+
+.. todo:: GET /db/_design/design-doc/_list/list-name/other-design-doc/view-name
+
+* **Method**: ``GET /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
+* **Request**:  TBC
+* **Response**:  TBC
+* **Admin Privileges Required**: no
+
+.. _api/ddoc/list/ddoc.post:
+
+``POST /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
+==========================================================================
+
+.. todo:: POST /db/_design/design-doc/_list/list-name/other-design-doc/view-name
+
+* **Method**: ``POST /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
+* **Request**:  TBC
+* **Response**:  TBC
+* **Admin Privileges Required**: no
+
+.. _api/ddoc/list:
+.. _api/ddoc/list.get:
+
+``GET /db/_design/design-doc/_list/list-name/view-name``
+========================================================
+
+.. todo:: GET /db/_design/design-doc/_list/list-name/view-name
+
+* **Method**: ``GET /db/_design/design-doc/_list/list-name/view-name``
+* **Request**:  TBC
+* **Response**:  TBC
+* **Admin Privileges Required**: no
+
+.. _api/ddoc/list.post:
+
+``POST /db/_design/design-doc/_list/list-name/view-name``
+=========================================================
+
+.. todo:: POST /db/_design/design-doc/_list/list-name/view-name
+
+* **Method**: ``POST /db/_design/design-doc/_list/list-name/view-name``
+* **Request**:  TBC
+* **Response**:  TBC
+* **Admin Privileges Required**: no
+
+.. _api/ddoc/update/doc:
+.. _api/ddoc/update/doc.put:
+
+``PUT /db/_design/design-doc/_update/updatename/doc``
+=====================================================
+
+.. todo:: POST /db/_design/design-doc/_update/updatename/doc
+
+* **Method**: ``POST /db/_design/design-doc/_update/updatename/doc``
+* **Request**:  TBC
+* **Response**:  TBC
+* **Admin Privileges Required**: no
+
+.. _api/ddoc/update:
+.. _api/ddoc/update.post:
+
+``POST /db/_design/design-doc/_update/updatename``
+==================================================
+
+.. todo:: PUT /db/_design/design-doc/_update/updatename/doc
+
+* **Method**: ``PUT /db/_design/design-doc/_update/updatename/doc``
+* **Request**:  TBC
+* **Response**:  TBC
+* **Admin Privileges Required**: no

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/ddoc/rewrites.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/ddoc/rewrites.rst b/share/doc/src/api/ddoc/rewrites.rst
new file mode 100644
index 0000000..e1998aa
--- /dev/null
+++ b/share/doc/src/api/ddoc/rewrites.rst
@@ -0,0 +1,24 @@
+.. 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.
+
+
+.. _api/ddoc/rewrite:
+
+``ALL /db/_design/design-doc/_rewrite/rewrite-name/anything``
+=============================================================
+
+.. todo:: ALL /db/_design/design-doc/_rewrite/rewrite-name/anything
+
+* **Method**: ``ALL /db/_design/design-doc/_rewrite/rewrite-name/anything``
+* **Request**:  TBC
+* **Response**:  TBC
+* **Admin Privileges Required**: no


[47/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add article about document joins by using views.

Two approaches:
- Linked documents
- View collations based on Christopher Lenz post:

http://www.cmlenz.net/archives/2007/10/couchdb-joins


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/bf60cd5e
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/bf60cd5e
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/bf60cd5e

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: bf60cd5e806e8a2addd01d1df16e7254d142242b
Parents: a2f550b
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 15:22:39 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 15:22:39 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am                |   3 +
 share/doc/src/couchapp/views/collation.rst |   2 +
 share/doc/src/couchapp/views/index.rst     |   1 +
 share/doc/src/couchapp/views/joins.rst     | 426 ++++++++++++++++++++++++
 4 files changed, 432 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/bf60cd5e/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index ab73390..7c4eb56 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -92,6 +92,7 @@ html_files = \
     html/_sources/couchapp/views/collation.txt \
     html/_sources/couchapp/views/index.txt \
     html/_sources/couchapp/views/intro.txt \
+    html/_sources/couchapp/views/joins.txt \
     html/_sources/fauxton/addons.txt \
     html/_sources/fauxton/index.txt \
     html/_sources/fauxton/install.txt \
@@ -181,6 +182,7 @@ html_files = \
     html/couchapp/views/collation.html \
     html/couchapp/views/index.html \
     html/couchapp/views/intro.html \
+    html/couchapp/views/joins.html \
     html/fauxton/addons.html \
     html/fauxton/index.html \
     html/fauxton/install.html \
@@ -268,6 +270,7 @@ src_files = \
     ../src/couchapp/views/collation.rst \
     ../src/couchapp/views/index.rst \
     ../src/couchapp/views/intro.rst \
+    ../src/couchapp/views/joins.rst \
     ../src/fauxton/addons.rst \
     ../src/fauxton/index.rst \
     ../src/fauxton/install.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/bf60cd5e/share/doc/src/couchapp/views/collation.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/collation.rst b/share/doc/src/couchapp/views/collation.rst
index 4b9f1b0..9fa8513 100644
--- a/share/doc/src/couchapp/views/collation.rst
+++ b/share/doc/src/couchapp/views/collation.rst
@@ -11,6 +11,8 @@
 .. the License.
 
 
+.. _views/collation:
+
 ===============
 Views Collation
 ===============

http://git-wip-us.apache.org/repos/asf/couchdb/blob/bf60cd5e/share/doc/src/couchapp/views/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/index.rst b/share/doc/src/couchapp/views/index.rst
index 9239a69..1a77caf 100644
--- a/share/doc/src/couchapp/views/index.rst
+++ b/share/doc/src/couchapp/views/index.rst
@@ -25,3 +25,4 @@ applications with CouchDB
 
   intro
   collation
+  joins

http://git-wip-us.apache.org/repos/asf/couchdb/blob/bf60cd5e/share/doc/src/couchapp/views/joins.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/joins.rst b/share/doc/src/couchapp/views/joins.rst
new file mode 100644
index 0000000..392bf5b
--- /dev/null
+++ b/share/doc/src/couchapp/views/joins.rst
@@ -0,0 +1,426 @@
+.. 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.
+
+
+.. _views/json:
+
+================
+Joins With Views
+================
+
+Linked Documents
+================
+
+If your :ref:`map function <mapfun>` emits an object value which has
+``{'_id': XXX}`` and you :ref:`query view <api/ddoc/view>` with
+``include_docs=true`` parameter, then CouchDB will fetch the document with id
+``XXX`` rather than the document which was processed to emit the key/value pair.
+
+This means that if one document contains the ids of other documents, it can
+cause those documents to be fetched in the view too, adjacent to the same key
+if required.
+
+For example, if you have the following hierarchically-linked documents:
+
+.. code-block:: javascript
+
+  [
+    { "_id": "11111" },
+    { "_id": "22222", "ancestors": ["11111"], "value": "hello" },
+    { "_id": "33333", "ancestors": ["22222","11111"], "value": "world" }
+  ]
+
+You can emit the values with the ancestor documents adjacent to them in the view
+like this:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc.value) {
+      emit([doc.value, 0], null);
+      if (doc.ancestors) {
+        for (var i in doc.ancestors) {
+          emit([doc.value, Number(i)+1], {_id: doc.ancestors[i]});
+        }
+      }
+    }
+  }
+
+The result you get is:
+
+.. code-block:: javascript
+
+  {
+      "total_rows": 5,
+      "offset": 0,
+      "rows": [
+          {
+              "id": "22222",
+              "key": [
+                  "hello",
+                  0
+              ],
+              "value": null,
+              "doc": {
+                  "_id": "22222",
+                  "_rev": "1-0eee81fecb5aa4f51e285c621271ff02",
+                  "ancestors": [
+                      "11111"
+                  ],
+                  "value": "hello"
+              }
+          },
+          {
+              "id": "22222",
+              "key": [
+                  "hello",
+                  1
+              ],
+              "value": {
+                  "_id": "11111"
+              },
+              "doc": {
+                  "_id": "11111",
+                  "_rev": "1-967a00dff5e02add41819138abb3284d"
+              }
+          },
+          {
+              "id": "33333",
+              "key": [
+                  "world",
+                  0
+              ],
+              "value": null,
+              "doc": {
+                  "_id": "33333",
+                  "_rev": "1-11e42b44fdb3d3784602eca7c0332a43",
+                  "ancestors": [
+                      "22222",
+                      "11111"
+                  ],
+                  "value": "world"
+              }
+          },
+          {
+              "id": "33333",
+              "key": [
+                  "world",
+                  1
+              ],
+              "value": {
+                  "_id": "22222"
+              },
+              "doc": {
+                  "_id": "22222",
+                  "_rev": "1-0eee81fecb5aa4f51e285c621271ff02",
+                  "ancestors": [
+                      "11111"
+                  ],
+                  "value": "hello"
+              }
+          },
+          {
+              "id": "33333",
+              "key": [
+                  "world",
+                  2
+              ],
+              "value": {
+                  "_id": "11111"
+              },
+              "doc": {
+                  "_id": "11111",
+                  "_rev": "1-967a00dff5e02add41819138abb3284d"
+              }
+          }
+      ]
+  }
+
+which makes it very cheap to fetch a document plus all its ancestors in one
+query.
+
+Note that the ``"id"`` in the row is still that of the originating document.
+The only difference is that ``include_docs`` fetches a different doc.
+
+The current revision of the document is resolved at query time, not at the time
+the view is generated. This means that if a new revision of the linked document
+is added later, it will appear in view queries even though the view itself
+hasn't changed. To force a specific revision of a linked document to be used,
+emit a ``"_rev"`` property as well as ``"_id"``.
+
+
+Using View Collation
+====================
+
+Just today, there was a discussion on IRC how you'd go about modeling a simple
+blogging system with “post” and “comment” entities, where any blog post might
+have N comments. If you'd be using an SQL database, you'd obviously have two
+tables with foreign keys and you'd be using joins. (At least until you needed
+to add some `denormalization`_).
+
+.. _denormalization: http://en.wikipedia.org/wiki/Denormalization
+
+But what would the “obvious” approach in CouchDB look like?
+
+Approach #1: Comments Inlined
+-----------------------------
+
+A simple approach would be to have one document per blog post, and store the
+comments inside that document:
+
+.. code-block:: javascript
+
+  {
+    "_id": "myslug",
+    "_rev": "123456",
+    "author": "john",
+    "title": "My blog post",
+    "content": "Bla bla bla …",
+    "comments": [
+      {"author": "jack", "content": "…"},
+      {"author": "jane", "content": "…"}
+    ]
+  }
+
+.. note::
+   Of course the model of an actual blogging system would be more extensive,
+   you'd have tags, timestamps, etc etc. This is just to demonstrate the basics.
+
+The obvious advantage of this approach is that the data that belongs together
+is stored in one place. Delete the post, and you automatically delete the
+corresponding comments, and so on.
+
+You may be thinking that putting the comments inside the blog post document
+would not allow us to query for the comments themselves, but you'd be wrong.
+You could trivially write a CouchDB view that would return all comments across
+all blog posts, keyed by author:
+
+.. code-block:: javascript
+
+  function(doc) {
+    for (var i in doc.comments) {
+      map(doc.comments[i].author, doc.comments[i].content);
+    }
+  }
+
+Now you could list all comments by a particular user by invoking the view and
+passing it a ``?key="username"`` query string parameter.
+
+However, this approach has a drawback that can be quite significant for many
+applications: To add a comment to a post, you need to:
+
+- Fetch the blog post document
+- Add the new comment to the JSON structure
+- Send the updated document to the server
+
+Now if you have multiple client processes adding comments at roughly the same
+time, some of them will get a `HTTP 409 Conflict` error on step 3 (that's
+optimistic concurrency in action). For some applications this makes sense, but
+in many other apps, you'd want to append new related data regardless of whether
+other data has been added in the meantime.
+
+The only way to allow non-conflicting addition of related data is by putting
+that related data into separate documents.
+
+Approach #2: Comments Separate
+------------------------------
+
+Using this approach you'd have one document per blog post, and one document per
+comment. The comment documents would have a “backlink” to the post they belong
+to.
+
+The blog post document would look similar to the above, minus the comments
+property. Also, we'd now have a type property on all our documents so that we
+can tell the difference between posts and comments:
+
+.. code-block:: javascript
+
+  {
+    "_id": "myslug",
+    "_rev": "123456",
+    "type": "post",
+    "author": "john",
+    "title": "My blog post",
+    "content": "Bla bla bla …"
+  }
+
+The comments themselves are stored in separate documents, which also have a type
+property (this time with the value “comment”), and in addition feature a post
+property containing the ID of the post document they belong to:
+
+.. code-block:: javascript
+
+  {
+    "_id": "ABCDEF",
+    "_rev": "123456",
+    "type": "comment",
+    "post": "myslug",
+    "author": "jack",
+    "content": "…"
+  }
+
+.. code-block:: javascript
+
+  {
+    "_id": "DEFABC",
+    "_rev": "123456",
+    "type": "comment",
+    "post": "myslug",
+    "author": "jane",
+    "content": "…"
+  }
+
+To list all comments per blog post, you'd add a simple view, keyed by blog post
+ID:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc.type == "comment") {
+      map(doc.post, {author: doc.author, content: doc.content});
+    }
+  }
+
+And you'd invoke that view passing it a ``?key="post_id"`` query string
+parameter.
+
+Viewing all comments by author is just as easy as before:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc.type == "comment") {
+      map(doc.author, {post: doc.post, content: doc.content});
+    }
+  }
+
+So this is better in some ways, but it also has a disadvantage.
+Imagine you want to display a blog post with all the associated comments on the
+same web page. With our first approach, we needed just a single request to the
+CouchDB server, namely a ``GET`` request to the document. With this second
+approach, we need two requests: a ``GET`` request to the post document, and a
+``GET`` request to the view that returns all comments for the post.
+
+That is okay, but not quite satisfactory. Just imagine you wanted to added
+threaded comments: you'd now need an additional fetch per comment. What we'd
+probably want then would be a way to join the blog post and the various comments
+together to be able to retrieve them with a single HTTP request.
+
+This was when Damien Katz, the author of CouchDB, chimed in to the discussion
+on IRC to show us the way.
+
+Optimization: Using the Power of View Collation
+-----------------------------------------------
+
+Obvious to Damien, but not at all obvious to the rest of us: it's fairly simple
+to make a view that includes both the content of the blog post document, and
+the content of all the comments associated with that post. The way you do that
+is by using `complex keys`. Until now we've been using simple string values for
+the view keys, but in fact they can be arbitrary JSON values, so let's make
+some use of that:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc.type == "post") {
+      map([doc._id, 0], doc);
+    } else if (doc.type == "comment") {
+      map([doc.post, 1], doc);
+    }
+  }
+
+Okay, this may be confusing at first. Let's take a step back and look at what
+views in CouchDB are really about.
+
+CouchDB views are basically highly efficient on-disk dictionaries that map keys
+to values, where the key is automatically indexed and can be used to filter
+and/or sort the results you get back from your views. When you “invoke” a view,
+you can say that you're only interested in a subset of the view rows by
+specifying a ``?key=foo`` query string parameter. Or you can specify
+``?startkey=foo`` and/or ``?endkey=bar`` query string parameters to fetch rows
+over a range of keys.
+
+It's also important to note that keys are always used for collating (i.e.
+sorting) the rows. CouchDB has well defined (but as of yet undocumented) rules
+for comparing arbitrary JSON objects for collation. For example, the JSON value
+``["foo", 2]`` is sorted after (considered “greater than”) the values
+``["foo"]`` or ``["foo", 1, "bar"]``, but before e.g. ``["foo", 2, "bar"]``.
+This feature enables a whole class of tricks that are rather non-obvious...
+
+.. seealso::
+
+  :ref:`views/collation`
+
+With that in mind, let's return to the view function above. First note that,
+unlike the previous view functions we've used here, this view handles both
+"post" and "comment" documents, and both of them end up as rows in the same
+view. Also, the key in this view is not just a simple string, but an array.
+The first element in that array is always the ID of the post, regardless of
+whether we're processing an actual post document, or a comment associated with
+a post. The second element is 0 for post documents, and 1 for comment documents.
+
+Let's assume we have two blog posts in our database. Without limiting the view
+results via ``key``, ``startkey``, or ``endkey``, we'd get back something like
+the following:
+
+.. code-block:: javascript
+
+  {
+    "total_rows": 5, "offset": 0, "rows": [{
+        "id": "myslug",
+        "key": ["myslug", 0],
+        "value": {...}
+      }, {
+        "id": "ABCDEF",
+        "key": ["myslug", 1],
+        "value": {...}
+      }, {
+        "id": "DEFABC",
+        "key": ["myslug", 1],
+        "value": {...}
+      }, {
+        "id": "other_slug",
+        "key": ["other_slug", 0],
+        "value": {...}
+      }, {
+        "id": "CDEFAB",
+        "key": ["other_slug", 1],
+        "value": {...}
+      },
+    ]
+  }
+
+.. note::
+   The ``...`` placeholder here would contain the complete JSON encoding of the
+   corresponding document
+
+Now, to get a specific blog post and all associated comments, we'd invoke that
+view with the query string::
+
+  ?startkey=["myslug"]&endkey;=["myslug", 2]
+
+We'd get back the first three rows, those that belong to the ``myslug`` post,
+but not the others. Et voila, we now have the data we need to display a post
+with all associated comments, retrieved via a single ``GET`` request.
+
+You may be asking what the 0 and 1 parts of the keys are for. They're simply
+to ensure that the post document is always sorted before the the associated
+comment documents. So when you get back the results from this view for a
+specific post, you'll know that the first row contains the data for the blog
+post itself, and the remaining rows contain the comment data.
+
+One remaining problem with this model is that comments are not ordered, but
+that's simply because we don't have date/time information associated with them.
+If we had, we'd add the timestamp as third element of the key array, probably
+as ISO date/time strings. Now we would continue using the query string
+``?startkey=["myslug"]&endkey=["myslug", 2]`` to fetch the blog post and all
+associated comments, only now they'd be in chronological order.


[20/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Reduce content duplicity for changes feed.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/ca28e125
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/ca28e125
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/ca28e125

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: ca28e12517b2b6cfb85b5b03491cbb867f64b8a3
Parents: 351e91a
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 03:41:31 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/database.rst | 54 ++++---------------------------------
 share/doc/src/changes.rst      | 20 +++++++++++---
 2 files changed, 21 insertions(+), 53 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/ca28e125/share/doc/src/api/database.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database.rst b/share/doc/src/api/database.rst
index 188a9f7..43a1f1c 100644
--- a/share/doc/src/api/database.rst
+++ b/share/doc/src/api/database.rst
@@ -335,55 +335,11 @@ If successful, the returned JSON will indicate success
 
 Obtains a list of the changes made to the database. This can be used to
 monitor for update and modifications to the database for post processing
-or synchronization. There are three different types of supported changes
-feeds, poll, longpoll, and continuous. All requests are poll requests by
-default. You can select any feed type explicitly using the ``feed``
-query argument.
-
--  **Poll**
-
-   With polling you can request the changes that have occured since a
-   specific sequence number. This returns the JSON structure containing
-   the changed document information. When you perform a poll change
-   request, only the changes since the specific sequence number are
-   returned. For example, the query
-
-   .. code-block:: http
-
-       DELETE http://couchdb:5984/recipes/_changes
-       Content-Type: application/json
-
-   Will get all of the changes in the database. You can request a
-   starting point using the ``since`` query argument and specifying the
-   sequence number. You will need to record the latest sequence number
-   in your client and then use this when making another request as the
-   new value to the ``since`` parameter.
-
--  **Longpoll**
-
-   With long polling the request to the server will remain open until a
-   change is made on the database, when the changes will be reported,
-   and then the connection will close. The long poll is useful when you
-   want to monitor for changes for a specific purpose without wanting to
-   monitoring continuously for changes.
-
-   Because the wait for a change can be significant you can set a
-   timeout before the connection is automatically closed (the
-   ``timeout`` argument). You can also set a heartbeat interval (using
-   the ``heartbeat`` query argument), which sends a newline to keep the
-   connection open.
-
--  **Continuous**
-
-   Continuous sends all new changes back to the client immediately,
-   without closing the connection. In continuous mode the format of the
-   changes is slightly different to accommodate the continuous nature
-   while ensuring that the JSON output is still valid for each change
-   notification.
-
-   As with the longpoll feed type you can set both the timeout and
-   heartbeat intervals to ensure that the connection is kept open for
-   new changes and updates.
+or synchronization.
+
+.. seealso::
+
+   :ref:`Detailed description of available changes feed types <changes>`
 
 The return structure for ``normal`` and ``longpoll`` modes is a JSON
 array of changes objects, and the last update sequence number. The

http://git-wip-us.apache.org/repos/asf/couchdb/blob/ca28e125/share/doc/src/changes.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/changes.rst b/share/doc/src/changes.rst
index 9ec747e..55f561f 100644
--- a/share/doc/src/changes.rst
+++ b/share/doc/src/changes.rst
@@ -143,16 +143,24 @@ including the given sequence number::
 Long Polling
 ============
 
+With long polling the request to the server will remain open until a
+change is made on the database, when the changes will be reported,
+and then the connection will close. The long poll is useful when you
+want to monitor for changes for a specific purpose without wanting to
+monitoring continuously for changes.
+
 The `longpoll` feed (probably most useful used from a browser) is a more
 efficient form of polling that waits for a change to occur before the response
 is sent. `longpoll` avoids the need to frequently poll CouchDB to discover
 nothing has changed!
 
-The response is basically the same JSON as is sent for the normal feed.
+The response is basically the same JSON as is sent for the `normal` feed.
 
-A timeout limits the maximum length of time the connection is open. If there
-are no changes before the timeout expires the response's results will be an
-empty list.  
+Because the wait for a change can be significant you can set a
+timeout before the connection is automatically closed (the
+``timeout`` argument). You can also set a heartbeat interval (using
+the ``heartbeat`` query argument), which sends a newline to keep the
+connection open.
 
 
 .. _changes/continuous:
@@ -168,6 +176,10 @@ A continuous feed stays open and connected to the database until explicitly
 closed and changes are sent to the client as they happen, i.e. in near
 real-time.
 
+As with the `longpoll` feed type you can set both the timeout and heartbeat
+intervals to ensure that the connection is kept open for new changes
+and updates.
+
 The continuous feed's response is a little different than the other feed types
 to simplify the job of the client - each line of the response is either empty
 or a JSON object representing a single change, as found in the normal feed's


[07/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add HEAD /db API method description.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/8d4acc04
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/8d4acc04
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/8d4acc04

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 8d4acc04e30628ac25f94b56b1688d81f8caf7f8
Parents: b226efc
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 22:20:46 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/database.rst | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/8d4acc04/share/doc/src/api/database.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database.rst b/share/doc/src/api/database.rst
index 43a1f1c..38c8f7c 100644
--- a/share/doc/src/api/database.rst
+++ b/share/doc/src/api/database.rst
@@ -24,6 +24,8 @@ A list of the available methods and URL paths are provided below:
 +--------+-------------------------+-------------------------------------------+
 | Method | Path                    | Description                               |
 +========+=========================+===========================================+
+| HEAD   | /db                     | Checks database existence                 |
++--------+-------------------------+-------------------------------------------+
 | GET    | /db                     | Returns database information              |
 +--------+-------------------------+-------------------------------------------+
 | PUT    | /db                     | Create a new database                     |
@@ -99,6 +101,27 @@ For clarity, the form below is used in the URL paths:
 
 Where ``db`` is the name of any database.
 
+.. _api/db.head:
+
+``HEAD /db``
+============
+
+* **Method**: ``HEAD /db``
+* **Request**: None
+* **Response**: None
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **200**:
+    Database exists.
+
+  * **404**:
+    Requested database not found.
+
+Returns the HTTP Headers containing a minimal amount of information
+about the specified database. Since the response body is empty this method
+is a lightweight way to check is database exists or not.
+
 .. _api/db.get:
 
 ``GET /db``


[19/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Provide quick links to show and edit docs on GitHub.

Thanks Marius for his extension.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/485d001d
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/485d001d
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/485d001d

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 485d001d98f51fdd21caafef8055385e10897d22
Parents: 2c74795
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 14:55:09 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am   |  6 +++++-
 share/doc/ext/github.py       | 44 ++++++++++++++++++++++++++++++++++++++
 share/doc/src/conf.py         | 17 +++++++++++----
 share/doc/templates/help.html |  8 +++++++
 4 files changed, 70 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/485d001d/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index c822195..ed8ef6c 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -196,13 +196,17 @@ src_files_html = \
     ../templates/searchbox.html \
     ../templates/utilities.html
 
+sphinx_extensions = \
+    ../ext/github.py
+
 EXTRA_DIST = \
     $(image_files) \
     $(src_files) \
     $(src_files_html) \
     $(info_file_build) \
     $(pdf_file_build) \
-    $(html_files_build)
+    $(html_files_build) \
+    $(sphinx_extensions)
 
 BUILT_SOURCES = \
     $(info_file_build) \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/485d001d/share/doc/ext/github.py
----------------------------------------------------------------------
diff --git a/share/doc/ext/github.py b/share/doc/ext/github.py
new file mode 100644
index 0000000..79bc193
--- /dev/null
+++ b/share/doc/ext/github.py
@@ -0,0 +1,44 @@
+## 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.
+
+import os
+
+
+def get_github_url(app, view, path):
+    return 'https://github.com/{project}/{view}/{branch}/{path}'.format(
+        project=app.config.github_project,
+        view=view,
+        branch=app.config.github_branch,
+        path=path)
+ 
+ 
+def html_page_context(app, pagename, templatename, context, doctree):
+    # base template for common sphinx pages like search or genindex
+    # there is no need to provide github show/edit links for them
+    if templatename != 'page.html':
+        return
+
+    # ok, I'm aware about that this is wrong way to concat url segments
+    # but this is one is most portable between 2.x and 3.x versions
+    # plus it fits our current requirements. But still, patches are welcome (:
+    path = os.path.join(
+        app.config.github_docs_path,
+        os.path.relpath(doctree.get('source'), app.builder.srcdir))
+    context['github_show_url'] = get_github_url(app, 'blob', path)
+    context['github_edit_url'] = get_github_url(app, 'edit', path)
+ 
+ 
+def setup(app):
+    app.add_config_value('github_project', '', True)
+    app.add_config_value('github_branch', 'master', True)
+    app.add_config_value('github_docs_path', '', True)
+    app.connect('html-page-context', html_page_context)

http://git-wip-us.apache.org/repos/asf/couchdb/blob/485d001d/share/doc/src/conf.py
----------------------------------------------------------------------
diff --git a/share/doc/src/conf.py b/share/doc/src/conf.py
index 6fd9112..396c6a9 100644
--- a/share/doc/src/conf.py
+++ b/share/doc/src/conf.py
@@ -10,9 +10,12 @@
 ## License for the specific language governing permissions and limitations under
 ## the License.
 
-import sys, os
+import os
+import sys
 
-extensions = ["sphinx.ext.todo", "sphinx.ext.extlinks"]
+sys.path.insert(0, os.path.abspath('../ext'))
+
+extensions = ["sphinx.ext.todo", "sphinx.ext.extlinks", 'github']
 
 source_suffix = ".rst"
 
@@ -46,7 +49,7 @@ html_logo = "../images/logo.png"
 
 html_favicon = "../images/favicon.ico"
 
-html_sidebars= {
+html_sidebars = {
     "**": [
         "searchbox.html",
         "localtoc.html",
@@ -68,7 +71,7 @@ latex_documents = [(
 )]
 
 latex_elements = {
-    "papersize":"a4paper"
+    "papersize": "a4paper"
 }
 
 texinfo_documents = [(
@@ -86,3 +89,9 @@ extlinks = {
     'issue': ('https://issues.apache.org/jira/browse/COUCHDB-%s', 'COUCHDB-'),
     'commit': ('https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=commit;h=%s', '#')
 }
+
+github_project = 'apache/couchdb'
+
+github_branch = 'master'
+
+github_docs_path = 'share/doc/src'

http://git-wip-us.apache.org/repos/asf/couchdb/blob/485d001d/share/doc/templates/help.html
----------------------------------------------------------------------
diff --git a/share/doc/templates/help.html b/share/doc/templates/help.html
index 67b0e50..fcc75c5 100644
--- a/share/doc/templates/help.html
+++ b/share/doc/templates/help.html
@@ -21,4 +21,12 @@ specific language governing permissions and limitations under the License.
 <li><a href="https://couchdb.apache.org/#mailing-list">Mailing Lists</a></li>
 <li><a href="http://webchat.freenode.net/?channels=couchdb">IRC</a></li>
 <li><a href="https://issues.apache.org/jira/browse/CouchDB">Issues</a></li>
+{%- if github_show_url %}
+<li><a href="{{ github_show_url }}"
+       rel="nofollow">{{ _('Show on GitHub') }}</a></li>
+{%- endif %}
+{%- if github_edit_url %}
+<li><a href="{{ github_edit_url }}"
+       rel="nofollow">{{ _('Edit on GitHub') }}</a></li>
+{%- endif %}
 </ul>


[31/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add Gentoo and FreeBSD install guides.

Feel free to contribute more guides for your OS!


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/18ee5e62
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/18ee5e62
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/18ee5e62

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 18ee5e62eb72aadd93bc07d11f20810a6f6fc53d
Parents: 3abdf0e
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 04:56:21 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am       |  6 +++
 share/doc/src/install/freebsd.rst | 80 ++++++++++++++++++++++++++++++++++
 share/doc/src/install/gentoo.rst  | 29 ++++++++++++
 share/doc/src/install/index.rst   |  2 +
 4 files changed, 117 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/18ee5e62/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 589fe95..4d198e7 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -84,6 +84,8 @@ html_files = \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
     html/_sources/install/index.html \
+    html/_sources/install/freebsd.html \
+    html/_sources/install/gentoo.html \
     html/_sources/install/unix.html \
     html/_sources/install/windows.html \
     html/_sources/query-server/index.txt \
@@ -162,6 +164,8 @@ html_files = \
     html/config/intro.html \
     html/config/proxying.html \
     html/install/index.html \
+    html/install/freebsd.html \
+    html/install/gentoo.html \
     html/install/unix.html \
     html/install/windows.html \
     html/query-server/index.html \
@@ -238,6 +242,8 @@ src_files = \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
     ../src/install/index.rst \
+    ../src/install/freebsd.rst \
+    ../src/install/gentoo.rst \
     ../src/install/unix.rst \
     ../src/install/windows.rst \
     ../src/query-server/index.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/18ee5e62/share/doc/src/install/freebsd.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/freebsd.rst b/share/doc/src/install/freebsd.rst
new file mode 100644
index 0000000..b82edd1
--- /dev/null
+++ b/share/doc/src/install/freebsd.rst
@@ -0,0 +1,80 @@
+.. 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.
+
+
+.. _install/freebsd:
+
+=======================
+Installation on FreeBSD
+=======================
+
+Installation from ports
+=======================
+
+.. code-block:: text
+
+    cd /usr/ports/databases/couchdb
+    make install clean
+
+This will install CouchDB from the ports collection.
+
+Start script
+------------
+
+The following options for ``/etc/rc.conf`` or ``/etc/rc.conf.local`` are
+supported by the start script (defaults shown)::
+
+    couchdb_enable="NO"
+    couchdb_enablelogs="YES"
+    couchdb_user="couchdb"
+
+After enabling couchdb rc service use the following to start CouchDB::
+
+    /usr/local/etc/rc.d/couchdb start
+
+This script responds to the arguments `start`, `stop`, `status`, `rcvar` etc..
+
+The start script will also use settings from the following config files:
+
+- /usr/local/etc/couchdb/default.ini
+- /usr/local/etc/couchdb/local.ini
+
+Administrators should use ``default.ini`` as reference and only modify the
+``local.ini`` file.
+
+Post install
+------------
+In case the install script fails to install a noninteractive user "couchdb" to
+be used for the database, the user needs to be created manually:
+
+I used the ``pw`` command to add a user "couchdb" in group "couchdb":
+
+.. code-block:: text
+
+    pw user add couchdb
+    pw user mod couchdb -c 'CouchDB, time to relax' -s /usr/sbin/nologin -d /var/lib/couchdb
+    pw group add couchdb
+
+The user is added to ``/etc/passwd`` and should look similar to the following:
+
+.. code-block:: text
+
+   shell#  grep couchdb /etc/passwd
+   couchdb:*:1013:1013:Couchdb, time to relax:/var/lib/couchdb/:/usr/sbin/nologin
+
+To change any of these settings, please refrain from editing `/etc/passwd` and
+instead use ``pw user mod ...`` or ``vipw``. Make sure that the user has no
+shell, but instead uses ``/usr/sbin/nologin``. The '*' in the second field means
+that this user can not login via password authorization. For details use
+`man 5 passwd`_.
+
+.. _man 5 passwd: http://linux.die.net/man/5/passwd

http://git-wip-us.apache.org/repos/asf/couchdb/blob/18ee5e62/share/doc/src/install/gentoo.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/gentoo.rst b/share/doc/src/install/gentoo.rst
new file mode 100644
index 0000000..13d1f33
--- /dev/null
+++ b/share/doc/src/install/gentoo.rst
@@ -0,0 +1,29 @@
+.. 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.
+
+
+.. _install/gentoo:
+
+Installation on Gentoo
+======================
+
+The simplest way is to use an the `ebuild`_ and install via `portage`_
+(``emerge``). This takes care of dependencies, creating the `couchdb` user,
+basically everything you need to get up and running.
+
+.. code-block:: text
+
+    emerge --ask --verbose couchdb
+
+
+.. _ebuild: http://devmanual.gentoo.org/quickstart/index.html
+.. _portage: http://www.gentoo.org/doc/en/handbook/handbook-x86.xml?part=2&chap=1

http://git-wip-us.apache.org/repos/asf/couchdb/blob/18ee5e62/share/doc/src/install/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/index.rst b/share/doc/src/install/index.rst
index 6d8082c..45ca9de 100644
--- a/share/doc/src/install/index.rst
+++ b/share/doc/src/install/index.rst
@@ -22,5 +22,7 @@ Installation
 
    unix
    windows
+   freebsd
+   gentoo
 
 


[32/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Bump required Erlang version.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/302783e6
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/302783e6
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/302783e6

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 302783e69e7f87f0953f15a3fd4fb2b0d8fe3bdc
Parents: 18ee5e6
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 05:02:54 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/src/install/unix.rst    | 2 +-
 share/doc/src/install/windows.rst | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/302783e6/share/doc/src/install/unix.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/unix.rst b/share/doc/src/install/unix.rst
index 5988d5c..3cd5902 100644
--- a/share/doc/src/install/unix.rst
+++ b/share/doc/src/install/unix.rst
@@ -49,7 +49,7 @@ Dependencies
 
 You should have the following installed:
 
-* `Erlang OTP (>=R13B04, <R16)  <http://erlang.org/>`_
+* `Erlang OTP (>=R13B04, <R17)  <http://erlang.org/>`_
 * `ICU                          <http://icu-project.org/>`_
 * `OpenSSL                      <http://www.openssl.org/>`_
 * `Mozilla SpiderMonkey (1.7)   <http://www.mozilla.org/js/spidermonkey/>`_

http://git-wip-us.apache.org/repos/asf/couchdb/blob/302783e6/share/doc/src/install/windows.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/install/windows.rst b/share/doc/src/install/windows.rst
index 1ecdb5b..eb46c6e 100644
--- a/share/doc/src/install/windows.rst
+++ b/share/doc/src/install/windows.rst
@@ -39,7 +39,7 @@ Dependencies
 
 You should have the following installed:
 
-* `Erlang OTP (>=R14B01, <R16)   <http://erlang.org/>`_
+* `Erlang OTP (>=14B01, <R17)    <http://erlang.org/>`_
 * `ICU        (>=4.*)            <http://icu-project.org/>`_
 * `OpenSSL    (>0.9.8r)          <http://www.openssl.org/>`_
 * `Mozilla SpiderMonkey (=1.8.5) <http://www.mozilla.org/js/spidermonkey/>`_


[16/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Protocol goes first.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/82478ae3
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/82478ae3
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/82478ae3

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 82478ae38bcdaee317c1acd77fc9c9f9d377ce30
Parents: 391bea7
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 22:53:54 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/replication/index.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/82478ae3/share/doc/src/replication/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication/index.rst b/share/doc/src/replication/index.rst
index 1dec453..cb1e49d 100644
--- a/share/doc/src/replication/index.rst
+++ b/share/doc/src/replication/index.rst
@@ -32,6 +32,6 @@ destination database.
    :maxdepth: 2
 
    intro
+   protocol
    replicator
    conflicts
-   protocol


[10/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Mention X-Couch-Full-Commit header for bulk API.

COUCHDB-1858


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/9af2b446
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/9af2b446
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/9af2b446

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 9af2b446a7f2c163b28d3ebd3bd61cf11cedcdb3
Parents: f38fab0
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 03:04:02 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/database.rst | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/9af2b446/share/doc/src/api/database.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database.rst b/share/doc/src/api/database.rst
index be6643e..ae85948 100644
--- a/share/doc/src/api/database.rst
+++ b/share/doc/src/api/database.rst
@@ -599,6 +599,21 @@ timestamp for when the CouchDB instance was started:
 * **Request**: JSON of the docs and updates to be applied
 * **Response**: JSON success statement
 * **Admin Privileges Required**: no
+
+* **HTTP Headers**:
+
+  * **Header**: ``X-Couch-Full-Commit``
+
+    * **Description**: Overrides server's commit policy.
+    * **Optional**: yes
+    * **Values**:
+
+      * **true**: Ensures that any non-committed changes are committed to
+        physical storage.
+      * **false**: Uses the delay commit in opposite to ``true`` value. CouchDB
+        responses quickly, but without any guarantees that all data are
+        successfully stored on disk.
+
 * **Return Codes**:
 
   * **201**:


[08/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Import wiki article about replication conflicts.

http://wiki.apache.org/couchdb/Replication_and_conflicts?action=recall&rev=10


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/59b7d7f0
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/59b7d7f0
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/59b7d7f0

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 59b7d7f085b9e1b3b20619edf824a73d9d3e5a3a
Parents: ae9ceac
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 22:46:04 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am              |   3 +
 share/doc/src/replications/conflicts.rst | 701 ++++++++++++++++++++++++++
 share/doc/src/replications/index.rst     |   1 +
 3 files changed, 705 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/59b7d7f0/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index cb60fba..2519f7e 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -68,6 +68,7 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
+    html/_sources/replications/conflicts.txt \
     html/_sources/replications/index.txt \
     html/_sources/replications/intro.txt \
     html/_sources/replications/protocol.txt \
@@ -126,6 +127,7 @@ html_files = \
     html/config/services.html \
     html/config/intro.html \
     html/config/proxying.html \
+    html/replications/conflicts.html \
     html/replications/index.html \
     html/replications/intro.html \
     html/replications/protocol.html \
@@ -182,6 +184,7 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
+    ../src/replications/conflicts.rst \
     ../src/replications/index.rst \
     ../src/replications/intro.rst \
     ../src/replications/protocol.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/59b7d7f0/share/doc/src/replications/conflicts.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/conflicts.rst b/share/doc/src/replications/conflicts.rst
new file mode 100644
index 0000000..bcd948d
--- /dev/null
+++ b/share/doc/src/replications/conflicts.rst
@@ -0,0 +1,701 @@
+.. 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.
+
+
+.. _replication/conflicts:
+
+==============================
+Replication and conflict model
+==============================
+
+Let's take the following example to illustrate replication and conflict handling.
+
+- Alice has a document containing Bob's business card;
+- She synchronizes it between her desktop PC and her laptop;
+- On the desktop PC, she updates Bob's E-mail address;
+  Without syncing again, she updates Bob's mobile number on the laptop;
+- Then she replicates the two to each other again.
+
+So on the desktop the document has Bob's new E-mail address and his old mobile
+number, and on the laptop it has his old E-mail address and his new mobile
+number.
+
+The question is, what happens to these conflicting updated documents?
+
+CouchDB replication
+===================
+
+CouchDB works with JSON documents inside databases. Replication of databases
+takes place over HTTP, and can be either a "pull" or a "push", but is
+unidirectional. So the easiest way to perform a full sync is to do a "push"
+followed by a "pull" (or vice versa).
+
+So, Alice creates v1 and sync it. She updates to v2a on one side and v2b on the
+other, and then replicates. What happens?
+
+The answer is simple: both versions exist on both sides!
+
+.. code-block:: text
+
+     DESKTOP                          LAPTOP
+   +---------+
+   | /db/bob |                                     INITIAL
+   |   v1    |                                     CREATION
+   +---------+
+
+   +---------+                      +---------+
+   | /db/bob |  ----------------->  | /db/bob |     PUSH
+   |   v1    |                      |   v1    |
+   +---------+                      +---------+
+
+   +---------+                      +---------+  INDEPENDENT
+   | /db/bob |                      | /db/bob |     LOCAL
+   |   v2a   |                      |   v2b   |     EDITS
+   +---------+                      +---------+
+
+   +---------+                      +---------+
+   | /db/bob |  ----------------->  | /db/bob |     PUSH
+   |   v2a   |                      |   v2a   |
+   +---------+                      |   v2b   |
+                                    +---------+
+
+   +---------+                      +---------+
+   | /db/bob |  <-----------------  | /db/bob |     PULL
+   |   v2a   |                      |   v2a   |
+   |   v2b   |                      |   v2b   |
+   +---------+                      +---------+
+
+After all, this is not a filesystem, so there's no restriction that only one
+document can exist with the name /db/bob. These are just "conflicting" revisions
+under the same name.
+
+Because the changes are always replicated, the data is safe. Both machines have
+identical copies of both documents, so failure of a hard drive on either side
+won't lose any of the changes.
+
+Another thing to notice is that peers do not have to be configured or tracked.
+You can do regular replications to peers, or you can do one-off, ad-hoc pushes
+or pulls. After the replication has taken place, there is no record kept of
+which peer any particular document or revision came from.
+
+So the question now is: what happens when you try to read /db/bob? By default,
+CouchDB picks one arbitrary revision as the "winner", using a deterministic
+algorithm so that the same choice will be made on all peers. The same happens
+with views: the deterministically-chosen winner is the only revision fed into
+your map function.
+
+Let's say that the winner is v2a. On the desktop, if Alice reads the document
+she'll see v2a, which is what she saved there. But on the laptop, after
+replication, she'll also see only v2a. It could look as if the changes she made
+there have been lost - but of course they have not, they have just been hidden
+away as a conflicting revision. But eventually she'll need these changes merged
+into Bob's business card, otherwise they will effectively have been lost.
+
+Any sensible business-card application will, at minimum, have to present the
+conflicting versions to Alice and allow her to create a new version
+incorporating information from them all. Ideally it would merge the updates
+itself.
+
+Conflict avoidance
+==================
+
+When working on a single node, CouchDB will avoid creating conflicting revisions
+by returning a 409 HTTP error. This is because, when you PUT a new version of a
+document, you must give the ``_rev`` of the previous version. If that ``_rev``
+has already been superseded, the update is rejected with a ``HTTP 409 Conflict``.
+
+So imagine two users on the same node are fetching Bob's business card, updating
+it concurrently, and writing it back:
+
+.. code-block:: text
+
+  USER1    ----------->  GET /db/bob
+           <-----------  {"_rev":"1-aaa", ...}
+
+  USER2    ----------->  GET /db/bob
+           <-----------  {"_rev":"1-aaa", ...}
+
+  USER1    ----------->  PUT /db/bob?rev=1-aaa
+           <-----------  {"_rev":"2-bbb", ...}
+
+  USER2    ----------->  PUT /db/bob?rev=1-aaa
+           <-----------  409 Conflict  (not saved)
+
+User2's changes are rejected, so it's up to the app to fetch /db/bob again,
+and either:
+
+#. apply the same changes as were applied to the earlier revision, and submit
+   a new PUT
+#. redisplay the document so the user has to edit it again
+#. just overwrite it with the document being saved before (which is not
+   advisable, as user1's changes will be silently lost)
+
+So when working in this mode, your application still has to be able to handle
+these conflicts and have a suitable retry strategy, but these conflicts never
+end up inside the database itself.
+
+Conflicts in batches
+====================
+
+There are two different ways that conflicts can end up in the database:
+
+- Conflicting changes made on different databases, which are replicated to each
+  other, as shown earlier.
+- Changes are written to the database using ``_bulk_docs`` and all_or_nothing,
+  which bypasses the 409 mechanism.
+
+The :ref:`_bulk_docs API <api/db/bulk_docs>` lets you submit multiple updates
+(and/or deletes) in a single HTTP POST. Normally, these are treated as
+independent updates; some in the batch may fail because the `_rev` is stale
+(just like a 409 from a PUT) whilst others are written successfully.
+The response from ``_bulk_docs`` lists the success/fail separately for each
+document in the batch.
+
+However there is another mode of working, whereby you specify
+``{"all_or_nothing":true}`` as part of the request. This is CouchDB's nearest
+equivalent of a "transaction", but it's not the same as a database transaction
+which can fail and roll back. Rather, it means that all of the changes in the
+request will be forcibly applied to the database, even if that introduces
+conflicts. The only guarantee you are given is that they will either all be
+applied to the database, or none of them (e.g. if the power is pulled out before
+the update is finished writing to disk).
+
+So this gives you a way to introduce conflicts within a single database
+instance. If you choose to do this instead of PUT, it means you don't have to
+write any code for the possibility of getting a 409 response, because you will
+never get one. Rather, you have to deal with conflicts appearing later in the
+database, which is what you'd have to do in a multi-master application anyway.
+
+.. code-block:: http
+
+  POST /db/_bulk_docs
+
+.. code-block:: javascript
+
+  {
+    "all_or_nothing": true,
+    "docs": [
+      {"_id":"x", "_rev":"1-xxx", ...},
+      {"_id":"y", "_rev":"1-yyy", ...},
+      ...
+    ]
+  }
+
+Revision tree
+=============
+
+When you update a document in CouchDB, it keeps a list of the previous
+revisions. In the case where conflicting updates are introduced, this history
+branches into a tree, where the current conflicting revisions for this document
+form the tips (leaf nodes) of this tree:
+
+.. code-block:: text
+
+      ,--> r2a
+    r1 --> r2b
+      `--> r2c
+
+Each branch can then extend its history - for example if you read revision r2b
+and then PUT with ?rev=r2b then you will make a new revision along that
+particular branch.
+
+.. code-block:: text
+
+      ,--> r2a -> r3a -> r4a
+    r1 --> r2b -> r3b
+      `--> r2c -> r3c
+
+Here, (r4a, r3b, r3c) are the set of conflicting revisions. The way you resolve
+a conflict is to delete the leaf nodes along the other branches. So when you
+combine (r4a+r3b+r3c) into a single merged document, you would replace r4a and
+delete r3b and r3c.
+
+.. code-block:: text
+
+      ,--> r2a -> r3a -> r4a -> r5a
+    r1 --> r2b -> r3b -> (r4b deleted)
+      `--> r2c -> r3c -> (r4c deleted)
+
+Note that r4b and r4c still exist as leaf nodes in the history tree, but as
+deleted docs. You can retrieve them but they will be marked ``"_deleted":true``.
+
+When you compact a database, the bodies of all the non-leaf documents are
+discarded. However, the list of historical _revs is retained, for the benefit of
+later conflict resolution in case you meet any old replicas of the database at
+some time in future. There is "revision pruning" to stop this getting
+arbitrarily large.
+
+Working with conflicting documents
+==================================
+
+The basic :ref:`GET /db/bob <api/doc.get>` operation will not show you any
+information about conflicts. You see only the deterministically-chosen winner,
+and get no indication as to whether other conflicting revisions exist or not:
+
+.. code-block:: javascript
+
+  {
+    "_id":"test",
+    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+    "hello":"bar"
+  }
+
+If you do ``GET /db/bob?conflicts=true``, and the document is in a conflict
+state, then you will get the winner plus a _conflicts member containing an array
+of the revs of the other, conflicting revision(s). You can then fetch them
+individually using subsequent ``GET /db/bob?rev=xxxx`` operations:
+
+.. code-block:: javascript
+
+  {
+    "_id":"test",
+    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+    "hello":"bar",
+    "_conflicts":[
+      "2-65db2a11b5172bf928e3bcf59f728970",
+      "2-5bc3c6319edf62d4c624277fdd0ae191"
+    ]
+  }
+
+If you do ``GET /db/bob?open_revs=all`` then you will get all the leaf nodes of
+the revision tree. This will give you all the current conflicts, but will also
+give you leaf nodes which have been deleted (i.e. parts of the conflict history
+which have since been resolved). You can remove these by filtering out documents
+with ``"_deleted":true``:
+
+.. code-block:: javascript
+
+  [
+    {"ok":{"_id":"test","_rev":"2-5bc3c6319edf62d4c624277fdd0ae191","hello":"foo"}},
+    {"ok":{"_id":"test","_rev":"2-65db2a11b5172bf928e3bcf59f728970","hello":"baz"}},
+    {"ok":{"_id":"test","_rev":"2-b91bb807b4685080c6a651115ff558f5","hello":"bar"}}
+  ]
+
+The ``"ok"`` tag is an artifact of ``open_revs``, which also lets you list
+explicit revisions as a JSON array, e.g. ``open_revs=[rev1,rev2,rev3]``. In this
+form, it would be possible to request a revision which is now missing, because
+the database has been compacted.
+
+.. note::
+  The order of revisions returned by ``open_revs=all`` is **NOT** related to
+  the deterministic "winning" algorithm. In the above example, the winning
+  revision is 2-b91b... and happens to be returned last, but in other cases it
+  can be returned in a different position.
+
+Once you have retrieved all the conflicting revisions, your application can then
+choose to display them all to the user. Or it could attempt to merge them, write
+back the merged version, and delete the conflicting versions - that is, to
+resolve the conflict permanently.
+
+As described above, you need to update one revision and delete all the
+conflicting revisions explicitly. This can be done using a single `POST` to
+``_bulk_docs``, setting ``"_deleted":true`` on those revisions you wish to
+delete.
+
+Multiple document API
+=====================
+
+You can fetch multiple documents at once using ``include_docs=true`` on a view.
+However, a ``conflicts=true`` request is ignored; the "doc" part of the value
+never includes a ``_conflicts`` member. Hence you would need to do another query
+to determine for each document whether it is in a conflicting state:
+
+.. code-block:: bash
+
+  $ curl 'http://127.0.0.1:5984/conflict_test/_all_docs?include_docs=true&conflicts=true'
+
+.. code-block:: javascript
+
+  {
+    "total_rows":1,
+    "offset":0,
+    "rows":[
+      {
+        "id":"test",
+        "key":"test",
+        "value":{"rev":"2-b91bb807b4685080c6a651115ff558f5"},
+        "doc":{
+          "_id":"test",
+          "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+          "hello":"bar"
+        }
+      }
+    ]
+  }
+
+.. code-block:: bash
+
+  $ curl 'http://127.0.0.1:5984/conflict_test/test?conflicts=true'
+
+.. code-block:: javascript
+
+  {
+    "_id":"test",
+    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+    "hello":"bar",
+    "_conflicts":[
+      "2-65db2a11b5172bf928e3bcf59f728970",
+      "2-5bc3c6319edf62d4c624277fdd0ae191"
+    ]
+  }
+
+View map functions
+==================
+
+Views only get the winning revision of a document. However they do also get a
+``_conflicts`` member if there are any conflicting revisions. This means you can
+write a view whose job is specifically to locate documents with conflicts.
+Here is a simple map function which achieves this:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc._conflicts) {
+      emit(null, [doc._rev].concat(doc._conflicts));
+    }
+  }
+
+which gives the following output:
+
+.. code-block:: javascript
+
+  {
+    "total_rows":1,
+    "offset":0,
+    "rows":[
+      {
+        "id":"test",
+        "key":null,
+        "value":[
+          "2-b91bb807b4685080c6a651115ff558f5",
+          "2-65db2a11b5172bf928e3bcf59f728970",
+          "2-5bc3c6319edf62d4c624277fdd0ae191"
+        ]
+      }
+    ]
+  }
+
+If you do this, you can have a separate "sweep" process which periodically scans
+your database, looks for documents which have conflicts, fetches the conflicting
+revisions, and resolves them.
+
+Whilst this keeps the main application simple, the problem with this approach is
+that there will be a window between a conflict being introduced and it being
+resolved. From a user's viewpoint, this may appear that the document they just
+saved successfully may suddenly lose their changes, only to be resurrected some
+time later. This may or may not be acceptable.
+
+Also, it's easy to forget to start the sweeper, or not to implement it properly,
+and this will introduce odd behaviour which will be hard to track down.
+
+CouchDB's "winning" revision algorithm may mean that information drops out of a
+view until a conflict has been resolved. Consider Bob's business card again;
+suppose Alice has a view which emits mobile numbers, so that her telephony
+application can display the caller's name based on caller ID. If there are
+conflicting documents with Bob's old and new mobile numbers, and they happen to
+be resolved in favour of Bob's old number, then the view won't be able to
+recognise his new one. In this particular case, the application might have
+preferred to put information from both the conflicting documents into the view,
+but this currently isn't possible.
+
+Suggested algorithm to fetch a document with conflict resolution:
+
+#. Get document via ``GET docid?conflicts=true`` request;
+#. For each member in the ``_conflicts`` array call ``GET docid?rev=xxx``.
+   If any errors occur at this stage, restart from step 1.
+   (There could be a race where someone else has already resolved this conflict
+   and deleted that rev)
+#. Perform application-specific merging
+#. Write ``_bulk_docs`` with an update to the first rev and deletes of the other
+   revs.
+
+This could either be done on every read (in which case you could replace all
+calls to GET in your application with calls to a library which does the above),
+or as part of your sweeper code.
+
+And here is an example of this in Ruby using the low-level `RestClient`_:
+
+.. _RestClient: https://rubygems.org/gems/rest-client
+
+.. code-block:: ruby
+
+  require 'rubygems'
+  require 'rest_client'
+  require 'json'
+  DB="http://127.0.0.1:5984/conflict_test"
+
+  # Write multiple documents as all_or_nothing, can introduce conflicts
+  def writem(docs)
+    JSON.parse(RestClient.post("#{DB}/_bulk_docs", {
+      "all_or_nothing" => true,
+      "docs" => docs,
+    }.to_json))
+  end
+
+  # Write one document, return the rev
+  def write1(doc, id=nil, rev=nil)
+    doc['_id'] = id if id
+    doc['_rev'] = rev if rev
+    writem([doc]).first['rev']
+  end
+
+  # Read a document, return *all* revs
+  def read1(id)
+    retries = 0
+    loop do
+      # FIXME: escape id
+      res = [JSON.parse(RestClient.get("#{DB}/#{id}?conflicts=true"))]
+      if revs = res.first.delete('_conflicts')
+        begin
+          revs.each do |rev|
+            res << JSON.parse(RestClient.get("#{DB}/#{id}?rev=#{rev}"))
+          end
+        rescue
+          retries += 1
+          raise if retries >= 5
+          next
+        end
+      end
+      return res
+    end
+  end
+
+  # Create DB
+  RestClient.delete DB rescue nil
+  RestClient.put DB, {}.to_json
+
+  # Write a document
+  rev1 = write1({"hello"=>"xxx"},"test")
+  p read1("test")
+
+  # Make three conflicting versions
+  write1({"hello"=>"foo"},"test",rev1)
+  write1({"hello"=>"bar"},"test",rev1)
+  write1({"hello"=>"baz"},"test",rev1)
+
+  res = read1("test")
+  p res
+
+  # Now let's replace these three with one
+  res.first['hello'] = "foo+bar+baz"
+  res.each_with_index do |r,i|
+    unless i == 0
+      r.replace({'_id'=>r['_id'], '_rev'=>r['_rev'], '_deleted'=>true})
+    end
+  end
+  writem(res)
+
+  p read1("test")
+
+An application written this way never has to deal with a ``PUT 409``, and is
+automatically multi-master capable.
+
+You can see that it's straightforward enough when you know what you're doing.
+It's just that CouchDB doesn't currently provide a convenient HTTP API for
+"fetch all conflicting revisions", nor "PUT to supersede these N revisions", so
+you need to wrap these yourself. I also don't know of any client-side libraries
+which provide support for this.
+
+Merging and revision history
+============================
+
+Actually performing the merge is an application-specific function. It depends
+on the structure of your data. Sometimes it will be easy: e.g. if a document
+contains a list which is only ever appended to, then you can perform a union of
+the two list versions.
+
+Some merge strategies look at the changes made to an object, compared to its
+previous version. This is how git's merge function works.
+
+For example, to merge Bob's business card versions v2a and v2b, you could look
+at the differences between v1 and v2b, and then apply these changes to v2a as
+well.
+
+With CouchDB, you can sometimes get hold of old revisions of a document.
+For example, if you fetch ``/db/bob?rev=v2b&revs_info=true`` you'll get a list
+of the previous revision ids which ended up with revision v2b. Doing the same
+for v2a you can find their common ancestor revision. However if the database
+has been compacted, the content of that document revision will have been lost.
+``revs_info`` will still show that v1 was an ancestor, but report it as
+"missing"::
+
+  BEFORE COMPACTION           AFTER COMPACTION
+
+       ,-> v2a                     v2a
+     v1
+       `-> v2b                     v2b
+
+So if you want to work with diffs, the recommended way is to store those diffs
+within the new revision itself. That is: when you replace v1 with v2a, include
+an extra field or attachment in v2a which says which fields were changed from
+v1 to v2a. This unfortunately does mean additional book-keeping for your
+application.
+
+Comparison with other replicating data stores
+=============================================
+
+The same issues arise with other replicating systems, so it can be instructive
+to look at these and see how they compare with CouchDB. Please feel free to add
+other examples.
+
+Unison
+------
+
+`Unison`_ is a bi-directional file synchronisation tool. In this case, the
+business card would be a file, say `bob.vcf`.
+
+.. _Unison: http://www.cis.upenn.edu/~bcpierce/unison/
+
+When you run unison, changes propagate both ways. If a file has changed on one
+side but not the other, the new replaces the old. Unison maintains a local state
+file so that it knows whether a file has changed since the last successful
+replication.
+
+In our example it has changed on both sides. Only one file called `bob.vcf`
+can exist within the filesystem. Unison solves the problem by simply ducking
+out: the user can choose to replace the remote version with the local version,
+or vice versa (both of which would lose data), but the default action is to
+leave both sides unchanged.
+
+From Alice's point of view, at least this is a simple solution. Whenever she's
+on the desktop she'll see the version she last edited on the desktop, and
+whenever she's on the laptop she'll see the version she last edited there.
+
+But because no replication has actually taken place, the data is not protected.
+If her laptop hard drive dies, she'll lose all her changes made on the laptop;
+ditto if her desktop hard drive dies.
+
+It's up to her to copy across one of the versions manually (under a different
+filename), merge the two, and then finally push the merged version to the other
+side.
+
+Note also that the original file (version v1) has been lost by this point.
+So it's not going to be known from inspection alone which of v2a and v2b has the
+most up-to-date E-mail address for Bob, and which has the most up-to-date mobile
+number. Alice has to remember which she entered last.
+
+
+Git
+----
+
+`Git`_ is a well-known distributed source control system. Like Unison, git deals
+with files. However, git considers the state of a whole set of files as a single
+object, the "tree". Whenever you save an update, you create a "commit" which
+points to both the updated tree and the previous commit(s), which in turn point
+to the previous tree(s). You therefore have a full history of all the states of
+the files. This forms a branch, and a pointer is kept to the tip of the branch,
+from which you can work backwards to any previous state. The "pointer" is
+actually an SHA1 hash of the tip commit.
+
+.. _Git: http://git-scm.com/
+
+If you are replicating with one or more peers, a separate branch is made for
+each of the peers. For example, you might have::
+
+    master               -- my local branch
+    remotes/foo/master   -- branch on peer 'foo'
+    remotes/bar/master   -- branch on peer 'bar'
+
+In the normal way of working, replication is a "pull", importing changes from
+a remote peer into the local repository. A "pull" does two things: first "fetch"
+the state of the peer into the remote tracking branch for that peer; and then
+attempt to "merge" those changes into the local branch.
+
+Now let's consider the business card. Alice has created a git repo containing
+``bob.vcf``, and cloned it across to the other machine. The branches look like
+this, where ``AAAAAAAA`` is the SHA1 of the commit::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: AAAAAAAA                        master: AAAAAAAA
+  remotes/laptop/master: AAAAAAAA         remotes/desktop/master: AAAAAAAA
+
+Now she makes a change on the desktop, and commits it into the desktop repo;
+then she makes a different change on the laptop, and commits it into the laptop
+repo::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: BBBBBBBB                        master: CCCCCCCC
+  remotes/laptop/master: AAAAAAAA         remotes/desktop/master: AAAAAAAA
+
+Now on the desktop she does ``git pull laptop``. Firstly, the remote objects
+are copied across into the local repo and the remote tracking branch is
+updated::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: BBBBBBBB                        master: CCCCCCCC
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: AAAAAAAA
+
+.. note::
+  repo still contains AAAAAAAA because commits BBBBBBBB and CCCCCCCC point to it
+
+Then git will attempt to merge the changes in. It can do this because it knows
+the parent commit to ``CCCCCCCC`` is ``AAAAAAAA``, so it takes a diff between
+``AAAAAAAA`` and ``CCCCCCCC`` and tries to apply it to ``BBBBBBBB``.
+
+If this is successful, then you'll get a new version with a merge commit::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: DDDDDDDD                        master: CCCCCCCC
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: AAAAAAAA
+
+Then Alice has to logon to the laptop and run ``git pull desktop``. A similar
+process occurs. The remote tracking branch is updated::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: DDDDDDDD                        master: CCCCCCCC
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: DDDDDDDD
+
+Then a merge takes place. This is a special-case: ``CCCCCCCC`` one of the parent
+commits of ``DDDDDDDD``, so the laptop can `fast forward` update from
+``CCCCCCCC`` to ``DDDDDDDD`` directly without having to do any complex merging.
+This leaves the final state as::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: DDDDDDDD                        master: DDDDDDDD
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: DDDDDDDD
+
+Now this is all and good, but you may wonder how this is relevant when thinking
+about CouchDB.
+
+Firstly, note what happens in the case when the merge algorithm fails.
+The changes are still propagated from the remote repo into the local one, and
+are available in the remote tracking branch; so unlike Unison, you know the data
+is protected. It's just that the local working copy may fail to update, or may
+diverge from the remote version. It's up to you to create and commit the
+combined version yourself, but you are guaranteed to have all the history you
+might need to do this.
+
+Note that whilst it's possible to build new merge algorithms into Git,
+the standard ones are focused on line-based changes to source code. They don't
+work well for XML or JSON if it's presented without any line breaks.
+
+The other interesting consideration is multiple peers. In this case you have
+multiple remote tracking branches, some of which may match your local branch,
+some of which may be behind you, and some of which may be ahead of you
+(i.e. contain changes that you haven't yet merged)::
+
+  master: AAAAAAAA
+  remotes/foo/master: BBBBBBBB
+  remotes/bar/master: CCCCCCCC
+  remotes/baz/master: AAAAAAAA
+
+Note that each peer is explicitly tracked, and therefore has to be explicitly
+created. If a peer becomes stale or is no longer needed, it's up to you to
+remove it from your configuration and delete the remote tracking branch.
+This is different to CouchDB, which doesn't keep any peer state in the database.
+
+Another difference with git is that it maintains all history back to time
+zero - git compaction keeps diffs between all those versions in order to reduce
+size, but CouchDB discards them. If you are constantly updating a document,
+the size of a git repo would grow forever. It is possible (with some effort)
+to use "history rewriting" to make git forget commits earlier than a particular
+one.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/59b7d7f0/share/doc/src/replications/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/index.rst b/share/doc/src/replications/index.rst
index 940a29c..1dec453 100644
--- a/share/doc/src/replications/index.rst
+++ b/share/doc/src/replications/index.rst
@@ -33,4 +33,5 @@ destination database.
 
    intro
    replicator
+   conflicts
    protocol


[33/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Move changes feeds description into API article.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/8f4db910
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/8f4db910
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/8f4db910

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 8f4db9109c7483ff1af136aa8c5733c689823b32
Parents: d67c273
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 04:36:08 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am            |   3 -
 share/doc/src/api/database/changes.rst | 291 ++++++++++++++++++++++------
 share/doc/src/changes.rst              | 250 ------------------------
 share/doc/src/index.rst                |   1 -
 4 files changed, 232 insertions(+), 313 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/8f4db910/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index c9fc423..1650fec 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -92,7 +92,6 @@ html_files = \
     html/_sources/replications/protocol.txt \
     html/_sources/replications/replicator.txt \
     html/_sources/changelog.txt \
-    html/_sources/changes.txt \
     html/_sources/contributing.txt \
     html/_sources/ddocs.txt \
     html/_sources/index.txt \
@@ -168,7 +167,6 @@ html_files = \
     html/replications/protocol.html \
     html/replications/replicator.html \
     html/changelog.html \
-    html/changes.html \
     html/ddocs.html \
     html/index.html \
     html/intro.html \
@@ -242,7 +240,6 @@ src_files = \
     ../src/replication/protocol.rst \
     ../src/replication/replicator.rst \
     ../src/changelog.rst \
-    ../src/changes.rst \
     ../src/contributing.rst \
     ../src/ddocs.rst \
     ../src/index.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/8f4db910/share/doc/src/api/database/changes.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database/changes.rst b/share/doc/src/api/database/changes.rst
index 30d2372..acdc238 100644
--- a/share/doc/src/api/database/changes.rst
+++ b/share/doc/src/api/database/changes.rst
@@ -10,11 +10,11 @@
 .. License for the specific language governing permissions and limitations under
 .. the License.
 
-.. _changes:
 
 .. _api/db/changes:
 .. _api/db/changes.get:
 
+====================
 ``GET /db/_changes``
 ====================
 
@@ -22,74 +22,128 @@
 * **Request**: None
 * **Response**: JSON success statement
 * **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: doc_ids
 
-    * **Description**:  Specify the list of documents IDs to be filtered
-    * **Optional**: yes
-    * **Type**: json
-    * **Default**: none
+A list of changes made to documents in the database, in the order they were
+made, can be obtained from the database's ``_changes`` resource.
+This can be used to monitor for update and modifications to the database for
+post processing or synchronization. You can query the ``_changes`` resource by
+issuing a ``GET`` request with the following (optional) parameters:
+
++--------------+----------------------------------------------+---------------+--------------+
+| Parameter    | Value                                        | Default Value |  Notes       |
++==============+==============================================+===============+==============+
+| since        | seqnum / now                                 | 0             | \(1)         |
++--------------+----------------------------------------------+---------------+--------------+
+| limit        | maxsequences                                 | none          | \(2)         |
++--------------+----------------------------------------------+---------------+--------------+
+| descending   | boolean                                      | false         | \(3)         |
++--------------+----------------------------------------------+---------------+--------------+
+| feed         | normal / longpoll / continuous / eventsource | normal        | \(4)         |
++--------------+----------------------------------------------+---------------+--------------+
+| heartbeat    | milliseconds                                 | 60000         | \(5)         |
++--------------+----------------------------------------------+---------------+--------------+
+| timeout      | milliseconds                                 | 60000         | \(6)         |
++--------------+----------------------------------------------+---------------+--------------+
+| filter       | designdoc/filtername / _view                 | none          | \(7)         |
++--------------+----------------------------------------------+---------------+--------------+
+| include_docs | boolean                                      | false         | \(8)         |
++--------------+----------------------------------------------+---------------+--------------+
+| style        | all_docs / main_only                         | main_only     | \(9)         |
++--------------+----------------------------------------------+---------------+--------------+
+| view         | designdoc/filtername                         | none          | \(10)        |
++--------------+----------------------------------------------+---------------+--------------+
+
+Notes:
+
+(1) Start the results from the change immediately after the given sequence
+    number.
+
+(2) Limit number of result rows to the specified value (note that using 0 here
+    has the same effect as 1).
+
+(3) Return the change results in descending sequence order (most recent change
+    first)
+
+(4) Select the type of feed.
+
+(5) Period in milliseconds after which an empty line is sent in the results.
+    Only applicable for `longpoll` or `continuous` feeds. Overrides any timeout
+    to keep the feed alive indefinitely.
+
+(6) Maximum period in milliseconds to wait for a change before the response is
+    sent, even if there are no results. Only applicable for `longpoll` or
+    `continuous` feeds. Note that 60000 is also the default maximum timeout to
+    prevent undetected dead connections.
+
+    You can change the default maximum timeout in your ini-configuration:
+
+    .. code-block:: ini
+
+        [httpd]
+        changes_timeout=#millisecs
+
+(7) Reference to a :ref:`filter function <filterfun>` from a design document
+    that will filter whole stream emitting only filtered events.
+    See the `section in the book`_ for more information.
+
+(8) Include the associated document with each result. If there are conflicts,
+    only the winning revision is returned.
+
+(9) Specifies how many revisions are returned in the changes array.
+    The default, `main_only`, will only return the current "winning" revision;
+    `all_docs` will return all leaf revisions (including conflicts and deleted
+    former conflicts.)
+
+(10) Allows to use view functions as filters. It requires to set ``filter``
+     special value `_view` to enable this feature. Documents counted as "passed"
+     for view filter in case if map function emits at least one record for them.
+
+.. versionchanged:: 0.11.0 added ``include_docs`` parameter
+.. versionchanged:: 1.2.0 added ``view`` parameter and special value `_view`
+   for ``filter`` one
+.. versionchanged:: 1.3.0 ``since`` parameter could take `now` value to start
+   listen changes since current seq number.
+.. versionchanged:: 1.3.0 ``eventsource`` feed type added.
 
-  * **Argument**: feed
 
-    * **Description**: Type of the :ref:`changes <changes>` feed
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**: normal
-    * **Supported Values**:
-
-      * **continuous**: :ref:`Continuous <changes/continuous>` mode
-      * **eventsource**: :ref:`Event source <changes/eventsource>` mode
-      * **longpoll**: :ref:`Long polling <changes/longpoll>` mode
-      * **normal**: :ref:`Normal <changes/normal>` mode
-
-  * **Argument**: filter
+.. _changes:
 
-    * **Description**:  Filter function from a design document to get updates
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**: none
-    * **Supported Values**:
+Changes Feeds
+=============
 
-  * **Argument**: heartbeat
+.. _changes/normal:
 
-    * **Description**:  Period after which an empty line is sent during longpoll
-      or continuous
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 60000
-    * **Quantity**: milliseconds
+Polling
+-------
 
-  * **Argument**: include_docs
+By default all changes are immediately returned as a JSON object::
 
-    * **Description**:  Include the document with the result
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
+    GET /somedatabase/_changes HTTP/1.1
 
-  * **Argument**: limit
+.. code-block:: javascript
 
-    * **Description**:  Maximum number of rows rows to return
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: none
+    {"results":[
+    {"seq":1,"id":"fresh","changes":[{"rev":"1-967a00dff5e02add41819138abb3284d"}]},
+    {"seq":3,"id":"updated","changes":[{"rev":"2-7051cbe5c8faecd085a3fa619e6e6337"}]},
+    {"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
+    ],
+    "last_seq":5}
 
-  * **Argument**: since
+``results`` is the list of changes in sequential order. New and changed
+documents only differ in the value of the rev; deleted documents include the
+``"deleted": true`` attribute. (In the ``style=all_docs mode``, deleted applies
+only to the current/winning revision. The other revisions listed might be
+deleted even if there is no deleted property; you have to ``GET`` them
+individually to make sure.)
 
-    * **Description**:  Start the results from changes immediately after the
-      specified sequence number
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 0
+``last_seq`` is the sequence number of the last update returned. (Currently it
+will always be the same as the seq of the last item in results.)
 
-Obtains a list of the changes made to the database. This can be used to
-monitor for update and modifications to the database for post processing
-or synchronization.
+Sending a ``since`` param in the query string skips all changes up to and
+including the given sequence number::
 
-.. seealso::
+    GET /somedatabase/_changes?since=3 HTTP/1.1
 
-   :ref:`Detailed description of available changes feed types <changes>`
 
 The return structure for ``normal`` and ``longpoll`` modes is a JSON
 array of changes objects, and the last update sequence number. The
@@ -112,14 +166,134 @@ structure is described in the following table.
 
 The return format for ``continuous`` mode the server sends a ``CRLF``
 (carriage-return, linefeed) delimited line for each change. Each line
-contains the `JSON object`_.
+contains the `JSON object` described above.
 
 You can also request the full contents of each document change (instead
-of just the change notification) by using the ``include_docs``
+of just the change notification) by using the ``include_docs`` parameter.
+
+.. code-block:: javascript
+
+    {"results":[
+    {"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
+    ],
+    "last_seq":5} 
+
+
+.. _changes/longpoll:
+
+Long Polling
+------------
+
+With long polling the request to the server will remain open until a
+change is made on the database, when the changes will be reported,
+and then the connection will close. The long poll is useful when you
+want to monitor for changes for a specific purpose without wanting to
+monitoring continuously for changes.
+
+The `longpoll` feed (probably most useful used from a browser) is a more
+efficient form of polling that waits for a change to occur before the response
+is sent. `longpoll` avoids the need to frequently poll CouchDB to discover
+nothing has changed!
+
+The response is basically the same JSON as is sent for the `normal` feed.
+
+Because the wait for a change can be significant you can set a
+timeout before the connection is automatically closed (the
+``timeout`` argument). You can also set a heartbeat interval (using
+the ``heartbeat`` query argument), which sends a newline to keep the
+connection open.
+
+
+.. _changes/continuous:
+
+Continuous
+----------
+
+Polling the CouchDB server is not a good thing to do. Setting up new HTTP
+connections just to tell the client that nothing happened puts unnecessary
+strain on CouchDB.
+
+A continuous feed stays open and connected to the database until explicitly
+closed and changes are sent to the client as they happen, i.e. in near
+real-time.
+
+As with the `longpoll` feed type you can set both the timeout and heartbeat
+intervals to ensure that the connection is kept open for new changes
+and updates.
+
+The continuous feed's response is a little different than the other feed types
+to simplify the job of the client - each line of the response is either empty
+or a JSON object representing a single change, as found in the normal feed's
+results.
+
+.. code-block:: text
+
+    GET /somedatabase/_changes?feed=continuous HTTP/1.1
+
+.. code-block:: javascript
+
+    {"seq":1,"id":"fresh","changes":[{"rev":"1-967a00dff5e02add41819138abb3284d"}]}
+    {"seq":3,"id":"updated","changes":[{"rev":"2-7051cbe5c8faecd085a3fa619e6e6337"}]}
+    {"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
+    ... tum tee tum ...
+    {"seq":6,"id":"updated","changes":[{"rev":"3-825cb35de44c433bfb2df415563a19de"}]}
+
+Obviously, `... tum tee tum ...` does not appear in the actual response, but
+represents a long pause before the change with seq 6 occurred.  
+
+.. _section in the book: http://books.couchdb.org/relax/reference/change-notifications
+
+
+.. _changes/eventsource:
+
+Event Source
+------------
+
+The `eventsource` feed provides push notifications that can be consumed in
+the form of DOM events in the browser. Refer to the `W3C eventsource
+specification`_ for further details. CouchDB also honors the ``Last-Event-ID``
+header, and if it's present it will take precedence over the ``since`` query
 parameter.
 
+.. code-block:: text
+
+    GET /somedatabase/_changes?feed=eventsource HTTP/1.1
+
+.. code-block:: javascript
+
+    // define the event handling function
+    if (window.EventSource) {
+
+      var source = new EventSource("/somedatabase/_changes?feed=eventsource");
+      source.onerror = function(e) {
+        alert('EventSource failed.');
+      };
+
+      var results = [];
+      var sourceListener = function(e) {
+        var data = JSON.parse(e.data);
+        results.push(data);
+      };
+
+      // start listening for events
+      source.addEventListener('message', sourceListener, false);
+
+      // stop listening for events
+      source.removeEventListener('message', sourceListener, false);
+
+    }
+
+.. note::
+
+   EventSource connections are subject to cross-origin resource sharing
+   restrictions. You might need to use the experimental :ref:`CORS support
+   <cors>` to get the EventSource to work in your application.
+
+.. _W3C eventsource specification: http://www.w3.org/TR/eventsource/
+
+
 Filtering
----------
+=========
 
 You can filter the contents of the changes feed in a number of ways. The
 most basic way is to specify one or more document IDs to the query. This
@@ -140,5 +314,4 @@ filter name. For example:
 The ``_changes`` feed can be used to watch changes to specific document
 ID's or the list of ``_design`` documents in a database. If the
 ``filters`` parameter is set to ``_doc_ids`` a list of doc IDs can be
-passed in the ``doc_ids`` parameter as a JSON array. For more
-information, see :ref:`changes`.
+passed in the ``doc_ids`` parameter as a JSON array.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/8f4db910/share/doc/src/changes.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/changes.rst b/share/doc/src/changes.rst
deleted file mode 100644
index 55f561f..0000000
--- a/share/doc/src/changes.rst
+++ /dev/null
@@ -1,250 +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.
-
-.. _changes:
-
-============
-Changes Feed
-============
-
-.. _changes/normal:
-
-Polling
-=======
-
-A list of changes made to documents in the database, in the order they were
-made, can be obtained from the database's ``_changes`` resource. You can query
-the ``_changes`` resource by issuing a ``GET`` request with the following
-(optional) parameters:
-
-+--------------+----------------------------------------------+---------------+--------------+
-| Parameter    | Value                                        | Default Value |  Notes       |
-+==============+==============================================+===============+==============+
-| since        | seqnum / now                                 | 0             | \(1)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| limit        | maxsequences                                 | none          | \(2)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| descending   | boolean                                      | false         | \(3)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| feed         | normal / longpoll / continuous / eventsource | normal        | \(4)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| heartbeat    | milliseconds                                 | 60000         | \(5)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| timeout      | milliseconds                                 | 60000         | \(6)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| filter       | designdoc/filtername / _view                 | none          | \(7)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| include_docs | boolean                                      | false         | \(8)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| style        | all_docs / main_only                         | main_only     | \(9)         |
-+--------------+----------------------------------------------+---------------+--------------+
-| view         | designdoc/filtername                         | none          | \(10)        |
-+--------------+----------------------------------------------+---------------+--------------+
-
-Notes:
-
-(1) Start the results from the change immediately after the given sequence
-    number.
-
-(2) Limit number of result rows to the specified value (note that using 0 here
-    has the same effect as 1).
-
-(3) Return the change results in descending sequence order (most recent change
-    first)
-
-(4) Select the type of feed.
-
-(5) Period in milliseconds after which an empty line is sent in the results.
-    Only applicable for `longpoll` or `continuous` feeds. Overrides any timeout
-    to keep the feed alive indefinitely.
-
-(6) Maximum period in milliseconds to wait for a change before the response is
-    sent, even if there are no results. Only applicable for `longpoll` or
-    `continuous` feeds. Note that 60000 is also the default maximum timeout to
-    prevent undetected dead connections.
-
-    You can change the default maximum timeout in your ini-configuration:
-
-    .. code-block:: ini
-
-        [httpd]
-        changes_timeout=#millisecs
-
-(7) Reference to a :ref:`filter function <filterfun>` from a design document
-    that will filter whole stream emitting only filtered events.
-    See the `section in the book`_ for more information.
-
-(8) Include the associated document with each result. If there are conflicts,
-    only the winning revision is returned.
-
-(9) Specifies how many revisions are returned in the changes array.
-    The default, `main_only`, will only return the current "winning" revision;
-    `all_docs` will return all leaf revisions (including conflicts and deleted
-    former conflicts.)
-
-(10) Allows to use view functions as filters. It requires to set ``filter``
-     special value `_view` to enable this feature. Documents counted as "passed"
-     for view filter in case if map function emits at least one record for them.
-
-.. versionchanged:: 0.11.0 added ``include_docs`` parameter
-.. versionchanged:: 1.2.0 added ``view`` parameter and special value `_view`
-   for ``filter`` one
-.. versionchanged:: 1.3.0 ``since`` parameter could take `now` value to start
-   listen changes since current seq number.
-.. versionchanged:: 1.3.0 ``eventsource`` feed type added.
-
-By default all changes are immediately returned as a JSON object::
-
-    GET /somedatabase/_changes HTTP/1.1
-
-.. code-block:: javascript
-
-    {"results":[
-    {"seq":1,"id":"fresh","changes":[{"rev":"1-967a00dff5e02add41819138abb3284d"}]},
-    {"seq":3,"id":"updated","changes":[{"rev":"2-7051cbe5c8faecd085a3fa619e6e6337"}]},
-    {"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
-    ],
-    "last_seq":5}
-
-``results`` is the list of changes in sequential order. New and changed
-documents only differ in the value of the rev; deleted documents include the
-``"deleted": true`` attribute. (In the ``style=all_docs mode``, deleted applies
-only to the current/winning revision. The other revisions listed might be
-deleted even if there is no deleted property; you have to ``GET`` them
-individually to make sure.)
-
-``last_seq`` is the sequence number of the last update returned. (Currently it
-will always be the same as the seq of the last item in results.)
-
-Sending a ``since`` param in the query string skips all changes up to and
-including the given sequence number::
-
-    GET /somedatabase/_changes?since=3 HTTP/1.1
-
-.. code-block:: javascript
-
-    {"results":[
-    {"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
-    ],
-    "last_seq":5} 
-
-
-.. _changes/longpoll:
-
-Long Polling
-============
-
-With long polling the request to the server will remain open until a
-change is made on the database, when the changes will be reported,
-and then the connection will close. The long poll is useful when you
-want to monitor for changes for a specific purpose without wanting to
-monitoring continuously for changes.
-
-The `longpoll` feed (probably most useful used from a browser) is a more
-efficient form of polling that waits for a change to occur before the response
-is sent. `longpoll` avoids the need to frequently poll CouchDB to discover
-nothing has changed!
-
-The response is basically the same JSON as is sent for the `normal` feed.
-
-Because the wait for a change can be significant you can set a
-timeout before the connection is automatically closed (the
-``timeout`` argument). You can also set a heartbeat interval (using
-the ``heartbeat`` query argument), which sends a newline to keep the
-connection open.
-
-
-.. _changes/continuous:
-
-Continuous
-==========
-
-Polling the CouchDB server is not a good thing to do. Setting up new HTTP
-connections just to tell the client that nothing happened puts unnecessary
-strain on CouchDB.
-
-A continuous feed stays open and connected to the database until explicitly
-closed and changes are sent to the client as they happen, i.e. in near
-real-time.
-
-As with the `longpoll` feed type you can set both the timeout and heartbeat
-intervals to ensure that the connection is kept open for new changes
-and updates.
-
-The continuous feed's response is a little different than the other feed types
-to simplify the job of the client - each line of the response is either empty
-or a JSON object representing a single change, as found in the normal feed's
-results.
-
-.. code-block:: text
-
-    GET /somedatabase/_changes?feed=continuous HTTP/1.1
-
-.. code-block:: javascript
-
-    {"seq":1,"id":"fresh","changes":[{"rev":"1-967a00dff5e02add41819138abb3284d"}]}
-    {"seq":3,"id":"updated","changes":[{"rev":"2-7051cbe5c8faecd085a3fa619e6e6337"}]}
-    {"seq":5,"id":"deleted","changes":[{"rev":"2-eec205a9d413992850a6e32678485900"}],"deleted":true}
-    ... tum tee tum ...
-    {"seq":6,"id":"updated","changes":[{"rev":"3-825cb35de44c433bfb2df415563a19de"}]}
-
-Obviously, `... tum tee tum ...` does not appear in the actual response, but
-represents a long pause before the change with seq 6 occurred.  
-
-.. _section in the book: http://books.couchdb.org/relax/reference/change-notifications
-
-
-.. _changes/eventsource:
-
-Event Source
-============
-
-The `eventsource` feed provides push notifications that can be consumed in
-the form of DOM events in the browser. Refer to the `W3C eventsource
-specification`_ for further details. CouchDB honors the ``Last-Event-ID`` header,
-and if it's present it will take precedence over the ``since`` query parameter.
-
-.. code-block:: text
-
-    GET /somedatabase/_changes?feed=eventsource HTTP/1.1
-
-.. code-block:: javascript
-
-    // define the event handling function
-    if (window.EventSource) {
-
-      var source = new EventSource("/somedatabase/_changes?feed=eventsource");
-      source.onerror = function(e) {
-        alert('EventSource failed.');
-      };
-      
-      var results = [];
-      var sourceListener = function(e) {
-        var data = JSON.parse(e.data);
-        results.push(data);
-      };
-
-      // start listening for events
-      source.addEventListener('message', sourceListener, false);
-      
-      // stop listening for events
-      source.removeEventListener('message', sourceListener, false);
-      
-    }
-
-.. note::
-
-   EventSource connections are subject to cross-origin resource sharing
-   restrictions. You might need to use the experimental :ref:`CORS support
-   <cors>` to get the EventSource to work in your application.
-
-.. _W3C eventsource specification: http://www.w3.org/TR/eventsource/

http://git-wip-us.apache.org/repos/asf/couchdb/blob/8f4db910/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index 2fcdb00..b6fca04 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -32,7 +32,6 @@ Contents
     replication/index
     ddocs
     query-server/index
-    changes
     api/index
     json-structure
     contributing


[17/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Describe global, database and design document http handlers.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/f38fab0d
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/f38fab0d
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/f38fab0d

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: f38fab0d01d18815f9585bbd9f696e7db0961a22
Parents: d6f745d
Author: Alexander Shorin <kx...@apache.org>
Authored: Mon Jul 22 10:00:52 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am            |   3 +
 share/doc/src/config/http-handlers.rst | 340 ++++++++++++++++++++++++++++
 share/doc/src/config/index.rst         |   1 +
 3 files changed, 344 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/f38fab0d/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 3302c7f..743cd4f 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -58,6 +58,7 @@ html_files = \
     html/_sources/config/couchdb.txt \
     html/_sources/config/externals.txt \
     html/_sources/config/http.txt \
+    html/_sources/config/http-handlers.txt \
     html/_sources/config/index.txt \
     html/_sources/config/logging.txt \
     html/_sources/config/misc.txt \
@@ -113,6 +114,7 @@ html_files = \
     html/config/couchdb.html \
     html/config/externals.html \
     html/config/http.html \
+    html/config/http-handlers.html \
     html/config/index.html \
     html/config/logging.html \
     html/config/misc.html \
@@ -166,6 +168,7 @@ src_files = \
     ../src/config/couchdb.rst \
     ../src/config/externals.rst \
     ../src/config/http.rst \
+    ../src/config/http-handlers.rst \
     ../src/config/index.rst \
     ../src/config/logging.rst \
     ../src/config/misc.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/f38fab0d/share/doc/src/config/http-handlers.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/http-handlers.rst b/share/doc/src/config/http-handlers.rst
new file mode 100644
index 0000000..65ba437
--- /dev/null
+++ b/share/doc/src/config/http-handlers.rst
@@ -0,0 +1,340 @@
+.. 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.
+
+.. highlight:: ini
+
+======================
+HTTP Resource Handlers
+======================
+
+.. _config/httpd_global_handlers:
+
+``[httpd_global_handlers]`` :: Global HTTP Handlers
+===================================================
+
+These HTTP resources are provided for CouchDB server root level.
+
+.. _config/httpd_global_handlers/root:
+
+:ref:`/ <api/misc/root>`
+------------------------
+
+::
+
+  [httpd_global_handlers]
+  / = {couch_httpd_misc_handlers, handle_welcome_req, <<"Welcome">>}
+
+
+.. _config/httpd_global_handlers/favicon.ico:
+
+:ref:`favicon.ico <api/misc/favicon>`
+-------------------------------------
+
+The favicon handler looks for `favicon.ico` file within specified directory::
+
+  [httpd_global_handlers]
+  favicon.ico = {couch_httpd_misc_handlers, handle_favicon_req, "/usr/share/couchdb/www"}
+
+
+.. _config/httpd_global_handlers/_active_tasks:
+
+:ref:`_active_tasks <api/misc/active_tasks>`
+--------------------------------------------
+
+::
+
+  [httpd_global_handlers]
+  _active_tasks = {couch_httpd_misc_handlers, handle_task_status_req}
+
+
+.. _config/httpd_global_handlers/_all_dbs:
+
+:ref:`_all_dbs <api/misc/all_dbs>`
+----------------------------------
+
+Provides list of all server's databases::
+
+  [httpd_global_handlers]
+  _all_dbs = {couch_httpd_misc_handlers, handle_all_dbs_req}
+
+.. note::
+
+   Sometimes you don't want to disclose database names for everyone, but you
+   also don't like/want/able to setup any proxies in front of CouchDB. Removing
+   this handler disables ``_all_dbs`` resource and there will be no way to get
+   list of available databases.
+
+   Same also is true for other resource handlers.
+
+
+.. _config/httpd_global_handlers/_config:
+
+:ref:`_config <api/config>`
+---------------------------
+
+Provides resource to work with CouchDB config :ref:`remotely <api/config>`.
+Any config changes that was made via HTTP API are applied automatically on fly
+and doesn't requires server instance to be restarted::
+
+  [httpd_global_handlers]
+  _config = {couch_httpd_misc_handlers, handle_config_req}
+
+
+.. _config/httpd_global_handlers/_log:
+
+:ref:`_log <api/misc/log>`
+--------------------------
+
+::
+
+  [httpd_global_handlers]
+  _log = {couch_httpd_misc_handlers, handle_log_req}
+
+
+.. _config/httpd_global_handlers/_oauth:
+
+``_oauth``
+----------
+
+::
+
+  [httpd_global_handlers]
+  _oauth = {couch_httpd_oauth, handle_oauth_req}
+
+
+.. _config/httpd_global_handlers/_replicate:
+
+:ref:`_replicate <api/misc/replicate>`
+--------------------------------------
+
+Provides API to run :ref:`temporary replications <api/misc/replicate>`::
+
+  [httpd_global_handlers]
+  _replicate = {couch_replicator_httpd, handle_req}
+
+
+.. _config/httpd_global_handlers/_restart:
+
+:ref:`_restart <api/misc/restart>`
+----------------------------------
+
+::
+
+  [httpd_global_handlers]
+  _restart = {couch_httpd_misc_handlers, handle_restart_req}
+
+
+.. _config/httpd_global_handlers/_session:
+
+``_session``
+------------
+
+Provides resource with information about current user's session::
+
+  [httpd_global_handlers]
+  _session = {couch_httpd_auth, handle_session_req}
+
+
+.. _config/httpd_global_handlers/_stats:
+
+:ref:`_stats <api/misc/stats>`
+------------------------------
+
+::
+
+  [httpd_global_handlers]
+  _stats = {couch_httpd_stats_handlers, handle_stats_req}
+
+
+.. _config/httpd_global_handlers/_utils:
+
+:ref:`_utils <api/misc/utils>`
+------------------------------
+
+The :ref:`_utils <api/misc/utils>` handler serves `Futon`'s web administration
+page::
+
+  [httpd_global_handlers]
+  _utils = {couch_httpd_misc_handlers, handle_utils_dir_req, "/usr/share/couchdb/www"}
+
+In similar way, you may setup custom handler to let CouchDB serve on disk static
+files.
+
+
+.. _config/httpd_global_handlers/_uuids:
+
+:ref:`_uuids <api/misc/uuids>`
+------------------------------
+
+Provides resource to get UUIDs generated on server side::
+
+  [httpd_global_handlers]
+  _uuids = {couch_httpd_misc_handlers, handle_uuids_req}
+
+
+.. _config/httpd_db_handlers:
+
+``[httpd_db_handlers]`` :: Database HTTP Handlers
+=================================================
+
+These HTTP resources are provided for CouchDB database level in context of the
+related one.
+
+.. _config/httpd_db_handlers/_all_docs:
+
+:ref:`_all_docs <api/db/all_docs>`
+----------------------------------
+
+::
+
+  [httpd_db_handlers]
+  _all_docs = {couch_mrview_http, handle_all_docs_req}
+
+
+.. _config/httpd_db_handlers/_changes:
+
+:ref:`_changes <changes>`
+-------------------------
+
+::
+
+  [httpd_db_handlers]
+  _changes = {couch_httpd_db, handle_changes_req}
+
+
+.. _config/httpd_db_handlers/_compact:
+
+:ref:`_compact <api/db/compact>`
+--------------------------------
+
+::
+
+  [httpd_db_handlers]
+  _compact = {couch_httpd_db, handle_compact_req}
+
+
+.. _config/httpd_db_handlers/_design:
+
+:ref:`_design <api/ddoc>`
+-------------------------
+
+::
+
+  [httpd_db_handlers]
+  _design = {couch_httpd_db, handle_design_req}
+
+
+.. _config/httpd_db_handlers/_temp_view:
+
+:ref:`_temp_view <api/db/temp_view>`
+------------------------------------
+
+::
+
+  [httpd_db_handlers]
+  _temp_view = {couch_mrview_http, handle_temp_view_req}
+
+
+.. _config/httpd_db_handlers/_view_cleanup:
+
+:ref:`_view_cleanup <api/db/view_cleanup>`
+------------------------------------------
+
+::
+
+  [httpd_db_handlers]
+  _view_cleanup = {couch_mrview_http, handle_cleanup_req}
+
+
+.. _config/httpd_design_handlers:
+
+``[httpd_design_handlers]`` :: Design Documents HTTP Handlers
+=============================================================
+
+These HTTP resources are provided for design documents.
+
+.. _config/httpd_design_handlers/_compact:
+
+:ref:`_compact <api/db/compact/ddoc>`
+-------------------------------------
+
+::
+
+  [httpd_design_handlers]
+  _compact = {couch_mrview_http, handle_compact_req}
+
+
+.. _config/httpd_design_handlers/_info:
+
+:ref:`_info <api/ddoc/info>`
+----------------------------
+
+::
+
+  [httpd_design_handlers]
+  _info = {couch_mrview_http, handle_info_req}
+
+
+.. _config/httpd_design_handlers/_list:
+
+:ref:`_list <api/ddoc/list>`
+----------------------------
+
+::
+
+  [httpd_design_handlers]
+  _list = {couch_mrview_show, handle_view_list_req}
+
+
+.. _config/httpd_design_handlers/_rewrite:
+
+:ref:`_rewrite <api/ddoc/rewrite>`
+----------------------------------
+
+::
+
+  [httpd_design_handlers]
+  _rewrite = {couch_httpd_rewrite, handle_rewrite_req}
+
+
+.. _config/httpd_design_handlers/_show:
+
+:ref:`_show <api/ddoc/show>`
+----------------------------
+
+::
+
+  [httpd_design_handlers]
+  _show = {couch_mrview_show, handle_doc_show_req}
+
+
+.. _config/httpd_design_handlers/_update:
+
+:ref:`_update <api/ddoc/update>`
+--------------------------------
+
+::
+
+  [httpd_design_handlers]
+  _update = {couch_mrview_show, handle_doc_update_req}
+
+
+.. _config/httpd_design_handlers/_view:
+
+:ref:`_view <api/ddoc/view>`
+----------------------------
+
+::
+
+  [httpd_design_handlers]
+  _view = {couch_mrview_http, handle_view_req}
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/f38fab0d/share/doc/src/config/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/index.rst b/share/doc/src/config/index.rst
index 5db70f8..a9513c2 100644
--- a/share/doc/src/config/index.rst
+++ b/share/doc/src/config/index.rst
@@ -28,6 +28,7 @@ Configuring CouchDB
    replicator
    query-servers
    externals
+   http-handlers
    services
    misc
    proxying


[42/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Describe public_fields option.

With big red warning.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/54504071
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/54504071
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/54504071

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 54504071b757daf4bd5406daa660a70d9001b5a5
Parents: ccdaffa
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 11:12:30 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 11:12:30 2013 +0400

----------------------------------------------------------------------
 share/doc/src/config/auth.rst | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/54504071/share/doc/src/config/auth.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/auth.rst b/share/doc/src/config/auth.rst
index 7cf2af9..6e3b59e 100644
--- a/share/doc/src/config/auth.rst
+++ b/share/doc/src/config/auth.rst
@@ -179,6 +179,29 @@ required for `Proxy Auth`::
   proxy_use_secret = false
 
 
+.. _config/couch_httpd_auth/public_fields:
+
+``public_fields`` :: User documents public fields
+-------------------------------------------------
+
+.. warning::
+
+   Due to :issue:`1838` issue, setting `public fields` allows list all documents
+   in the :ref:`_users <config/couch_httpd_auth/authentication_db>` database,
+   no matter does their documents contains public fields or not. If your system
+   uses email-based user login, enabling this feature may be fatal from security
+   point.
+
+Comma-separated list of field names that will be available to view for any user
+document in :ref:`authentication_db <config/couch_httpd_auth/authentication_db>`
+If unset or not specified, authenticated users may retrieve only their own docs.
+
+::
+
+  [couch_httpd_auth]
+  public_fields = first_name, last_name, contacts, url
+
+
 .. _config/couch_httpd_auth/require_valid_user:
 
 ``require_valid_user`` :: Force users authentication


[27/50] [abbrv] Split API articles into small files focused on specific problem.

Posted by kx...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/document/common.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/document/common.rst b/share/doc/src/api/document/common.rst
new file mode 100644
index 0000000..6ac9b2d
--- /dev/null
+++ b/share/doc/src/api/document/common.rst
@@ -0,0 +1,781 @@
+.. 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.
+
+
+.. _api/db.post:
+
+``POST /db``
+============
+
+* **Method**: ``POST /db``
+* **Request**: JSON of the new document
+* **Response**: JSON with the committed document information
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: batch
+
+    * **Description**:  Allow document store request to be batched with others
+    * **Optional**: yes
+    * **Type**: string
+    * **Supported Values**: asd
+    * **ok**: Enable
+
+* **Return Codes**:
+
+  * **201**:
+    Document has been created successfully
+  * **409**:
+    Conflict - a document with the specified document ID already exists
+
+Create a new document in the specified database, using the supplied JSON
+document structure. If the JSON structure includes the ``_id`` field,
+then the document will be created with the specified document ID. If the
+``_id`` field is not specified, a new unique ID will be generated.
+
+For example, you can generate a new document with a generated UUID using
+the following request:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/
+    Content-Type: application/json
+
+    {
+       "servings" : 4,
+       "subtitle" : "Delicious with fresh bread",
+       "title" : "Fish Stew"
+    }
+
+The return JSON will specify the automatically generated ID and revision
+information:
+
+.. code-block:: javascript
+
+    {
+       "id" : "64575eef70ab90a2b8d55fc09e00440d",
+       "ok" : true,
+       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
+    }
+
+Specifying the Document ID
+--------------------------
+
+The document ID can be specified by including the ``_id`` field in the
+JSON of the submitted record. The following request will create the same
+document with the ID ``FishStew``:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/
+    Content-Type: application/json
+
+    {
+       "_id" : "FishStew",
+       "servings" : 4,
+       "subtitle" : "Delicious with fresh bread",
+       "title" : "Fish Stew"
+    }
+
+The structure of the submitted document is as shown in the table below:
+
+In either case, the returned JSON will specify the document ID, revision
+ID, and status message:
+
+.. code-block:: javascript
+
+    {
+       "id" : "FishStew",
+       "ok" : true,
+       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
+    }
+
+
+UUID generation algorithms
+--------------------------
+
+CouchDB supports a number of different UUID generation algorithms for use
+in situations where a user-specified UUID does not make sense. These
+can be set simply by `PUT http://couchdb:5984/_config/uuids/algorithm`.
+
+
++---------------+---------------------+------------------------------------+
+| Algorithm     | Description         | Sample UUID                        |
++===============+=====================+====================================+
+| random        | 128 bits of pure    | - 43febce5675468a5467fb5467ce9e6c0 |
+|               | random awesomeness  |                                    |
++---------------+---------------------+------------------------------------+
+| sequential    | monotonically       | - f755c413badf66b22941313f9f001e28 |
+|               | increasing ids with | - f755c413badf66b22941313f9f0024ca |
+|               | random increments   | - f755c413badf66b22941313f9f00332c |
++---------------+---------------------+------------------------------------+
+| utc_random    | time since start of | - 04cfa405381205204f75100d0241ccc3 |
+|               | epoch, as 14 hex    | - 04cfa4059c48e76e7c054bbe033dd8db |
+|               | digits, followed by | - 04cfa405fce10b0df4c08f95e667cd2f |
+|               | 18 random digits.   |                                    |
++---------------+---------------------+------------------------------------+
+| utc_id        | time since start of | - 04cfa718b00848_i_am_in_yer_couch |
+| & additional  | epoch, as 14 hex    | - 04cfa71d377aef_i_am_in_yer_couch |
+| parameter     | digits, followed by | - 04cfa71e0deabd_i_am_in_yer_couch |
+|               | utc_id_suffix.      |                                    |
++---------------+---------------------+------------------------------------+
+
+.. note:: **Impact of UUID choices:**
+   The choice of UUID has a significant impact on the layout of the B-tree,
+   prior to compaction.
+
+   For example, a sequential UUID algorithm during uploading thousands of
+   documents, will avoid the need to rewrite many intermediate B-tree nodes.
+   A random UUID algorithm may require rewriting intermediate nodes on a regular
+   basis, with a corresponding decrease of throughput, and significant wasted
+   space due to the append-only B-tree design.
+
+   It is generally recommended to set your own UUIDs, or use the sequential
+   algorithm unless you have a specific need and take into account the likely
+   need for compaction to re-balance the B-tree and reclaim wasted space.
+
+.. _api/doc/batch-writes:
+
+Batch Mode Writes
+-----------------
+
+You can write documents to the database at a higher rate by using the
+batch option. This collects document writes together in memory (on a
+user-by-user basis) before they are committed to disk. This increases
+the risk of the documents not being stored in the event of a failure,
+since the documents are not written to disk immediately.
+
+To use the batched mode, append the ``batch=ok`` query argument to the
+URL of the ``PUT`` or ``POST`` request. The CouchDB server will respond
+with a 202 HTTP response code immediately.
+
+Including Attachments
+---------------------
+
+You can include one or more attachments with a given document by
+incorporating the attachment information within the JSON of the
+document. This provides a simpler alternative to loading documents with
+attachments than making a separate call (see :ref:`api/doc/attachment.put`).
+
+* **_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
+
+The ``filename`` will be the attachment name. For example, when sending
+the JSON structure below:
+
+.. code-block:: javascript
+
+    {
+       "_id" : "FishStew",
+       "servings" : 4,
+       "subtitle" : "Delicious with fresh bread",
+       "title" : "Fish Stew"
+       "_attachments" : {
+          "styling.css" : {
+             "content-type" : "text/css",
+             "data" : "cCB7IGZvbnQtc2l6ZTogMTJwdDsgfQo=",
+             },
+       },
+    }
+
+
+The attachment ``styling.css`` can be accessed using
+``/recipes/FishStew/styling.css``. For more information on attachments,
+see :ref:`api/doc/attachment.get`.
+
+The document data embedded in to the structure must be encoded using
+base64.
+
+.. _api/doc.get:
+
+``GET /db/doc``
+===============
+
+* **Method**: ``GET /db/doc``
+* **Request**: None
+* **Response**: Returns the JSON for the document
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: conflicts
+
+    * **Description**: Returns the conflict tree for the document.
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+    * **Supported Values**:
+
+      * **true**: Includes the revisions
+
+  * **Argument**: rev
+
+    * **Description**: Specify the revision to return
+    * **Optional**: yes
+    * **Type**: string
+    * **Supported Values**:
+
+      * **true**: Includes the revisions
+
+  * **Argument**: revs
+
+    * **Description**:  Return a list of the revisions for the document
+    * **Optional**: yes
+    * **Type**: boolean
+
+  * **Argument**: revs_info
+
+    * **Description**: Return a list of detailed revision information for the
+      document
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Supported Values**:
+
+      * **true**: Includes the revisions
+
+* **Return Codes**:
+
+  * **200**:
+    Document retrieved
+  * **400**:
+    The format of the request or revision was invalid
+  * **404**:
+    The specified document or revision cannot be found, or has been deleted
+  * **409**:
+    Conflict - a document with the specified document ID already exists
+
+Returns the specified ``doc`` from the specified ``db``. For example, to
+retrieve the document with the id ``FishStew`` you would send the
+following request:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/FishStew
+    Content-Type: application/json
+    Accept: application/json
+
+The returned JSON is the JSON of the document, including the document ID
+and revision number:
+
+.. code-block:: javascript
+
+    {
+       "_id" : "FishStew",
+       "_rev" : "3-a1a9b39ee3cc39181b796a69cb48521c",
+       "servings" : 4,
+       "subtitle" : "Delicious with a green salad",
+       "title" : "Irish Fish Stew"
+    }
+
+
+Unless you request a specific revision, the latest revision of the
+document will always be returned.
+
+Attachments
+-----------
+
+If the document includes attachments, then the returned structure will
+contain a summary of the attachments associated with the document, but
+not the attachment data itself.
+
+The JSON for the returned document will include the ``_attachments``
+field, with one or more attachment definitions. For example:
+
+.. code-block:: javascript
+
+    {
+       "_id" : "FishStew",
+       "servings" : 4,
+       "subtitle" : "Delicious with fresh bread",
+       "title" : "Fish Stew"
+       "_attachments" : {
+          "styling.css" : {
+             "stub" : true,
+             "content-type" : "text/css",
+             "length" : 783426,
+             },
+       },
+    }
+
+The format of the returned JSON is shown in the table below:
+
+* **_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
+    * **length**: Length (bytes) of the attachment data
+    * **revpos**: Revision where this attachment exists
+    * **stub**: Indicates whether the attachment is a stub
+
+Getting a List of Revisions
+---------------------------
+
+You can obtain a list of the revisions for a given document by adding
+the ``revs=true`` parameter to the request URL. For example:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/FishStew?revs=true
+    Accept: application/json
+
+The returned JSON structure includes the original document, including a
+``_revisions`` structure that includes the revision information:
+
+.. code-block:: javascript
+
+    {
+       "servings" : 4,
+       "subtitle" : "Delicious with a green salad",
+       "_id" : "FishStew",
+       "title" : "Irish Fish Stew",
+       "_revisions" : {
+          "ids" : [
+             "a1a9b39ee3cc39181b796a69cb48521c",
+             "7c4740b4dcf26683e941d6641c00c39d",
+             "9c65296036141e575d32ba9c034dd3ee"
+          ],
+          "start" : 3
+       },
+       "_rev" : "3-a1a9b39ee3cc39181b796a69cb48521c"
+    }
+
+* **_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
+
+Obtaining an Extended Revision History
+--------------------------------------
+
+You can get additional information about the revisions for a given
+document by supplying the ``revs_info`` argument to the query:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/FishStew?revs_info=true
+    Accept: application/json
+
+This returns extended revision information, including the availability
+and status of each revision:
+
+.. code-block:: javascript
+
+    {
+       "servings" : 4,
+       "subtitle" : "Delicious with a green salad",
+       "_id" : "FishStew",
+       "_revs_info" : [
+          {
+             "status" : "available",
+             "rev" : "3-a1a9b39ee3cc39181b796a69cb48521c"
+          },
+          {
+             "status" : "available",
+             "rev" : "2-7c4740b4dcf26683e941d6641c00c39d"
+          },
+          {
+             "status" : "available",
+             "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
+          }
+       ],
+       "title" : "Irish Fish Stew",
+       "_rev" : "3-a1a9b39ee3cc39181b796a69cb48521c"
+    }
+
+* **_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
+
+Obtaining a Specific Revision
+-----------------------------
+
+To get a specific revision, use the ``rev`` argument to the request, and
+specify the full revision number:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/FishStew?rev=2-7c4740b4dcf26683e941d6641c00c39d
+    Accept: application/json
+
+The specified revision of the document will be returned, including a
+``_rev`` field specifying the revision that was requested:
+
+.. code-block:: javascript
+
+    {
+       "_id" : "FishStew",
+       "_rev" : "2-7c4740b4dcf26683e941d6641c00c39d",
+       "servings" : 4,
+       "subtitle" : "Delicious with a green salad",
+       "title" : "Fish Stew"
+    }
+
+.. _api/doc.head:
+
+``HEAD /db/doc``
+================
+
+* **Method**: ``HEAD /db/doc``
+* **Request**: None
+* **Response**: None
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Specify the revision to return
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: revs
+
+    * **Description**:  Return a list of the revisions for the document
+    * **Optional**: yes
+    * **Type**: boolean
+
+  * **Argument**: revs_info
+
+    * **Description**:  Return a list of detailed revision information for the
+      document
+    * **Optional**: yes
+    * **Type**: boolean
+
+* **Return Codes**:
+
+  * **404**:
+    The specified document or revision cannot be found, or has been deleted
+
+Returns the HTTP Headers containing a minimal amount of information
+about the specified document. The method supports the same query
+arguments as the ``GET`` method, but only the header information
+(including document size, and the revision as an ETag), is returned. For
+example, a simple ``HEAD`` request:
+
+.. code-block:: http
+
+    HEAD http://couchdb:5984/recipes/FishStew
+    Content-Type: application/json
+
+
+Returns the following HTTP Headers:
+
+.. code-block:: javascript
+
+    HTTP/1.1 200 OK
+    Server: CouchDB/1.0.1 (Erlang OTP/R13B)
+    Etag: "7-a19a1a5ecd946dad70e85233ba039ab2"
+    Date: Fri, 05 Nov 2010 14:54:43 GMT
+    Content-Type: text/plain;charset=utf-8
+    Content-Length: 136
+    Cache-Control: must-revalidate
+
+The ``Etag`` header shows the current revision for the requested
+document, and the ``Content-Length`` specifies the length of the data,
+if the document were requested in full.
+
+Adding any of the query arguments (as supported by ```GET```_ method),
+then the resulting HTTP Headers will correspond to what would be
+returned. Note that the current revision is not returned when the
+``refs_info`` argument is used. For example:
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Server: CouchDB/1.0.1 (Erlang OTP/R13B)
+    Date: Fri, 05 Nov 2010 14:57:16 GMT
+    Content-Type: text/plain;charset=utf-8
+    Content-Length: 609
+    Cache-Control: must-revalidate
+
+.. _api/doc.put:
+
+``PUT /db/doc``
+===============
+
+* **Method**: ``PUT /db/doc``
+* **Request**: JSON of the new document, or updated version of the existed
+  document
+* **Response**: JSON of the document ID and revision
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: batch
+
+    * **Description**:  Allow document store request to be batched with others
+    * **Optional**: yes
+    * **Type**: string
+    * **Supported Values**:
+
+      * **ok**: Enable
+
+* **HTTP Headers**
+
+  * **Header**: ``If-Match``
+
+    * **Description**: Current revision of the document for validation
+    * **Optional**: yes
+
+* **Return Codes**:
+
+  * **201**:
+    Document has been created successfully
+  * **202**:
+    Document accepted for writing (batch mode)
+
+
+The ``PUT`` method creates a new named document, or creates a new
+revision of the existing document. Unlike the ``POST`` method, you
+must specify the document ID in the request URL.
+
+For example, to create the document ``FishStew``, you would send the
+following request:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/FishStew
+    Content-Type: application/json
+
+    {
+      "servings" : 4,
+      "subtitle" : "Delicious with fresh bread",
+      "title" : "Fish Stew"
+    }
+
+The return type is JSON of the status, document ID,and revision number:
+
+.. code-block:: javascript
+
+    {
+       "id" : "FishStew",
+       "ok" : true,
+       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
+    }
+
+Updating an Existing Document
+-----------------------------
+
+To update an existing document you must specify the current revision
+number within the ``_rev`` parameter. For example:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/FishStew
+    Content-Type: application/json
+
+    {
+      "_rev" : "1-9c65296036141e575d32ba9c034dd3ee",
+      "servings" : 4,
+      "subtitle" : "Delicious with fresh salad",
+      "title" : "Fish Stew"
+    }
+
+Alternatively, you can supply the current revision number in the
+``If-Match`` HTTP header of the request. For example:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/FishStew
+    If-Match: 2-d953b18035b76f2a5b1d1d93f25d3aea
+    Content-Type: application/json
+
+    {
+       "servings" : 4,
+       "subtitle" : "Delicious with fresh salad",
+       "title" : "Fish Stew"
+    }
+
+The JSON returned will include the updated revision number:
+
+.. code-block:: javascript
+
+    {
+       "id" : "FishStew99",
+       "ok" : true,
+       "rev" : "2-d953b18035b76f2a5b1d1d93f25d3aea"
+    }
+
+For information on batched writes, which can provide improved
+performance, see :ref:`api/doc/batch-writes`.
+
+.. _api/doc.delete:
+
+``DELETE /db/doc``
+==================
+
+* **Method**: ``DELETE /db/doc``
+* **Request**: None
+* **Response**: JSON of the deleted revision
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Current revision of the document for validation
+    * **Optional**: yes
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``If-Match``
+
+    * **Description**: Current revision of the document for validation
+    * **Optional**: yes
+
+* **Return Codes**:
+
+  * **409**:
+    Revision is missing, invalid or not the latest
+
+Deletes the specified document from the database. You must supply the
+current (latest) revision, either by using the ``rev`` parameter to
+specify the revision:
+
+.. code-block:: http
+
+    DELETE http://couchdb:5984/recipes/FishStew?rev=3-a1a9b39ee3cc39181b796a69cb48521c
+    Content-Type: application/json
+
+Alternatively, you can use ETags with the ``If-Match`` field:
+
+.. code-block:: http
+
+    DELETE http://couchdb:5984/recipes/FishStew
+    If-Match: 3-a1a9b39ee3cc39181b796a69cb48521c
+    Content-Type: application/json
+
+
+The returned JSON contains the document ID, revision and status:
+
+.. code-block:: javascript
+
+    {
+       "id" : "FishStew",
+       "ok" : true,
+       "rev" : "4-2719fd41187c60762ff584761b714cfb"
+    }
+
+.. note:: Note that deletion of a record increments the revision number. The
+   use of a revision for deletion of the record allows replication of
+   the database to correctly track the deletion in synchronized copies.
+
+.. _api/doc.copy:
+
+``COPY /db/doc``
+================
+
+* **Method**: ``COPY /db/doc``
+* **Request**: None
+* **Response**: JSON of the new document and revision
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Revision to copy from
+    * **Optional**: yes
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``Destination``
+
+    * **Description**: Destination document (and optional revision)
+    * **Optional**: no
+
+* **Return Codes**:
+
+  * **201**:
+    Document has been copied and created successfully
+  * **409**:
+    Revision is missing, invalid or not the latest
+
+The ``COPY`` command (which is non-standard HTTP) copies an existing
+document to a new or existing document.
+
+The source document is specified on the request line, with the
+``Destination`` HTTP Header of the request specifying the target
+document.
+
+Copying a Document
+------------------
+
+You can copy the latest version of a document to a new document by
+specifying the current document and target document:
+
+.. code-block:: http
+
+    COPY http://couchdb:5984/recipes/FishStew
+    Content-Type: application/json
+    Destination: IrishFishStew
+
+The above request copies the document ``FishStew`` to the new document
+``IrishFishStew``. The response is the ID and revision of the new
+document.
+
+.. code-block:: javascript
+
+    {
+       "id" : "IrishFishStew",
+       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
+    }
+
+Copying from a Specific Revision
+--------------------------------
+
+To copy *from* a specific version, use the ``rev`` argument to the query
+string:
+
+.. code-block:: http
+
+    COPY http://couchdb:5984/recipes/FishStew?rev=5-acfd32d233f07cea4b4f37daaacc0082
+    Content-Type: application/json
+    Destination: IrishFishStew
+
+The new document will be created using the information in the specified
+revision of the source document.
+
+Copying to an Existing Document
+-------------------------------
+
+To copy to an existing document, you must specify the current revision
+string for the target document, using the ``rev`` parameter to the
+``Destination`` HTTP Header string. For example:
+
+.. code-block:: http
+
+    COPY http://couchdb:5984/recipes/FishStew
+    Content-Type: application/json
+    Destination: IrishFishStew?rev=1-9c65296036141e575d32ba9c034dd3ee
+
+The return value will be the new revision of the copied document:
+
+.. code-block:: javascript
+
+    {
+       "id" : "IrishFishStew",
+       "rev" : "2-55b6a1b251902a2c249b667dab1c6692"
+    }
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/document/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/document/index.rst b/share/doc/src/api/document/index.rst
new file mode 100644
index 0000000..d471b90
--- /dev/null
+++ b/share/doc/src/api/document/index.rst
@@ -0,0 +1,53 @@
+.. 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.
+
+.. _api/doc:
+
+================
+Document Methods
+================
+
+The CouchDB API Server Document methods detail how to create, read,
+update and delete documents within a database.
+
+A list of the available methods and URL paths are provided below:
+
++--------+-------------------------+-------------------------------------------+
+| Method | Path                    | Description                               |
++========+=========================+===========================================+
+| POST   | /db                     | Create a new document                     |
++--------+-------------------------+-------------------------------------------+
+| GET    | /db/doc                 | Returns the latest revision of the        |
+|        |                         | document                                  |
++--------+-------------------------+-------------------------------------------+
+| HEAD   | /db/doc                 | Returns bare information in the HTTP      |
+|        |                         | Headers for the document                  |
++--------+-------------------------+-------------------------------------------+
+| PUT    | /db/doc                 | Inserts a new document, or new version    |
+|        |                         | of an existing document                   |
++--------+-------------------------+-------------------------------------------+
+| DELETE | /db/doc                 | Deletes the document                      |
++--------+-------------------------+-------------------------------------------+
+| COPY   | /db/doc                 | Copies the document                       |
++--------+-------------------------+-------------------------------------------+
+| GET    | /db/doc/attachment      | Gets the attachment of a document         |
++--------+-------------------------+-------------------------------------------+
+| PUT    | /db/doc/attachment      | Adds an attachment of a document          |
++--------+-------------------------+-------------------------------------------+
+| DELETE | /db/doc/attachment      | Deletes an attachment of a document       |
++--------+-------------------------+-------------------------------------------+
+
+
+.. toctree::
+
+   common
+   attachments

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/documents.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/documents.rst b/share/doc/src/api/documents.rst
deleted file mode 100644
index a1ca0ab..0000000
--- a/share/doc/src/api/documents.rst
+++ /dev/null
@@ -1,1045 +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.
-
-.. _api/doc:
-
-================
-Document Methods
-================
-
-The CouchDB API Server Document methods detail how to create, read,
-update and delete documents within a database.
-
-A list of the available methods and URL paths are provided below:
-
-+--------+-------------------------+-------------------------------------------+
-| Method | Path                    | Description                               |
-+========+=========================+===========================================+
-| POST   | /db                     | Create a new document                     |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /db/doc                 | Returns the latest revision of the        |
-|        |                         | document                                  |
-+--------+-------------------------+-------------------------------------------+
-| HEAD   | /db/doc                 | Returns bare information in the HTTP      |
-|        |                         | Headers for the document                  |
-+--------+-------------------------+-------------------------------------------+
-| PUT    | /db/doc                 | Inserts a new document, or new version    |
-|        |                         | of an existing document                   |
-+--------+-------------------------+-------------------------------------------+
-| DELETE | /db/doc                 | Deletes the document                      |
-+--------+-------------------------+-------------------------------------------+
-| COPY   | /db/doc                 | Copies the document                       |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /db/doc/attachment      | Gets the attachment of a document         |
-+--------+-------------------------+-------------------------------------------+
-| PUT    | /db/doc/attachment      | Adds an attachment of a document          |
-+--------+-------------------------+-------------------------------------------+
-| DELETE | /db/doc/attachment      | Deletes an attachment of a document       |
-+--------+-------------------------+-------------------------------------------+
-
-.. _api/db.post:
-
-``POST /db``
-============
-
-* **Method**: ``POST /db``
-* **Request**: JSON of the new document
-* **Response**: JSON with the committed document information
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: batch
-
-    * **Description**:  Allow document store request to be batched with others
-    * **Optional**: yes
-    * **Type**: string
-    * **Supported Values**: asd
-    * **ok**: Enable
-
-* **Return Codes**:
-
-  * **201**:
-    Document has been created successfully
-  * **409**:
-    Conflict - a document with the specified document ID already exists
-
-Create a new document in the specified database, using the supplied JSON
-document structure. If the JSON structure includes the ``_id`` field,
-then the document will be created with the specified document ID. If the
-``_id`` field is not specified, a new unique ID will be generated.
-
-For example, you can generate a new document with a generated UUID using
-the following request:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/
-    Content-Type: application/json
-
-    {
-       "servings" : 4,
-       "subtitle" : "Delicious with fresh bread",
-       "title" : "Fish Stew"
-    }
-
-The return JSON will specify the automatically generated ID and revision
-information:
-
-.. code-block:: javascript
-
-    {
-       "id" : "64575eef70ab90a2b8d55fc09e00440d",
-       "ok" : true,
-       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
-    }
-
-Specifying the Document ID
---------------------------
-
-The document ID can be specified by including the ``_id`` field in the
-JSON of the submitted record. The following request will create the same
-document with the ID ``FishStew``:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/
-    Content-Type: application/json
-
-    {
-       "_id" : "FishStew",
-       "servings" : 4,
-       "subtitle" : "Delicious with fresh bread",
-       "title" : "Fish Stew"
-    }
-
-The structure of the submitted document is as shown in the table below:
-
-In either case, the returned JSON will specify the document ID, revision
-ID, and status message:
-
-.. code-block:: javascript
-
-    {
-       "id" : "FishStew",
-       "ok" : true,
-       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
-    }
-        
-
-UUID generation algorithms
---------------------------
-
-CouchDB supports a number of different UUID generation algorithms for use
-in situations where a user-specified UUID does not make sense. These
-can be set simply by `PUT http://couchdb:5984/_config/uuids/algorithm`.
-
-
-+---------------+---------------------+------------------------------------+
-| Algorithm     | Description         | Sample UUID                        |
-+===============+=====================+====================================+
-| random        | 128 bits of pure    | - 43febce5675468a5467fb5467ce9e6c0 |
-|               | random awesomeness  |                                    |
-+---------------+---------------------+------------------------------------+
-| sequential    | monotonically       | - f755c413badf66b22941313f9f001e28 |
-|               | increasing ids with | - f755c413badf66b22941313f9f0024ca |
-|               | random increments   | - f755c413badf66b22941313f9f00332c |
-+---------------+---------------------+------------------------------------+
-| utc_random    | time since start of | - 04cfa405381205204f75100d0241ccc3 |
-|               | epoch, as 14 hex    | - 04cfa4059c48e76e7c054bbe033dd8db |
-|               | digits, followed by | - 04cfa405fce10b0df4c08f95e667cd2f |
-|               | 18 random digits.   |                                    |
-+---------------+---------------------+------------------------------------+
-| utc_id        | time since start of | - 04cfa718b00848_i_am_in_yer_couch |
-| & additional  | epoch, as 14 hex    | - 04cfa71d377aef_i_am_in_yer_couch |
-| parameter     | digits, followed by | - 04cfa71e0deabd_i_am_in_yer_couch |
-|               | utc_id_suffix.      |                                    |
-+---------------+---------------------+------------------------------------+
-
-.. note:: **Impact of UUID choices:**
-   The choice of UUID has a significant impact on the layout of the B-tree,
-   prior to compaction.
-
-   For example, a sequential UUID algorithm during uploading thousands of
-   documents, will avoid the need to rewrite many intermediate B-tree nodes.
-   A random UUID algorithm may require rewriting intermediate nodes on a regular
-   basis, with a corresponding decrease of throughput, and significant wasted
-   space due to the append-only B-tree design.
-
-   It is generally recommended to set your own UUIDs, or use the sequential
-   algorithm unless you have a specific need and take into account the likely
-   need for compaction to re-balance the B-tree and reclaim wasted space.
-
-.. _api/doc/batch-writes:
-
-Batch Mode Writes
------------------
-
-You can write documents to the database at a higher rate by using the
-batch option. This collects document writes together in memory (on a
-user-by-user basis) before they are committed to disk. This increases
-the risk of the documents not being stored in the event of a failure,
-since the documents are not written to disk immediately.
-
-To use the batched mode, append the ``batch=ok`` query argument to the
-URL of the ``PUT`` or ``POST`` request. The CouchDB server will respond
-with a 202 HTTP response code immediately.
-
-Including Attachments
----------------------
-
-You can include one or more attachments with a given document by
-incorporating the attachment information within the JSON of the
-document. This provides a simpler alternative to loading documents with
-attachments than making a separate call (see :ref:`api/doc/attachment.put`).
-
-* **_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
-
-The ``filename`` will be the attachment name. For example, when sending
-the JSON structure below:
-
-.. code-block:: javascript
-
-    {
-       "_id" : "FishStew",
-       "servings" : 4,
-       "subtitle" : "Delicious with fresh bread",
-       "title" : "Fish Stew"
-       "_attachments" : {
-          "styling.css" : {
-             "content-type" : "text/css",
-             "data" : "cCB7IGZvbnQtc2l6ZTogMTJwdDsgfQo=",
-             },
-       },
-    }
-        
-
-The attachment ``styling.css`` can be accessed using
-``/recipes/FishStew/styling.css``. For more information on attachments,
-see :ref:`api/doc/attachment.get`.
-
-The document data embedded in to the structure must be encoded using
-base64.
-
-.. _api/doc.get:
-
-``GET /db/doc``
-===============
-
-* **Method**: ``GET /db/doc``
-* **Request**: None
-* **Response**: Returns the JSON for the document
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: conflicts
-
-    * **Description**: Returns the conflict tree for the document.
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-    * **Supported Values**:
-
-      * **true**: Includes the revisions
-
-  * **Argument**: rev
-
-    * **Description**: Specify the revision to return
-    * **Optional**: yes
-    * **Type**: string
-    * **Supported Values**:
-
-      * **true**: Includes the revisions
-
-  * **Argument**: revs
-
-    * **Description**:  Return a list of the revisions for the document
-    * **Optional**: yes
-    * **Type**: boolean
-
-  * **Argument**: revs_info
-
-    * **Description**: Return a list of detailed revision information for the
-      document
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Supported Values**:
-
-      * **true**: Includes the revisions
-
-* **Return Codes**:
-
-  * **200**:
-    Document retrieved
-  * **400**:
-    The format of the request or revision was invalid
-  * **404**:
-    The specified document or revision cannot be found, or has been deleted
-  * **409**:
-    Conflict - a document with the specified document ID already exists
-
-Returns the specified ``doc`` from the specified ``db``. For example, to
-retrieve the document with the id ``FishStew`` you would send the
-following request:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/FishStew
-    Content-Type: application/json
-    Accept: application/json
-
-The returned JSON is the JSON of the document, including the document ID
-and revision number:
-
-.. code-block:: javascript
-
-    {
-       "_id" : "FishStew",
-       "_rev" : "3-a1a9b39ee3cc39181b796a69cb48521c",
-       "servings" : 4,
-       "subtitle" : "Delicious with a green salad",
-       "title" : "Irish Fish Stew"
-    }
-        
-
-Unless you request a specific revision, the latest revision of the
-document will always be returned.
-
-Attachments
------------
-
-If the document includes attachments, then the returned structure will
-contain a summary of the attachments associated with the document, but
-not the attachment data itself.
-
-The JSON for the returned document will include the ``_attachments``
-field, with one or more attachment definitions. For example:
-
-.. code-block:: javascript
-
-    {
-       "_id" : "FishStew",
-       "servings" : 4,
-       "subtitle" : "Delicious with fresh bread",
-       "title" : "Fish Stew"
-       "_attachments" : {
-          "styling.css" : {
-             "stub" : true,
-             "content-type" : "text/css",
-             "length" : 783426,
-             },
-       },
-    }
-
-The format of the returned JSON is shown in the table below:
-
-* **_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
-    * **length**: Length (bytes) of the attachment data
-    * **revpos**: Revision where this attachment exists
-    * **stub**: Indicates whether the attachment is a stub
-
-Getting a List of Revisions
----------------------------
-
-You can obtain a list of the revisions for a given document by adding
-the ``revs=true`` parameter to the request URL. For example:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/FishStew?revs=true
-    Accept: application/json
-
-The returned JSON structure includes the original document, including a
-``_revisions`` structure that includes the revision information:
-
-.. code-block:: javascript
-
-    {
-       "servings" : 4,
-       "subtitle" : "Delicious with a green salad",
-       "_id" : "FishStew",
-       "title" : "Irish Fish Stew",
-       "_revisions" : {
-          "ids" : [
-             "a1a9b39ee3cc39181b796a69cb48521c",
-             "7c4740b4dcf26683e941d6641c00c39d",
-             "9c65296036141e575d32ba9c034dd3ee"
-          ],
-          "start" : 3
-       },
-       "_rev" : "3-a1a9b39ee3cc39181b796a69cb48521c"
-    }
-
-* **_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
-
-Obtaining an Extended Revision History
---------------------------------------
-
-You can get additional information about the revisions for a given
-document by supplying the ``revs_info`` argument to the query:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/FishStew?revs_info=true
-    Accept: application/json
-
-This returns extended revision information, including the availability
-and status of each revision:
-
-.. code-block:: javascript
-
-    {
-       "servings" : 4,
-       "subtitle" : "Delicious with a green salad",
-       "_id" : "FishStew",
-       "_revs_info" : [
-          {
-             "status" : "available",
-             "rev" : "3-a1a9b39ee3cc39181b796a69cb48521c"
-          },
-          {
-             "status" : "available",
-             "rev" : "2-7c4740b4dcf26683e941d6641c00c39d"
-          },
-          {
-             "status" : "available",
-             "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
-          }
-       ],
-       "title" : "Irish Fish Stew",
-       "_rev" : "3-a1a9b39ee3cc39181b796a69cb48521c"
-    }
-
-* **_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
-
-Obtaining a Specific Revision
------------------------------
-
-To get a specific revision, use the ``rev`` argument to the request, and
-specify the full revision number:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/FishStew?rev=2-7c4740b4dcf26683e941d6641c00c39d
-    Accept: application/json
-
-The specified revision of the document will be returned, including a
-``_rev`` field specifying the revision that was requested:
-
-.. code-block:: javascript
-
-    {
-       "_id" : "FishStew",
-       "_rev" : "2-7c4740b4dcf26683e941d6641c00c39d",
-       "servings" : 4,
-       "subtitle" : "Delicious with a green salad",
-       "title" : "Fish Stew"
-    }
-
-.. _api/doc.head:
-
-``HEAD /db/doc``
-================
-
-* **Method**: ``HEAD /db/doc``
-* **Request**: None
-* **Response**: None
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Specify the revision to return
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: revs
-
-    * **Description**:  Return a list of the revisions for the document
-    * **Optional**: yes
-    * **Type**: boolean
-
-  * **Argument**: revs_info
-
-    * **Description**:  Return a list of detailed revision information for the
-      document
-    * **Optional**: yes
-    * **Type**: boolean
-
-* **Return Codes**:
-
-  * **404**:
-    The specified document or revision cannot be found, or has been deleted
-
-Returns the HTTP Headers containing a minimal amount of information
-about the specified document. The method supports the same query
-arguments as the ``GET`` method, but only the header information
-(including document size, and the revision as an ETag), is returned. For
-example, a simple ``HEAD`` request:
-
-.. code-block:: http
-
-    HEAD http://couchdb:5984/recipes/FishStew
-    Content-Type: application/json
-        
-
-Returns the following HTTP Headers:
-
-.. code-block:: javascript
-
-    HTTP/1.1 200 OK
-    Server: CouchDB/1.0.1 (Erlang OTP/R13B)
-    Etag: "7-a19a1a5ecd946dad70e85233ba039ab2"
-    Date: Fri, 05 Nov 2010 14:54:43 GMT
-    Content-Type: text/plain;charset=utf-8
-    Content-Length: 136
-    Cache-Control: must-revalidate
-
-The ``Etag`` header shows the current revision for the requested
-document, and the ``Content-Length`` specifies the length of the data,
-if the document were requested in full.
-
-Adding any of the query arguments (as supported by ```GET```_ method),
-then the resulting HTTP Headers will correspond to what would be
-returned. Note that the current revision is not returned when the
-``refs_info`` argument is used. For example:
-
-.. code-block:: http
-
-    HTTP/1.1 200 OK
-    Server: CouchDB/1.0.1 (Erlang OTP/R13B)
-    Date: Fri, 05 Nov 2010 14:57:16 GMT
-    Content-Type: text/plain;charset=utf-8
-    Content-Length: 609
-    Cache-Control: must-revalidate
-
-.. _api/doc.put:
-
-``PUT /db/doc``
-===============
-
-* **Method**: ``PUT /db/doc``
-* **Request**: JSON of the new document, or updated version of the existed
-  document
-* **Response**: JSON of the document ID and revision
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: batch
-
-    * **Description**:  Allow document store request to be batched with others
-    * **Optional**: yes
-    * **Type**: string
-    * **Supported Values**:
-
-      * **ok**: Enable
-
-* **HTTP Headers**
-
-  * **Header**: ``If-Match``
-
-    * **Description**: Current revision of the document for validation
-    * **Optional**: yes
-
-* **Return Codes**:
-
-  * **201**:
-    Document has been created successfully
-  * **202**:
-    Document accepted for writing (batch mode)
-
-
-The ``PUT`` method creates a new named document, or creates a new
-revision of the existing document. Unlike the ``POST`` method, you
-must specify the document ID in the request URL.
-
-For example, to create the document ``FishStew``, you would send the
-following request:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/FishStew
-    Content-Type: application/json
-
-    {
-      "servings" : 4,
-      "subtitle" : "Delicious with fresh bread",
-      "title" : "Fish Stew"
-    }
-
-The return type is JSON of the status, document ID,and revision number:
-
-.. code-block:: javascript
-
-    {
-       "id" : "FishStew",
-       "ok" : true,
-       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
-    }
-
-Updating an Existing Document
------------------------------
-
-To update an existing document you must specify the current revision
-number within the ``_rev`` parameter. For example:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/FishStew
-    Content-Type: application/json
-
-    {
-      "_rev" : "1-9c65296036141e575d32ba9c034dd3ee",
-      "servings" : 4,
-      "subtitle" : "Delicious with fresh salad",
-      "title" : "Fish Stew"
-    }
-
-Alternatively, you can supply the current revision number in the
-``If-Match`` HTTP header of the request. For example:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/FishStew
-    If-Match: 2-d953b18035b76f2a5b1d1d93f25d3aea
-    Content-Type: application/json
-
-    {
-       "servings" : 4,
-       "subtitle" : "Delicious with fresh salad",
-       "title" : "Fish Stew"
-    }
-
-The JSON returned will include the updated revision number:
-
-.. code-block:: javascript
-
-    {
-       "id" : "FishStew99",
-       "ok" : true,
-       "rev" : "2-d953b18035b76f2a5b1d1d93f25d3aea"
-    }
-
-For information on batched writes, which can provide improved
-performance, see :ref:`api/doc/batch-writes`.
-
-.. _api/doc.delete:
-
-``DELETE /db/doc``
-==================
-
-* **Method**: ``DELETE /db/doc``
-* **Request**: None
-* **Response**: JSON of the deleted revision
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Current revision of the document for validation
-    * **Optional**: yes
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``If-Match``
-
-    * **Description**: Current revision of the document for validation
-    * **Optional**: yes
-
-* **Return Codes**:
-
-  * **409**:
-    Revision is missing, invalid or not the latest
-
-Deletes the specified document from the database. You must supply the
-current (latest) revision, either by using the ``rev`` parameter to
-specify the revision:
-
-.. code-block:: http
-
-    DELETE http://couchdb:5984/recipes/FishStew?rev=3-a1a9b39ee3cc39181b796a69cb48521c
-    Content-Type: application/json
-
-Alternatively, you can use ETags with the ``If-Match`` field:
-
-.. code-block:: http
-
-    DELETE http://couchdb:5984/recipes/FishStew
-    If-Match: 3-a1a9b39ee3cc39181b796a69cb48521c
-    Content-Type: application/json
-        
-
-The returned JSON contains the document ID, revision and status:
-
-.. code-block:: javascript
-
-    {
-       "id" : "FishStew",
-       "ok" : true,
-       "rev" : "4-2719fd41187c60762ff584761b714cfb"
-    }
-
-.. note:: Note that deletion of a record increments the revision number. The
-   use of a revision for deletion of the record allows replication of
-   the database to correctly track the deletion in synchronized copies.
-
-.. _api/doc.copy:
-
-``COPY /db/doc``
-================
-
-* **Method**: ``COPY /db/doc``
-* **Request**: None
-* **Response**: JSON of the new document and revision
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Revision to copy from
-    * **Optional**: yes
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``Destination``
-
-    * **Description**: Destination document (and optional revision)
-    * **Optional**: no
-
-* **Return Codes**:
-
-  * **201**:
-    Document has been copied and created successfully
-  * **409**:
-    Revision is missing, invalid or not the latest
-
-The ``COPY`` command (which is non-standard HTTP) copies an existing
-document to a new or existing document.
-
-The source document is specified on the request line, with the
-``Destination`` HTTP Header of the request specifying the target
-document.
-
-Copying a Document
-------------------
-
-You can copy the latest version of a document to a new document by
-specifying the current document and target document:
-
-.. code-block:: http
-
-    COPY http://couchdb:5984/recipes/FishStew
-    Content-Type: application/json
-    Destination: IrishFishStew
-
-The above request copies the document ``FishStew`` to the new document
-``IrishFishStew``. The response is the ID and revision of the new
-document.
-
-.. code-block:: javascript
-
-    {
-       "id" : "IrishFishStew",
-       "rev" : "1-9c65296036141e575d32ba9c034dd3ee"
-    }
-
-Copying from a Specific Revision
---------------------------------
-
-To copy *from* a specific version, use the ``rev`` argument to the query
-string:
-
-.. code-block:: http
-
-    COPY http://couchdb:5984/recipes/FishStew?rev=5-acfd32d233f07cea4b4f37daaacc0082
-    Content-Type: application/json
-    Destination: IrishFishStew
-
-The new document will be created using the information in the specified
-revision of the source document.
-
-Copying to an Existing Document
--------------------------------
-
-To copy to an existing document, you must specify the current revision
-string for the target document, using the ``rev`` parameter to the
-``Destination`` HTTP Header string. For example:
-
-.. code-block:: http
-
-    COPY http://couchdb:5984/recipes/FishStew
-    Content-Type: application/json
-    Destination: IrishFishStew?rev=1-9c65296036141e575d32ba9c034dd3ee
-
-The return value will be the new revision of the copied document:
-
-.. code-block:: javascript
-
-    {
-       "id" : "IrishFishStew",
-       "rev" : "2-55b6a1b251902a2c249b667dab1c6692"
-    }
-
-.. _api/doc/attachment:
-.. _api/doc/attachment.get:
-
-``GET /db/doc/attachment``
-==========================
-
-* **Method**: ``GET /db/doc/attachment``
-* **Request**: None
-* **Response**: Returns the attachment data
-* **Admin Privileges Required**: no
-
-Returns the file attachment ``attachment`` associated with the document
-``doc``. The raw data of the associated attachment is returned (just as
-if you were accessing a static file. The returned HTTP ``Content-type``
-will be the same as the content type set when the document attachment
-was submitted into the database.
-
-.. _api/doc/attachment/range:
-
-HTTP Range Requests
--------------------
-
-HTTP allows you to specify byte ranges for requests. This allows the
-implementation of resumable downloads and skippable audio and video
-streams alike. This is available for all attachments inside CouchDB.
-
-This is just a real quick run through how this looks under the hood.
-Usually, you will have larger binary files to serve from CouchDB, like
-MP3s and videos, but to make things a little more obvious, I use a text
-file here (Note that I use the ``application/octet-stream`` Content-Type
-instead of ``text/plain``).
-
-.. code-block:: bash
-
-    shell> cat file.txt
-    My hovercraft is full of eels!
-
-Now let's store this text file as an attachment in CouchDB. First, we
-create a database:
-
-.. code-block:: bash
-
-    shell> curl -X PUT http://127.0.0.1:5984/test
-    {"ok":true}
-
-Then we create a new document and the file attachment in one go:
-
-.. code-block:: bash
-
-    shell> curl -X PUT http://127.0.0.1:5984/test/doc/file.txt \
-                -H "Content-Type: application/octet-stream" -d@file.txt
-    {"ok":true,"id":"doc","rev":"1-287a28fa680ae0c7fb4729bf0c6e0cf2"}
-
-Now we can request the whole file easily:
-
-.. code-block:: bash
-
-    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt
-    My hovercraft is full of eels!
-
-But say we only want the first 13 bytes:
-
-.. code-block:: bash
-
-    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt \
-                -H "Range: bytes=0-12"
-    My hovercraft
-
-HTTP supports many ways to specify single and even multiple byte
-ranges. Read all about it in `RFC 2616`_.
-
-.. note::
-   Databases that have been created with CouchDB 1.0.2 or earlier will
-   support range requests in |version|, but they are using a less-optimal
-   algorithm. If you plan to make heavy use of this feature, make sure
-   to compact your database with CouchDB |version| to take advantage of a
-   better algorithm to find byte ranges.
-
-.. _RFC 2616: http://tools.ietf.org/html/rfc2616#section-14.27
-
-
-.. _api/doc/attachment.put:
-
-``PUT /db/doc/attachment``
-==========================
-
-* **Method**: ``PUT /db/doc/attachment``
-* **Request**: Raw document data
-* **Response**: JSON document status
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Current document revision
-    * **Optional**: no
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``Content-Length``
-
-    * **Description**: Length (bytes) of the attachment being uploaded
-    * **Optional**: no
-
-  * **Header**: ``Content-Type``
-
-    * **Description**: MIME type for the uploaded attachment
-    * **Optional**: no
-
-  * **Header**: ``If-Match``
-
-    * **Description**: Current revision of the document for validation
-    * **Optional**: yes
-
-* **Return Codes**:
-
-  * **201**:
-    Attachment has been accepted
-
-Upload the supplied content as an attachment to the specified document
-(``doc``). The ``attachment`` name provided must be a URL encoded
-string. You must also supply either the ``rev`` query argument or the
-``If-Match`` HTTP header for validation, and the HTTP headers (to set
-the attachment content type). The content type is used when the
-attachment is requested as the corresponding content-type in the
-returned document header.
-
-For example, you could upload a simple text document using the following
-request:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/FishStew/basic?rev=8-a94cb7e50ded1e06f943be5bfbddf8ca
-    Content-Length: 10
-    Content-Type: text/plain
-
-    Roast it
-
-Or by using the ``If-Match`` HTTP header:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/FishStew/basic
-    If-Match: 8-a94cb7e50ded1e06f943be5bfbddf8ca
-    Content-Length: 10
-    Content-Type: text/plain
-
-    Roast it
-
-The returned JSON contains the new document information:
-
-.. code-block:: javascript
-
-    {
-       "id" : "FishStew",
-       "ok" : true,
-       "rev" : "9-247bb19a41bfd9bfdaf5ee6e2e05be74"
-    }
-
-.. note:: Uploading an attachment updates the corresponding document revision.
-   Revisions are tracked for the parent document, not individual
-   attachments.
-
-Updating an Existing Attachment
--------------------------------
-
-Uploading an attachment using an existing attachment name will update
-the corresponding stored content of the database. Since you must supply
-the revision information to add an attachment to a document, this serves
-as validation to update the existing attachment.
-
-.. _api/doc/attachment.delete:
-
-``DELETE /db/doc/attachment``
-=============================
-
-* **Method**: ``DELETE /db/doc/attachment``
-* **Request**: None
-* **Response**: JSON status
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Current document revision
-    * **Optional**: no
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``If-Match``
-
-    * **Description**: Current revision of the document for validation
-    * **Optional**: yes
-
-* **Return Codes**:
-
-  * **200**:
-    Attachment deleted successfully
-  * **409**:
-    Supplied revision is incorrect or missing
-
-Deletes the attachment ``attachment`` to the specified ``doc``. You must
-supply the ``rev`` argument with the current revision to delete the
-attachment.
-
-For example to delete the attachment ``basic`` from the recipe
-``FishStew``:
-
-.. code-block:: http
-
-    DELETE http://couchdb:5984/recipes/FishStew/basic?rev=9-247bb19a41bfd9bfdaf5ee6e2e05be74
-    Content-Type: application/json
-
-        
-
-The returned JSON contains the updated revision information:
-
-.. code-block:: javascript
-
-    {
-       "id" : "FishStew",
-       "ok" : true,
-       "rev" : "10-561bf6b1e27615cee83d1f48fa65dd3e"
-    }
-
-.. _JSON object: #table-couchdb-api-db_db-json-changes
-.. _POST: #couchdb-api-dbdoc_db_post

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/index.rst b/share/doc/src/api/index.rst
index 398a058..2449471 100644
--- a/share/doc/src/api/index.rst
+++ b/share/doc/src/api/index.rst
@@ -12,6 +12,7 @@
 
 .. _api:
 
+=============
 API Reference
 =============
 
@@ -34,10 +35,8 @@ This reference is structured according to the URL structure, as below.
    :maxdepth: 2
 
    basics
-   database
-   documents
-   design
+   server/index
+   database/index
+   document/index
+   ddoc/index
    local
-   configuration
-   authn
-   misc


[09/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add replication protocol definition.

COUCHDB-1824


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/ae9ceacc
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/ae9ceacc
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/ae9ceacc

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: ae9ceacc8fe3aa0fdd9b6ff2a201e4cd76487953
Parents: 4ecafeb
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 22:41:28 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am             |   3 +
 share/doc/src/replications/index.rst    |   1 +
 share/doc/src/replications/protocol.rst | 201 +++++++++++++++++++++++++++
 3 files changed, 205 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/ae9ceacc/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 1580f85..cb60fba 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -70,6 +70,7 @@ html_files = \
     html/_sources/config/proxying.txt \
     html/_sources/replications/index.txt \
     html/_sources/replications/intro.txt \
+    html/_sources/replications/protocol.txt \
     html/_sources/replications/replicator.txt \
     html/_sources/changelog.txt \
     html/_sources/changes.txt \
@@ -127,6 +128,7 @@ html_files = \
     html/config/proxying.html \
     html/replications/index.html \
     html/replications/intro.html \
+    html/replications/protocol.html \
     html/replications/replicator.html \
     html/changelog.html \
     html/changes.html \
@@ -182,6 +184,7 @@ src_files = \
     ../src/config/proxying.rst \
     ../src/replications/index.rst \
     ../src/replications/intro.rst \
+    ../src/replications/protocol.rst \
     ../src/replications/replicator.rst \
     ../src/changelog.rst \
     ../src/changes.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/ae9ceacc/share/doc/src/replications/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/index.rst b/share/doc/src/replications/index.rst
index b626bc6..940a29c 100644
--- a/share/doc/src/replications/index.rst
+++ b/share/doc/src/replications/index.rst
@@ -33,3 +33,4 @@ destination database.
 
    intro
    replicator
+   protocol

http://git-wip-us.apache.org/repos/asf/couchdb/blob/ae9ceacc/share/doc/src/replications/protocol.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/protocol.rst b/share/doc/src/replications/protocol.rst
new file mode 100644
index 0000000..bf478f7
--- /dev/null
+++ b/share/doc/src/replications/protocol.rst
@@ -0,0 +1,201 @@
+.. 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.
+
+.. _replication/protocol:
+
+============================
+CouchDB Replication Protocol
+============================
+
+The **CouchDB Replication protocol** is a protocol for synchronizing
+documents between 2 peers over HTTP/1.1.
+
+Language
+--------
+
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+document are to be interpreted as described in :rfc:`2119`.
+
+
+Goals
+-----
+
+The CouchDB Replication protocol is a synchronization protocol for
+synchronizing documents between 2 peers over HTTP/1.1.
+
+In theory the CouchDB protocol can be used between products that
+implement it. However the reference implementation, written in Erlang_, is
+provided by the couch_replicator_ module available in Apache CouchDB.
+
+
+The CouchDB_ replication protocol is using the `CouchDB REST API
+<http://wiki.apache.org/couchdb/Reference>`_ and so is based on HTTP and
+the Apache CouchDB MVC Data model. The primary goal of this
+specification is to describe the CouchDB replication algorithm.
+
+
+Definitions
+-----------
+
+ID:
+    An identifier (could be an UUID) as described in :rfc:`4122`
+
+Sequence:
+    An ID provided by the changes feed. It can be numeric but not
+    necessarily.
+
+Revision:
+    (to define)
+
+Document
+    A document is JSON entity with a unique ID and revision.
+
+Database
+    A collection of documents with a unique URI
+
+URI
+    An uri is defined by the :rfc:`2396` . It can be an URL as defined
+    in :rfc:`1738`.
+
+Source
+    Database from where the Documents are replicated
+
+Target
+    Database where the Document are replicated
+
+Checkpoint
+    Last source sequence ID
+
+
+Algorithm
+---------
+
+1. Get unique identifiers for the Source and Target based on their URI if
+   replication task ID is not available.
+
+2. Save this identifier in a special Document named `_local/<uniqueid>`
+   on the Target database. This document isn't replicated. It will
+   collect the last Source sequence ID, the Checkpoint, from the
+   previous replication process.
+
+3. Get the Source changes feed by passing it the Checkpoint using the
+   `since` parameter by calling the `/<source>/_changes` URL. The
+   changes feed only return a list of current revisions.
+
+
+.. note::
+
+    This step can be done continuously using the `feed=longpoll` or
+    `feed=continuous` parameters. Then the feed will continuously get
+    the changes.
+
+
+4. Collect a group of Document/Revisions ID pairs from the **changes
+   feed** and send them to the target databases on the
+   `/<target>/_revs_diffs` URL. The result will contain the list of
+   revisions **NOT** in the Target.
+
+5. GET each revisions from the source Database by calling the URL
+   `/<source>/<docid>?revs=true&open_revs`=<revision>` . This
+   will get the document with teh parent revisions. Also don't forget to
+   get attachments that aren't already stored at the target. As an
+   optimisation you can use the HTTP multipart api to get all.
+
+6. Collect a group of revisions fetched at previous step and store them
+   on the target database using the `Bulk Docs
+   <http://wiki.apache.org/couchdb/HTTP_Document_API#Bulk_Docs>`_ API
+   with the `new_edit: false` JSON property to preserve their revisions
+   ID.
+
+7. After the group of revision is stored on the Target, save
+   the new Checkpoint on the Source.
+
+
+.. note::
+
+    - Even if some revisions have been ignored the sequence should be
+      take in consideration for the Checkpoint.
+
+    - To compare non numeric sequence ordering, you will have to keep an
+      ordered list of the sequences IDS as they appear in the _changes
+      feed and compare their indices.
+
+Filter replication
+------------------
+
+The replication can be filtered by passing the `filter` parameter to the
+changes feeds with a function name. This will call a function on each
+changes. If this function return True, the document will be added to the
+feed.
+
+
+Optimisations
+-------------
+
+- The system should run each steps in parallel to reduce the latency.
+
+- The number of revisions passed to the step 3 and 6 should be large
+  enough to reduce the bandwidth and make sure to reduce the latency.
+
+
+API Reference
+-------------
+
+- :ref:`api/db.head` -- Check Database existence
+- :ref:`api/db/ensure_full_commit` -- Ensure that all changes are stored on disk
+- :ref:`api/local/doc.get` -- Read the last Checkpoint
+- :ref:`api/local/doc.put` -- Save a new Checkpoint
+
+Push Only
+~~~~~~~~~
+
+- :ref:`api/db.put` -- Create Target if it not exists and option was provided
+- :ref:`api/db/revs_diff.post` -- Locate Revisions that are not known to the
+  Target
+- :ref:`api/db/bulk_docs.post` -- Upload Revisions to the Target
+- :ref:`api/doc.put`?new_edits=false -- Upload a single Document with
+  attachments to the Target
+
+Pull Only
+~~~~~~~~~
+
+- :ref:`api/db/changes.get` -- Locate changes since on Source the last pull.
+  The request uses next query parameters:
+
+  - ``style=all_docs``
+  - ``feed=feed`` , where feed is :ref:`normal <changes/normal>` or
+    :ref:`longpoll <changes/longpoll>`
+  - ``limit=limit``
+  - ``heartbeat=heartbeat``
+
+- :ref:`api/doc.get` -- Retrieve a single Document from Source with attachments.
+  The request uses next query parameters:
+
+  - ``open_revs=revid`` - where ``revid`` is the actual Document Revision at the
+    moment of the pull request
+  - ``revs=true``
+  - ``atts_since=lastrev``
+
+Reference
+---------
+
+* `TouchDB Ios wiki <https://github.com/couchbaselabs/TouchDB-iOS/wiki/Replication-Algorithm>`_
+* `CouchDB documentation
+  <http://wiki.apache.org/couchdb/Replication>`_
+* CouchDB `change notifications`_
+
+.. _CouchDB: http://couchdb.apache.org
+.. _Erlang: http://erlang.org
+.. _couch_replicator: https://github.com/apache/couchdb/tree/master/src/couch_replicator
+.. _change notifications: http://guide.couchdb.org/draft/notifications.html
+


[25/50] [abbrv] Split API articles into small files focused on specific problem.

Posted by kx...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/server/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/server/index.rst b/share/doc/src/api/server/index.rst
new file mode 100644
index 0000000..fb3229f
--- /dev/null
+++ b/share/doc/src/api/server/index.rst
@@ -0,0 +1,75 @@
+.. 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.
+
+
+.. _api/server:
+
+==============
+Server Methods
+==============
+
+The CouchDB server interface provides the basic interface to a
+CouchDB server for obtaining CouchDB information and getting and setting
+configuration information.
+
+A list of the available methods and URL paths are provided below:
+
++--------+-------------------------+-------------------------------------------+
+| Method | Path                    | Description                               |
++========+=========================+===========================================+
+| GET    | /                       |  Get the welcome message and version      |
+|        |                         |  information                              |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_active_tasks          |  Obtain a list of the tasks running in the|
+|        |                         |  server                                   |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_all_dbs               |  Get a list of all the DBs                |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_config                |  Obtain a list of the entire server       |
+|        |                         |  configuration                            |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_config/section        |  Get all the configuration values for the |
+|        |                         |  specified section                        |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_config/section/key    |  Get a specific section/config value      |
++--------+-------------------------+-------------------------------------------+
+| PUT    | /_config/section/key    |  Set the specified configuration value    |
++--------+-------------------------+-------------------------------------------+
+| DELETE | /_config/section/key    |  Delete the current setting               |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_log                   |  Return the server log file               |
++--------+-------------------------+-------------------------------------------+
+| POST   | /_replicate             |  Set or cancel replication                |
++--------+-------------------------+-------------------------------------------+
+| POST   | /_restart               |  Restart the server                       |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_session               |  Returns cookie based login user          |
+|        |                         |  information                              |
++--------+-------------------------+-------------------------------------------+
+| POST   | /_session               |  Do cookie based user login               |
++--------+-------------------------+-------------------------------------------+
+| DELETE | /_session               |  Logout cookie based user                 |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_stats                 |  Return server statistics                 |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_utils                 |  CouchDB administration interface (Futon) |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_uuids                 |  Get generated UUIDs from the server      |
++--------+-------------------------+-------------------------------------------+
+| GET    | /favicon.ico            |  Get the site icon                        |
++--------+-------------------------+-------------------------------------------+
+
+.. toctree::
+
+   common
+   authn
+   configuration

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/config/http-handlers.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/http-handlers.rst b/share/doc/src/config/http-handlers.rst
index 65ba437..19ef17c 100644
--- a/share/doc/src/config/http-handlers.rst
+++ b/share/doc/src/config/http-handlers.rst
@@ -25,8 +25,8 @@ These HTTP resources are provided for CouchDB server root level.
 
 .. _config/httpd_global_handlers/root:
 
-:ref:`/ <api/misc/root>`
-------------------------
+:ref:`/ <api/server/root>`
+--------------------------
 
 ::
 
@@ -36,8 +36,8 @@ These HTTP resources are provided for CouchDB server root level.
 
 .. _config/httpd_global_handlers/favicon.ico:
 
-:ref:`favicon.ico <api/misc/favicon>`
--------------------------------------
+:ref:`favicon.ico <api/server/favicon>`
+---------------------------------------
 
 The favicon handler looks for `favicon.ico` file within specified directory::
 
@@ -47,8 +47,8 @@ The favicon handler looks for `favicon.ico` file within specified directory::
 
 .. _config/httpd_global_handlers/_active_tasks:
 
-:ref:`_active_tasks <api/misc/active_tasks>`
---------------------------------------------
+:ref:`_active_tasks <api/server/active_tasks>`
+----------------------------------------------
 
 ::
 
@@ -58,8 +58,8 @@ The favicon handler looks for `favicon.ico` file within specified directory::
 
 .. _config/httpd_global_handlers/_all_dbs:
 
-:ref:`_all_dbs <api/misc/all_dbs>`
-----------------------------------
+:ref:`_all_dbs <api/server/all_dbs>`
+------------------------------------
 
 Provides list of all server's databases::
 
@@ -91,8 +91,8 @@ and doesn't requires server instance to be restarted::
 
 .. _config/httpd_global_handlers/_log:
 
-:ref:`_log <api/misc/log>`
---------------------------
+:ref:`_log <api/server/log>`
+----------------------------
 
 ::
 
@@ -113,10 +113,10 @@ and doesn't requires server instance to be restarted::
 
 .. _config/httpd_global_handlers/_replicate:
 
-:ref:`_replicate <api/misc/replicate>`
---------------------------------------
+:ref:`_replicate <api/server/replicate>`
+----------------------------------------
 
-Provides API to run :ref:`temporary replications <api/misc/replicate>`::
+Provides API to run :ref:`temporary replications <api/server/replicate>`::
 
   [httpd_global_handlers]
   _replicate = {couch_replicator_httpd, handle_req}
@@ -124,8 +124,8 @@ Provides API to run :ref:`temporary replications <api/misc/replicate>`::
 
 .. _config/httpd_global_handlers/_restart:
 
-:ref:`_restart <api/misc/restart>`
-----------------------------------
+:ref:`_restart <api/server/restart>`
+------------------------------------
 
 ::
 
@@ -146,8 +146,8 @@ Provides resource with information about current user's session::
 
 .. _config/httpd_global_handlers/_stats:
 
-:ref:`_stats <api/misc/stats>`
-------------------------------
+:ref:`_stats <api/server/stats>`
+--------------------------------
 
 ::
 
@@ -157,10 +157,10 @@ Provides resource with information about current user's session::
 
 .. _config/httpd_global_handlers/_utils:
 
-:ref:`_utils <api/misc/utils>`
-------------------------------
+:ref:`_utils <api/server/utils>`
+--------------------------------
 
-The :ref:`_utils <api/misc/utils>` handler serves `Futon`'s web administration
+The :ref:`_utils <api/server/utils>` handler serves `Futon`'s web administration
 page::
 
   [httpd_global_handlers]
@@ -172,8 +172,8 @@ files.
 
 .. _config/httpd_global_handlers/_uuids:
 
-:ref:`_uuids <api/misc/uuids>`
-------------------------------
+:ref:`_uuids <api/server/uuids>`
+--------------------------------
 
 Provides resource to get UUIDs generated on server side::
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/config/http.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/http.rst b/share/doc/src/config/http.rst
index 0131e48..6c7e0ba 100644
--- a/share/doc/src/config/http.rst
+++ b/share/doc/src/config/http.rst
@@ -141,7 +141,7 @@ Controls :ref:`CORS <config/cors>` feature::
 ``log_max_chunk_size`` :: Logs chunk size
 -----------------------------------------
 
-Defines maximum chunk size in bytes for :ref:`_log <api/misc/log>` resource::
+Defines maximum chunk size in bytes for :ref:`_log <api/server/log>` resource::
 
   [httpd]
   log_max_chunk_size = 1000000

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/intro.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/intro.rst b/share/doc/src/intro.rst
index faf6bcc..6f3603b 100644
--- a/share/doc/src/intro.rst
+++ b/share/doc/src/intro.rst
@@ -81,7 +81,7 @@ The main sections are:
    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/misc/active_tasks>` API call.
+   :ref:`Active Tasks <api/server/active_tasks>` API call.
 
 -  Verify Installation
 
@@ -201,7 +201,7 @@ 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:`api/misc/replicate`. For more information on
+For more information, see :ref:`api/server/replicate`. For more information on
 replication, see :ref:`replication`.
 
 .. _using-curl:

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/replication/intro.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication/intro.rst b/share/doc/src/replication/intro.rst
index f9c81e2..ea4892d 100644
--- a/share/doc/src/replication/intro.rst
+++ b/share/doc/src/replication/intro.rst
@@ -35,7 +35,7 @@ each document describes one replication process (see
 
 A replication is triggered by storing a replication document in the replicator
 database. Its status can be inspected through the active tasks API (see
-:ref:`api/misc/active_tasks` and :ref:`replication-status`). A replication can be
+:ref:`api/server/active_tasks` and :ref:`replication-status`). A replication can be
 stopped by deleting the document, or by updating it with its `cancel` property
 set to `true`.
 


[49/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Fix build files references.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/0c22cf64
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/0c22cf64
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/0c22cf64

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 0c22cf6487b114086ad944d84e5c8228d29ad5a6
Parents: b548740
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 16:16:10 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 16:16:10 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/0c22cf64/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index ffe64aa..75e9ddb 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -106,11 +106,11 @@ html_files = \
     html/_sources/query-server/erlang.txt \
     html/_sources/query-server/javascript.txt \
     html/_sources/query-server/protocol.txt \
-    html/_sources/replications/conflicts.txt \
-    html/_sources/replications/index.txt \
-    html/_sources/replications/intro.txt \
-    html/_sources/replications/protocol.txt \
-    html/_sources/replications/replicator.txt \
+    html/_sources/replication/conflicts.txt \
+    html/_sources/replication/index.txt \
+    html/_sources/replication/intro.txt \
+    html/_sources/replication/protocol.txt \
+    html/_sources/replication/replicator.txt \
     html/_sources/changelog.txt \
     html/_sources/contributing.txt \
     html/_sources/externals.txt \
@@ -197,11 +197,11 @@ html_files = \
     html/query-server/erlang.html \
     html/query-server/javascript.html \
     html/query-server/protocol.html \
-    html/replications/conflicts.html \
-    html/replications/index.html \
-    html/replications/intro.html \
-    html/replications/protocol.html \
-    html/replications/replicator.html \
+    html/replication/conflicts.html \
+    html/replication/index.html \
+    html/replication/intro.html \
+    html/replication/protocol.html \
+    html/replication/replicator.html \
     html/changelog.html \
     html/externals.html \
     html/index.html \


[02/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Group external processes configuration.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/af75771f
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/af75771f
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/af75771f

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: af75771f1d7696e22b940f12c15b56441757435b
Parents: 4208966
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 17 08:38:17 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:36 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am                  |   9 +-
 share/doc/src/config/externals.rst           | 179 ++++++++++++++++++++++
 share/doc/src/config/index.rst               |   3 +-
 share/doc/src/config/os-daemons.rst          | 126 ---------------
 share/doc/src/config/update-notification.rst |  64 --------
 5 files changed, 183 insertions(+), 198 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/af75771f/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 2c820e4..a211b31 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -58,14 +58,13 @@ html_files = \
     html/_sources/config/compaction.txt \
     html/_sources/config/couchdb.txt \
     html/_sources/config/daemons.txt \
+    html/_sources/config/externals.txt \
     html/_sources/config/http.txt \
     html/_sources/config/index.txt \
     html/_sources/config/log.txt \
-    html/_sources/config/os-daemons.txt \
     html/_sources/config/query-servers.txt \
     html/_sources/config/replicator.txt \
     html/_sources/config/stats.txt \
-    html/_sources/config/update-notification.txt \
     html/_sources/config/uuids.txt \
     html/_sources/config/vendor.txt \
     html/_sources/config/intro.txt \
@@ -117,14 +116,13 @@ html_files = \
     html/config/compaction.html \
     html/config/couchdb.html \
     html/config/daemons.html \
+    html/config/externals.html \
     html/config/http.html \
     html/config/index.html \
     html/config/log.html \
-    html/config/os-daemons.html \
     html/config/query-servers.html \
     html/config/replicator.html \
     html/config/stats.html \
-    html/config/update-notification.html \
     html/config/uuids.html \
     html/config/vendor.html \
     html/config/intro.html \
@@ -174,14 +172,13 @@ src_files = \
     ../src/config/compaction.rst \
     ../src/config/couchdb.rst \
     ../src/config/daemons.rst \
+    ../src/config/externals.rst \
     ../src/config/http.rst \
     ../src/config/index.rst \
     ../src/config/log.rst \
-    ../src/config/os-daemons.rst \
     ../src/config/query-servers.rst \
     ../src/config/replicator.rst \
     ../src/config/stats.rst \
-    ../src/config/update-notification.rst \
     ../src/config/uuids.rst \
     ../src/config/vendor.rst \
     ../src/config/intro.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/af75771f/share/doc/src/config/externals.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/externals.rst b/share/doc/src/config/externals.rst
new file mode 100644
index 0000000..4f0d4e9
--- /dev/null
+++ b/share/doc/src/config/externals.rst
@@ -0,0 +1,179 @@
+.. 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.
+
+.. highlight:: ini
+
+==================
+External Processes
+==================
+
+.. _config/os_daemons:
+
+``[os_daemons]`` :: OS Daemons
+==============================
+
+This is a simple feature that allows users to configure CouchDB so that it
+maintains a given OS level process alive. If the process dies for any reason,
+CouchDB will restart it. If the process restarts too often, then CouchDB will
+mark it has halted and not attempt to restart it. The default max restart rate
+is ``3`` times in the last ``5`` seconds. These parameters are
+:ref:`adjustable <config/os_daemons_settings>`.
+
+Commands that are started in this manner will have access to a simple
+API over stdio to request configuration parameters or to add log
+statements to CouchDB's logs.
+
+To configure an OS process as a CouchDB os_daemon, create a section
+in your `local.ini` like such::
+
+  [os_daemons]
+  daemon_name = /path/to/command -with args
+
+This will make CouchDB bring up the command and attempt to keep it
+alive. To request a configuration parameter, an `os_daemon` can write
+a simple JSON message to stdout like such::
+
+  ["get", "os_daemons"]\n
+
+which would return::
+
+  {"daemon_name": "/path/to/command -with args"}\n
+
+Or::
+
+  ["get", "os_daemons", "daemon_name"]\n
+
+which would return::
+
+  "/path/to/command -with args"\n
+
+There's no restriction on what configuration variables are visible.
+There's also no method for altering the configuration.
+
+If you would like your OS daemon to be restarted in the event that
+the configuration changes, you can send the following messages::
+
+  ["register", $(SECTION)]\n
+
+When anything in that section changes, your OS process will be
+rebooted so it can pick up the new configuration settings. If you
+want to listen for changes on a specific key, you can send something
+like::
+
+  ["register", $(SECTION), $(KEY)]\n
+
+In this case, CouchDB will only restart your daemon if that exact
+section/key pair changes, instead of anything in that entire section.
+
+Logging commands look like::
+
+  ["log", $(JSON_MESSAGE)]\n
+
+Where ``$(JSON_MESSAGE)`` is arbitrary JSON data. These messages are
+logged at the 'info' level. If you want to log at a different level
+you can pass messages like such::
+
+  ["log", $(JSON_MESSAGE), {"level": $(LEVEL)}]\n
+
+Where ``$(LEVEL)`` is one of "debug", "info", or "error".
+
+When implementing a daemon process to be managed by CouchDB you
+should remember to use a method like checking the parent process
+id or if stdin has been closed. These flags can tell you if
+your daemon process has been orphaned so you can exit cleanly.
+
+There is no interactivity between CouchDB and the running process, but
+you can use the OS Daemons service to create new HTTP servers and
+responders and then use the new proxy service to redirect requests and
+output to the CouchDB managed service. For more information on proxying,
+see :ref:`http-proxying`. For further background on the OS Daemon service, see
+`CouchDB Externals API`_.
+
+.. _CouchDB Externals API: http://davispj.com/2010/09/26/new-couchdb-externals-api.html
+
+
+.. _config/os_daemons_settings:
+
+``[os_daemon_settings]`` :: OS Daemons settings
+===============================================
+
+.. _config/os_daemons_settings/max_retries:
+
+``max_retries`` :: Maximum restart retries
+------------------------------------------
+
+Specifies maximum attempts to run :ref:`os_daemon <config/os_daemons>` before
+mark him halted::
+
+  [os_daemon_settings]
+  max_retries = 3
+
+
+.. _config/os_daemons_settings/retry_time:
+
+``retry_time`` :: Delay between restart attempts
+------------------------------------------------
+
+Delay in seconds between :ref:`os_daemon <config/os_daemons>` restarts::
+
+  [os_daemon_settings]
+  retry_time = 5
+
+
+
+.. _update-notifications:
+.. _config/update-notification:
+
+``[update_notification]`` :: Update notifications
+=================================================
+
+CouchDB is able to spawn OS processes to notify them about recent databases
+updates. The notifications are in form of JSON messages sent as a line of text,
+terminated by ``CR`` (``\n``) character, to the OS processes through `stdout`::
+
+  [update_notification]
+  ;unique notifier name=/full/path/to/exe -with "cmd line arg"
+  index_updater = ruby /usr/local/bin/index_updater.rb
+
+
+The update notification messages are depend upon of event type:
+
+- **Database created**:
+
+  .. code-block:: javascript
+
+    {"type":"created","db":"dbname"}
+
+
+- **Database updated**:  this event raises when any document gets updated for
+  specified database:
+
+  .. code-block:: javascript
+
+    {"type":"updated","db":"dbname"}
+
+
+- **Design document updated**: for design document updates there is special
+  event raised in additional to regular db update one:
+
+  .. code-block:: javascript
+
+    {"type":"ddoc_updated","db":"dbname","id":"_design/ddoc_name"}
+
+
+- **Database deleted**:
+
+  .. code-block:: javascript
+
+    {"type":"deleted","db":"dbname"}
+
+.. note:: New line (``\n``) trailing character was removed from examples.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/af75771f/share/doc/src/config/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/index.rst b/share/doc/src/config/index.rst
index 0a877a1..5e5d4ef 100644
--- a/share/doc/src/config/index.rst
+++ b/share/doc/src/config/index.rst
@@ -24,16 +24,15 @@ Configuring CouchDB
    auth
    compaction
    query-servers
+   externals
    proxying
 
    attachments
    couchdb
    daemons
    log
-   os-daemons
    replicator
    stats
-   update-notification
    uuids
    vendor
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/af75771f/share/doc/src/config/os-daemons.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/os-daemons.rst b/share/doc/src/config/os-daemons.rst
deleted file mode 100644
index 8f8611d..0000000
--- a/share/doc/src/config/os-daemons.rst
+++ /dev/null
@@ -1,126 +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.
-
-.. highlight:: ini
-
-.. _config/os_daemons:
-
-``[os_daemons]`` :: OS Daemons
-==============================
-
-This is a simple feature that allows users to configure CouchDB so that it
-maintains a given OS level process alive. If the process dies for any reason,
-CouchDB will restart it. If the process restarts too often, then CouchDB will
-mark it has halted and not attempt to restart it. The default max restart rate
-is ``3`` times in the last ``5`` seconds. These parameters are
-:ref:`adjustable <config/os_daemons_settings>`.
-
-Commands that are started in this manner will have access to a simple
-API over stdio to request configuration parameters or to add log
-statements to CouchDB's logs.
-
-To configure an OS process as a CouchDB os_daemon, create a section
-in your `local.ini` like such::
-
-  [os_daemons]
-  daemon_name = /path/to/command -with args
-
-This will make CouchDB bring up the command and attempt to keep it
-alive. To request a configuration parameter, an `os_daemon` can write
-a simple JSON message to stdout like such::
-
-  ["get", "os_daemons"]\n
-
-which would return::
-
-  {"daemon_name": "/path/to/command -with args"}\n
-
-Or::
-
-  ["get", "os_daemons", "daemon_name"]\n
-
-which would return::
-
-  "/path/to/command -with args"\n
-
-There's no restriction on what configuration variables are visible.
-There's also no method for altering the configuration.
-
-If you would like your OS daemon to be restarted in the event that
-the configuration changes, you can send the following messages::
-
-  ["register", $(SECTION)]\n
-
-When anything in that section changes, your OS process will be
-rebooted so it can pick up the new configuration settings. If you
-want to listen for changes on a specific key, you can send something
-like::
-
-  ["register", $(SECTION), $(KEY)]\n
-
-In this case, CouchDB will only restart your daemon if that exact
-section/key pair changes, instead of anything in that entire section.
-
-Logging commands look like::
-
-  ["log", $(JSON_MESSAGE)]\n
-
-Where ``$(JSON_MESSAGE)`` is arbitrary JSON data. These messages are
-logged at the 'info' level. If you want to log at a different level
-you can pass messages like such::
-
-  ["log", $(JSON_MESSAGE), {"level": $(LEVEL)}]\n
-
-Where ``$(LEVEL)`` is one of "debug", "info", or "error".
-
-When implementing a daemon process to be managed by CouchDB you
-should remember to use a method like checking the parent process
-id or if stdin has been closed. These flags can tell you if
-your daemon process has been orphaned so you can exit cleanly.
-
-There is no interactivity between CouchDB and the running process, but
-you can use the OS Daemons service to create new HTTP servers and
-responders and then use the new proxy service to redirect requests and
-output to the CouchDB managed service. For more information on proxying,
-see :ref:`http-proxying`. For further background on the OS Daemon service, see
-`CouchDB Externals API`_.
-
-.. _CouchDB Externals API: http://davispj.com/2010/09/26/new-couchdb-externals-api.html
-
-
-.. _config/os_daemons_settings:
-
-``[os_daemon_settings]`` :: OS Daemons settings
-===============================================
-
-.. _config/os_daemons_settings/max_retries:
-
-``max_retries`` :: Maximum restart retries
-------------------------------------------
-
-Specifies maximum attempts to run :ref:`os_daemon <config/os_daemons>` before
-mark him halted::
-
-  [os_daemon_settings]
-  max_retries = 3
-
-
-.. _config/os_daemons_settings/retry_time:
-
-``retry_time`` :: Delay between restart attempts
-------------------------------------------------
-
-Delay in seconds between :ref:`os_daemon <config/os_daemons>` restarts::
-
-  [os_daemon_settings]
-  retry_time = 5
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/af75771f/share/doc/src/config/update-notification.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/update-notification.rst b/share/doc/src/config/update-notification.rst
deleted file mode 100644
index 9f4b1ef..0000000
--- a/share/doc/src/config/update-notification.rst
+++ /dev/null
@@ -1,64 +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.
-
-.. highlight:: ini
-
-.. TODO: move `update-notification` reference to special article about this
-   feature
-
-.. _update-notifications:
-.. _config/update-notification:
-
-``[update_notification]`` :: Update notifications
-=================================================
-
-CouchDB is able to spawn OS processes to notify them about recent databases
-updates. The notifications are in form of JSON messages sent as a line of text,
-terminated by ``CR`` (``\n``) character, to the OS processes through `stdout`::
-
-  [update_notification]
-  ;unique notifier name=/full/path/to/exe -with "cmd line arg"
-  index_updater = ruby /usr/local/bin/index_updater.rb
-
-
-The update notification messages are depend upon of event type:
-
-- **Database created**:
-
-  .. code-block:: javascript
-
-    {"type":"created","db":"dbname"}
-
-
-- **Database updated**:  this event raises when any document gets updated for
-  specified database:
-
-  .. code-block:: javascript
-
-    {"type":"updated","db":"dbname"}
-
-
-- **Design document updated**: for design document updates there is special
-  event raised in additional to regular db update one:
-
-  .. code-block:: javascript
-
-    {"type":"ddoc_updated","db":"dbname","id":"_design/ddoc_name"}
-
-
-- **Database deleted**:
-
-  .. code-block:: javascript
-
-    {"type":"deleted","db":"dbname"}
-
-.. note:: New line (``\n``) trailing character was removed from examples.


[03/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Group replication articles.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/4ecafebf
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/4ecafebf
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/4ecafebf

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 4ecafebf46b97a93d479628781d8e94e5ebad414
Parents: 8d4acc0
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 22:38:30 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am               |  15 +-
 share/doc/src/index.rst                   |   3 +-
 share/doc/src/replication.rst             |  95 ------
 share/doc/src/replications/index.rst      |  35 +++
 share/doc/src/replications/intro.rst      |  95 ++++++
 share/doc/src/replications/replicator.rst | 383 +++++++++++++++++++++++++
 share/doc/src/replicator.rst              | 383 -------------------------
 7 files changed, 523 insertions(+), 486 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/4ecafebf/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index ed8ef6c..1580f85 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -68,6 +68,9 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
+    html/_sources/replications/index.txt \
+    html/_sources/replications/intro.txt \
+    html/_sources/replications/replicator.txt \
     html/_sources/changelog.txt \
     html/_sources/changes.txt \
     html/_sources/contributing.txt \
@@ -76,8 +79,6 @@ html_files = \
     html/_sources/intro.txt \
     html/_sources/json-structure.txt \
     html/_sources/query-servers.txt \
-    html/_sources/replication.txt \
-    html/_sources/replicator.txt \
     html/_static/ajax-loader.gif \
     html/_static/basic.css \
     html/_static/comment-bright.png \
@@ -124,6 +125,9 @@ html_files = \
     html/config/services.html \
     html/config/intro.html \
     html/config/proxying.html \
+    html/replications/index.html \
+    html/replications/intro.html \
+    html/replications/replicator.html \
     html/changelog.html \
     html/changes.html \
     html/ddocs.html \
@@ -131,8 +135,6 @@ html_files = \
     html/intro.html \
     html/json-structure.html \
     html/query-servers.html \
-    html/replication.html \
-    html/replicator.html \
     html/objects.inv \
     html/genindex.html \
     html/search.html \
@@ -178,6 +180,9 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
+    ../src/replications/index.rst \
+    ../src/replications/intro.rst \
+    ../src/replications/replicator.rst \
     ../src/changelog.rst \
     ../src/changes.rst \
     ../src/contributing.rst \
@@ -186,8 +191,6 @@ src_files = \
     ../src/intro.rst \
     ../src/json-structure.rst \
     ../src/query-servers.rst \
-    ../src/replication.rst \
-    ../src/replicator.rst \
     ../src/conf.py
 
 src_files_html = \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/4ecafebf/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index eef82ca..4a3a51b 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -29,8 +29,7 @@ Contents
 
     intro
     config/index
-    replication
-    replicator
+    replications/index
     ddocs
     query-servers
     changes

http://git-wip-us.apache.org/repos/asf/couchdb/blob/4ecafebf/share/doc/src/replication.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication.rst b/share/doc/src/replication.rst
deleted file mode 100644
index e109858..0000000
--- a/share/doc/src/replication.rst
+++ /dev/null
@@ -1,95 +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.
-
-.. _replication:
-
-Replication
-===========
-
-One of CouchDB's strengths is the ability to synchronize two copies of the same
-database. This enables users to distribute data across several nodes or
-datacenters, but also to move data more closely to clients.
-
-Replication involves a source and a destination database, which can be one the
-same or on different CouchDB instances. The aim of the replication is that at
-the end of the process, all active documents on the source database are also in
-the destination database and all documents that were deleted in the source
-databases are also deleted on the destination database (if they even existed).
-
-
-Triggering Replication
-----------------------
-
-Replication is controlled through documents in the :ref:`replicator`, where
-each document describes one replication process (see
-:ref:`replication-settings`).
-
-A replication is triggered by storing a replication document in the replicator
-database. Its status can be inspected through the active tasks API (see
-:ref:`api/misc/active_tasks` and :ref:`replication-status`). A replication can be
-stopped by deleting the document, or by updating it with its `cancel` property
-set to `true`.
-
-
-Replication Procedure
----------------------
-
-During replication, CouchDB will compare the source and the destination
-database to determine which documents differ between the source and the
-destination database. It does so by following the :ref:`changes` on the source
-and comparing the documents to the destination. Changes are submitted to the
-destination in batches where they can introduce conflicts. Documents that
-already exist on the destination in the same revision are not transferred. As
-the deletion of documents is represented by a new revision, a document deleted
-on the source will also be deleted on the target.
-
-A replication task will finish once it reaches the end of the changes feed. If
-its `continuous` property is set to true, it will wait for new changes to
-appear until the task is cancelled. Replication tasks also create checkpoint
-documents on the destination to ensure that a restarted task can continue from
-where it stopped, for example after it has crashed.
-
-When a replication task is initiated on the sending node, it is called *push*
-replication, if it is initiated by the receiving node, it is called *pull*
-replication.
-
-
-Master - Master replication
----------------------------
-
-One replication task will only transfer changes in one direction. To achieve
-master-master replication it is possible to set up two replication tasks in
-different directions. When a change is replication from database A to B by the
-first task, the second will discover that the new change on B already exists in
-A and will wait for further changes.
-
-
-Controlling which Documents to Replicate
-----------------------------------------
-
-There are two ways for controlling which documents are replicated, and which
-are skipped. *Local* documents are never replicated (see :ref:`api/local`).
-
-Additionally, :ref:`filterfun` can be used in a replication documents (see
-:ref:`replication-settings`). The replication task will then evaluate
-the filter function for each document in the changes feed. The document will
-only be replicated if the filter returns `true`.
-
-
-Migrating Data to Clients
--------------------------
-
-Replication can be especially useful for bringing data closer to clients.
-`PouchDB <http://pouchdb.com/>`_ implements the replication algorithm of CouchDB
-in JavaScript, making it possible to make data from a CouchDB database
-available in an offline browser application, and synchronize changes back to
-CouchDB.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/4ecafebf/share/doc/src/replications/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/index.rst b/share/doc/src/replications/index.rst
new file mode 100644
index 0000000..b626bc6
--- /dev/null
+++ b/share/doc/src/replications/index.rst
@@ -0,0 +1,35 @@
+.. 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.
+
+.. _replication:
+
+================
+Data Replication
+================
+
+The replication is an incremental one way process involving two databases
+(a source and a destination).
+
+The aim of the replication is that at the end of the process, all active
+documents on the source database are also in the destination database and all
+documents that were deleted in the source databases are also deleted (if exists)
+on the destination database.
+
+The replication process only copies the last revision of a document, so all
+previous revisions that were only on the source database are not copied to the
+destination database.
+
+.. toctree::
+   :maxdepth: 2
+
+   intro
+   replicator

http://git-wip-us.apache.org/repos/asf/couchdb/blob/4ecafebf/share/doc/src/replications/intro.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/intro.rst b/share/doc/src/replications/intro.rst
new file mode 100644
index 0000000..f9c81e2
--- /dev/null
+++ b/share/doc/src/replications/intro.rst
@@ -0,0 +1,95 @@
+.. 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.
+
+.. _replication/intro:
+
+Introduction Into Replications
+==============================
+
+One of CouchDB's strengths is the ability to synchronize two copies of the same
+database. This enables users to distribute data across several nodes or
+datacenters, but also to move data more closely to clients.
+
+Replication involves a source and a destination database, which can be one the
+same or on different CouchDB instances. The aim of the replication is that at
+the end of the process, all active documents on the source database are also in
+the destination database and all documents that were deleted in the source
+databases are also deleted on the destination database (if they even existed).
+
+
+Triggering Replication
+----------------------
+
+Replication is controlled through documents in the :ref:`replicator`, where
+each document describes one replication process (see
+:ref:`replication-settings`).
+
+A replication is triggered by storing a replication document in the replicator
+database. Its status can be inspected through the active tasks API (see
+:ref:`api/misc/active_tasks` and :ref:`replication-status`). A replication can be
+stopped by deleting the document, or by updating it with its `cancel` property
+set to `true`.
+
+
+Replication Procedure
+---------------------
+
+During replication, CouchDB will compare the source and the destination
+database to determine which documents differ between the source and the
+destination database. It does so by following the :ref:`changes` on the source
+and comparing the documents to the destination. Changes are submitted to the
+destination in batches where they can introduce conflicts. Documents that
+already exist on the destination in the same revision are not transferred. As
+the deletion of documents is represented by a new revision, a document deleted
+on the source will also be deleted on the target.
+
+A replication task will finish once it reaches the end of the changes feed. If
+its `continuous` property is set to true, it will wait for new changes to
+appear until the task is cancelled. Replication tasks also create checkpoint
+documents on the destination to ensure that a restarted task can continue from
+where it stopped, for example after it has crashed.
+
+When a replication task is initiated on the sending node, it is called *push*
+replication, if it is initiated by the receiving node, it is called *pull*
+replication.
+
+
+Master - Master replication
+---------------------------
+
+One replication task will only transfer changes in one direction. To achieve
+master-master replication it is possible to set up two replication tasks in
+different directions. When a change is replication from database A to B by the
+first task, the second will discover that the new change on B already exists in
+A and will wait for further changes.
+
+
+Controlling which Documents to Replicate
+----------------------------------------
+
+There are two ways for controlling which documents are replicated, and which
+are skipped. *Local* documents are never replicated (see :ref:`api/local`).
+
+Additionally, :ref:`filterfun` can be used in a replication documents (see
+:ref:`replication-settings`). The replication task will then evaluate
+the filter function for each document in the changes feed. The document will
+only be replicated if the filter returns `true`.
+
+
+Migrating Data to Clients
+-------------------------
+
+Replication can be especially useful for bringing data closer to clients.
+`PouchDB <http://pouchdb.com/>`_ implements the replication algorithm of CouchDB
+in JavaScript, making it possible to make data from a CouchDB database
+available in an offline browser application, and synchronize changes back to
+CouchDB.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/4ecafebf/share/doc/src/replications/replicator.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/replicator.rst b/share/doc/src/replications/replicator.rst
new file mode 100644
index 0000000..1a40c65
--- /dev/null
+++ b/share/doc/src/replications/replicator.rst
@@ -0,0 +1,383 @@
+.. 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.
+
+.. _replicator:
+
+Replicator Database
+===================
+
+A database where you ``PUT``/``POST`` documents to trigger replications
+and you ``DELETE`` to cancel ongoing replications. These documents have
+exactly the same content as the JSON objects we used to ``POST`` to
+``_replicate`` (fields ``source``, ``target``, ``create_target``,
+``continuous``, ``doc_ids``, ``filter``, ``query_params``.
+
+Replication documents can have a user defined ``_id``. Design documents
+(and ``_local`` documents) added to the replicator database are ignored.
+
+The default name of this database is ``_replicator``. The name can be
+changed in the ``local.ini`` configuration, section ``[replicator]``,
+parameter ``db``.
+
+Basics
+------
+
+Let's say you PUT the following document into ``_replicator``:
+
+.. code-block:: javascript
+
+    {
+        "_id": "my_rep",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "create_target":  true
+    }
+
+In the couch log you'll see 2 entries like these:
+
+.. code-block:: text
+
+    [Thu, 17 Feb 2011 19:43:59 GMT] [info] [<0.291.0>] Document `my_rep` triggered replication `c0ebe9256695ff083347cbf95f93e280+create_target`
+    [Thu, 17 Feb 2011 19:44:37 GMT] [info] [<0.124.0>] Replication `c0ebe9256695ff083347cbf95f93e280+create_target` finished (triggered by document `my_rep`)
+
+As soon as the replication is triggered, the document will be updated by
+CouchDB with 3 new fields:
+
+.. code-block:: javascript
+
+    {
+        "_id": "my_rep",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "create_target":  true,
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297974122
+    }
+
+Special fields set by the replicator start with the prefix
+``_replication_``.
+
+-  ``_replication_id``
+
+   The ID internally assigned to the replication. This is also the ID
+   exposed by ``/_active_tasks``.
+
+-  ``_replication_state``
+
+   The current state of the replication.
+
+-  ``_replication_state_time``
+
+   A Unix timestamp (number of seconds since 1 Jan 1970) that tells us
+   when the current replication state (marked in ``_replication_state``)
+   was set.
+
+When the replication finishes, it will update the ``_replication_state``
+field (and ``_replication_state_time``) with the value ``completed``, so
+the document will look like:
+
+.. code-block:: javascript
+
+    {
+        "_id": "my_rep",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "create_target":  true,
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "completed",
+        "_replication_state_time":  1297974122
+    }
+
+When an error happens during replication, the ``_replication_state``
+field is set to ``error`` (and ``_replication_state_time`` gets updated of
+course).
+
+When you PUT/POST a document to the ``_replicator`` database, CouchDB
+will attempt to start the replication up to 10 times (configurable under
+``[replicator]``, parameter ``max_replication_retry_count``). If it
+fails on the first attempt, it waits 5 seconds before doing a second
+attempt. If the second attempt fails, it waits 10 seconds before doing a
+third attempt. If the third attempt fails, it waits 20 seconds before
+doing a fourth attempt (each attempt doubles the previous wait period).
+When an attempt fails, the Couch log will show you something like:
+
+.. code-block:: text
+
+    [error] [<0.149.0>] Error starting replication `67c1bb92010e7abe35d7d629635f18b6+create_target` (document `my_rep_2`): {db_not_found,<<"could not open http://myserver:5986/foo/">>
+
+.. note::
+   The ``_replication_state`` field is only set to ``error`` when all
+   the attempts were unsuccessful.
+
+There are only 3 possible values for the ``_replication_state`` field:
+``triggered``, ``completed`` and ``error``. Continuous replications
+never get their state set to ``completed``.
+
+Documents describing the same replication
+-----------------------------------------
+
+Lets suppose 2 documents are added to the ``_replicator`` database in
+the following order:
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_A",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar"
+    }
+
+and
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_B",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar"
+    }
+
+Both describe exactly the same replication (only their ``_ids`` differ).
+In this case document ``doc_A`` triggers the replication, getting
+updated by CouchDB with the fields ``_replication_state``,
+``_replication_state_time`` and ``_replication_id``, just like it was
+described before. Document ``doc_B`` however, is only updated with one
+field, the ``_replication_id`` so it will look like this:
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_B",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280"
+    }
+
+While document ``doc_A`` will look like this:
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_A",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297974122
+    }
+
+Note that both document get exactly the same value for the
+``_replication_id`` field. This way you can identify which documents
+refer to the same replication - you can for example define a view which
+maps replication IDs to document IDs.
+
+Canceling replications
+----------------------
+
+To cancel a replication simply ``DELETE`` the document which triggered
+the replication. The Couch log will show you an entry like the
+following:
+
+.. code-block:: text
+
+    [Thu, 17 Feb 2011 20:16:29 GMT] [info] [<0.125.0>] Stopped replication `c0ebe9256695ff083347cbf95f93e280+continuous+create_target` because replication document `doc_A` was deleted
+
+.. note::
+   You need to ``DELETE`` the document that triggered the replication.
+   ``DELETE``-ing another document that describes the same replication
+   but did not trigger it, will not cancel the replication.
+
+Server restart
+--------------
+
+When CouchDB is restarted, it checks its ``_replicator`` database and
+restarts any replication that is described by a document that either has
+its ``_replication_state`` field set to ``triggered`` or it doesn't have
+yet the ``_replication_state`` field set.
+
+.. note::
+   Continuous replications always have a ``_replication_state`` field
+   with the value ``triggered``, therefore they're always restarted
+   when CouchDB is restarted.
+
+Changing the Replicator Database
+--------------------------------
+
+Imagine your replicator database (default name is ``_replicator``) has the
+two following documents that represent pull replications from servers A
+and B:
+
+.. code-block:: javascript
+
+    {
+        "_id": "rep_from_A",
+        "source":  "http://aserver.com:5984/foo",
+        "target":  "foo_a",
+        "continuous":  true,
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297971311
+    }
+
+.. code-block:: javascript
+
+    {
+        "_id": "rep_from_B",
+        "source":  "http://bserver.com:5984/foo",
+        "target":  "foo_b",
+        "continuous":  true,
+        "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297974122
+    }
+
+Now without stopping and restarting CouchDB, you change the name of the
+replicator database to ``another_replicator_db``:
+
+.. code-block:: bash
+
+    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"another_replicator_db"'
+    "_replicator"
+
+As soon as this is done, both pull replications defined before, are
+stopped. This is explicitly mentioned in CouchDB's log:
+
+.. code-block:: text
+
+    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.104.0>] Stopping all ongoing replications because the replicator database was deleted or changed
+    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.127.0>] 127.0.0.1 - - PUT /_config/replicator/db 200
+
+Imagine now you add a replication document to the new replicator
+database named ``another_replicator_db``:
+
+.. code-block:: javascript
+
+    {
+        "_id": "rep_from_X",
+        "source":  "http://xserver.com:5984/foo",
+        "target":  "foo_x",
+        "continuous":  true
+    }
+
+From now own you have a single replication going on in your system: a
+pull replication pulling from server X. Now you change back the
+replicator database to the original one ``_replicator``:
+
+::
+
+    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"_replicator"'
+    "another_replicator_db"
+
+Immediately after this operation, the replication pulling from server X
+will be stopped and the replications defined in the ``_replicator``
+database (pulling from servers A and B) will be resumed.
+
+Changing again the replicator database to ``another_replicator_db`` will
+stop the pull replications pulling from servers A and B, and resume the
+pull replication pulling from server X.
+
+Replicating the replicator database
+-----------------------------------
+
+Imagine you have in server C a replicator database with the two
+following pull replication documents in it:
+
+.. code-block:: javascript
+
+    {
+         "_id": "rep_from_A",
+         "source":  "http://aserver.com:5984/foo",
+         "target":  "foo_a",
+         "continuous":  true,
+         "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+         "_replication_state":  "triggered",
+         "_replication_state_time":  1297971311
+    }
+
+.. code-block:: javascript
+
+    {
+         "_id": "rep_from_B",
+         "source":  "http://bserver.com:5984/foo",
+         "target":  "foo_b",
+         "continuous":  true,
+         "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
+         "_replication_state":  "triggered",
+         "_replication_state_time":  1297974122
+    }
+
+Now you would like to have the same pull replications going on in server
+D, that is, you would like to have server D pull replicating from
+servers A and B. You have two options:
+
+-  Explicitly add two documents to server's D replicator database
+
+-  Replicate server's C replicator database into server's D replicator
+   database
+
+Both alternatives accomplish exactly the same goal.
+
+Delegations
+-----------
+
+Replication documents can have a custom ``user_ctx`` property. This
+property defines the user context under which a replication runs. For
+the old way of triggering replications (POSTing to ``/_replicate/``),
+this property was not needed (it didn't exist in fact) - this is because
+at the moment of triggering the replication it has information about the
+authenticated user. With the replicator database, since it's a regular
+database, the information about the authenticated user is only present
+at the moment the replication document is written to the database - the
+replicator database implementation is like a ``_changes`` feed consumer
+(with ``?include_docs=true``) that reacts to what was written to the
+replicator database - in fact this feature could be implemented with an
+external script/program. This implementation detail implies that for non
+admin users, a ``user_ctx`` property, containing the user's name and a
+subset of his/her roles, must be defined in the replication document.
+This is ensured by the document update validation function present in
+the default design document of the replicator database. This validation
+function also ensure that a non admin user can set a user name property
+in the ``user_ctx`` property that doesn't match his/her own name (same
+principle applies for the roles).
+
+For admins, the ``user_ctx`` property is optional, and if it's missing
+it defaults to a user context with name null and an empty list of roles
+- this mean design documents will not be written to local targets. If
+writing design documents to local targets is desired, the a user context
+with the roles ``_admin`` must be set explicitly.
+
+Also, for admins the ``user_ctx`` property can be used to trigger a
+replication on behalf of another user. This is the user context that
+will be passed to local target database document validation functions.
+
+.. note::
+   The ``user_ctx`` property only has effect for local endpoints.
+
+Example delegated replication document:
+
+.. code-block:: javascript
+
+    {
+         "_id": "my_rep",
+         "source":  "http://bserver.com:5984/foo",
+         "target":  "bar",
+         "continuous":  true,
+         "user_ctx": {
+              "name": "joe",
+              "roles": ["erlanger", "researcher"]
+         }
+    }
+
+As stated before, for admins the ``user_ctx`` property is optional, while
+for regular (non admin) users it's mandatory. When the roles property of
+``user_ctx`` is missing, it defaults to the empty list ``[ ]``.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/4ecafebf/share/doc/src/replicator.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replicator.rst b/share/doc/src/replicator.rst
deleted file mode 100644
index 1a40c65..0000000
--- a/share/doc/src/replicator.rst
+++ /dev/null
@@ -1,383 +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.
-
-.. _replicator:
-
-Replicator Database
-===================
-
-A database where you ``PUT``/``POST`` documents to trigger replications
-and you ``DELETE`` to cancel ongoing replications. These documents have
-exactly the same content as the JSON objects we used to ``POST`` to
-``_replicate`` (fields ``source``, ``target``, ``create_target``,
-``continuous``, ``doc_ids``, ``filter``, ``query_params``.
-
-Replication documents can have a user defined ``_id``. Design documents
-(and ``_local`` documents) added to the replicator database are ignored.
-
-The default name of this database is ``_replicator``. The name can be
-changed in the ``local.ini`` configuration, section ``[replicator]``,
-parameter ``db``.
-
-Basics
-------
-
-Let's say you PUT the following document into ``_replicator``:
-
-.. code-block:: javascript
-
-    {
-        "_id": "my_rep",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "create_target":  true
-    }
-
-In the couch log you'll see 2 entries like these:
-
-.. code-block:: text
-
-    [Thu, 17 Feb 2011 19:43:59 GMT] [info] [<0.291.0>] Document `my_rep` triggered replication `c0ebe9256695ff083347cbf95f93e280+create_target`
-    [Thu, 17 Feb 2011 19:44:37 GMT] [info] [<0.124.0>] Replication `c0ebe9256695ff083347cbf95f93e280+create_target` finished (triggered by document `my_rep`)
-
-As soon as the replication is triggered, the document will be updated by
-CouchDB with 3 new fields:
-
-.. code-block:: javascript
-
-    {
-        "_id": "my_rep",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "create_target":  true,
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297974122
-    }
-
-Special fields set by the replicator start with the prefix
-``_replication_``.
-
--  ``_replication_id``
-
-   The ID internally assigned to the replication. This is also the ID
-   exposed by ``/_active_tasks``.
-
--  ``_replication_state``
-
-   The current state of the replication.
-
--  ``_replication_state_time``
-
-   A Unix timestamp (number of seconds since 1 Jan 1970) that tells us
-   when the current replication state (marked in ``_replication_state``)
-   was set.
-
-When the replication finishes, it will update the ``_replication_state``
-field (and ``_replication_state_time``) with the value ``completed``, so
-the document will look like:
-
-.. code-block:: javascript
-
-    {
-        "_id": "my_rep",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "create_target":  true,
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "completed",
-        "_replication_state_time":  1297974122
-    }
-
-When an error happens during replication, the ``_replication_state``
-field is set to ``error`` (and ``_replication_state_time`` gets updated of
-course).
-
-When you PUT/POST a document to the ``_replicator`` database, CouchDB
-will attempt to start the replication up to 10 times (configurable under
-``[replicator]``, parameter ``max_replication_retry_count``). If it
-fails on the first attempt, it waits 5 seconds before doing a second
-attempt. If the second attempt fails, it waits 10 seconds before doing a
-third attempt. If the third attempt fails, it waits 20 seconds before
-doing a fourth attempt (each attempt doubles the previous wait period).
-When an attempt fails, the Couch log will show you something like:
-
-.. code-block:: text
-
-    [error] [<0.149.0>] Error starting replication `67c1bb92010e7abe35d7d629635f18b6+create_target` (document `my_rep_2`): {db_not_found,<<"could not open http://myserver:5986/foo/">>
-
-.. note::
-   The ``_replication_state`` field is only set to ``error`` when all
-   the attempts were unsuccessful.
-
-There are only 3 possible values for the ``_replication_state`` field:
-``triggered``, ``completed`` and ``error``. Continuous replications
-never get their state set to ``completed``.
-
-Documents describing the same replication
------------------------------------------
-
-Lets suppose 2 documents are added to the ``_replicator`` database in
-the following order:
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_A",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar"
-    }
-
-and
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_B",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar"
-    }
-
-Both describe exactly the same replication (only their ``_ids`` differ).
-In this case document ``doc_A`` triggers the replication, getting
-updated by CouchDB with the fields ``_replication_state``,
-``_replication_state_time`` and ``_replication_id``, just like it was
-described before. Document ``doc_B`` however, is only updated with one
-field, the ``_replication_id`` so it will look like this:
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_B",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280"
-    }
-
-While document ``doc_A`` will look like this:
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_A",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297974122
-    }
-
-Note that both document get exactly the same value for the
-``_replication_id`` field. This way you can identify which documents
-refer to the same replication - you can for example define a view which
-maps replication IDs to document IDs.
-
-Canceling replications
-----------------------
-
-To cancel a replication simply ``DELETE`` the document which triggered
-the replication. The Couch log will show you an entry like the
-following:
-
-.. code-block:: text
-
-    [Thu, 17 Feb 2011 20:16:29 GMT] [info] [<0.125.0>] Stopped replication `c0ebe9256695ff083347cbf95f93e280+continuous+create_target` because replication document `doc_A` was deleted
-
-.. note::
-   You need to ``DELETE`` the document that triggered the replication.
-   ``DELETE``-ing another document that describes the same replication
-   but did not trigger it, will not cancel the replication.
-
-Server restart
---------------
-
-When CouchDB is restarted, it checks its ``_replicator`` database and
-restarts any replication that is described by a document that either has
-its ``_replication_state`` field set to ``triggered`` or it doesn't have
-yet the ``_replication_state`` field set.
-
-.. note::
-   Continuous replications always have a ``_replication_state`` field
-   with the value ``triggered``, therefore they're always restarted
-   when CouchDB is restarted.
-
-Changing the Replicator Database
---------------------------------
-
-Imagine your replicator database (default name is ``_replicator``) has the
-two following documents that represent pull replications from servers A
-and B:
-
-.. code-block:: javascript
-
-    {
-        "_id": "rep_from_A",
-        "source":  "http://aserver.com:5984/foo",
-        "target":  "foo_a",
-        "continuous":  true,
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297971311
-    }
-
-.. code-block:: javascript
-
-    {
-        "_id": "rep_from_B",
-        "source":  "http://bserver.com:5984/foo",
-        "target":  "foo_b",
-        "continuous":  true,
-        "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297974122
-    }
-
-Now without stopping and restarting CouchDB, you change the name of the
-replicator database to ``another_replicator_db``:
-
-.. code-block:: bash
-
-    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"another_replicator_db"'
-    "_replicator"
-
-As soon as this is done, both pull replications defined before, are
-stopped. This is explicitly mentioned in CouchDB's log:
-
-.. code-block:: text
-
-    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.104.0>] Stopping all ongoing replications because the replicator database was deleted or changed
-    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.127.0>] 127.0.0.1 - - PUT /_config/replicator/db 200
-
-Imagine now you add a replication document to the new replicator
-database named ``another_replicator_db``:
-
-.. code-block:: javascript
-
-    {
-        "_id": "rep_from_X",
-        "source":  "http://xserver.com:5984/foo",
-        "target":  "foo_x",
-        "continuous":  true
-    }
-
-From now own you have a single replication going on in your system: a
-pull replication pulling from server X. Now you change back the
-replicator database to the original one ``_replicator``:
-
-::
-
-    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"_replicator"'
-    "another_replicator_db"
-
-Immediately after this operation, the replication pulling from server X
-will be stopped and the replications defined in the ``_replicator``
-database (pulling from servers A and B) will be resumed.
-
-Changing again the replicator database to ``another_replicator_db`` will
-stop the pull replications pulling from servers A and B, and resume the
-pull replication pulling from server X.
-
-Replicating the replicator database
------------------------------------
-
-Imagine you have in server C a replicator database with the two
-following pull replication documents in it:
-
-.. code-block:: javascript
-
-    {
-         "_id": "rep_from_A",
-         "source":  "http://aserver.com:5984/foo",
-         "target":  "foo_a",
-         "continuous":  true,
-         "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-         "_replication_state":  "triggered",
-         "_replication_state_time":  1297971311
-    }
-
-.. code-block:: javascript
-
-    {
-         "_id": "rep_from_B",
-         "source":  "http://bserver.com:5984/foo",
-         "target":  "foo_b",
-         "continuous":  true,
-         "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
-         "_replication_state":  "triggered",
-         "_replication_state_time":  1297974122
-    }
-
-Now you would like to have the same pull replications going on in server
-D, that is, you would like to have server D pull replicating from
-servers A and B. You have two options:
-
--  Explicitly add two documents to server's D replicator database
-
--  Replicate server's C replicator database into server's D replicator
-   database
-
-Both alternatives accomplish exactly the same goal.
-
-Delegations
------------
-
-Replication documents can have a custom ``user_ctx`` property. This
-property defines the user context under which a replication runs. For
-the old way of triggering replications (POSTing to ``/_replicate/``),
-this property was not needed (it didn't exist in fact) - this is because
-at the moment of triggering the replication it has information about the
-authenticated user. With the replicator database, since it's a regular
-database, the information about the authenticated user is only present
-at the moment the replication document is written to the database - the
-replicator database implementation is like a ``_changes`` feed consumer
-(with ``?include_docs=true``) that reacts to what was written to the
-replicator database - in fact this feature could be implemented with an
-external script/program. This implementation detail implies that for non
-admin users, a ``user_ctx`` property, containing the user's name and a
-subset of his/her roles, must be defined in the replication document.
-This is ensured by the document update validation function present in
-the default design document of the replicator database. This validation
-function also ensure that a non admin user can set a user name property
-in the ``user_ctx`` property that doesn't match his/her own name (same
-principle applies for the roles).
-
-For admins, the ``user_ctx`` property is optional, and if it's missing
-it defaults to a user context with name null and an empty list of roles
-- this mean design documents will not be written to local targets. If
-writing design documents to local targets is desired, the a user context
-with the roles ``_admin`` must be set explicitly.
-
-Also, for admins the ``user_ctx`` property can be used to trigger a
-replication on behalf of another user. This is the user context that
-will be passed to local target database document validation functions.
-
-.. note::
-   The ``user_ctx`` property only has effect for local endpoints.
-
-Example delegated replication document:
-
-.. code-block:: javascript
-
-    {
-         "_id": "my_rep",
-         "source":  "http://bserver.com:5984/foo",
-         "target":  "bar",
-         "continuous":  true,
-         "user_ctx": {
-              "name": "joe",
-              "roles": ["erlanger", "researcher"]
-         }
-    }
-
-As stated before, for admins the ``user_ctx`` property is optional, while
-for regular (non admin) users it's mandatory. When the roles property of
-``user_ctx`` is missing, it defaults to the empty list ``[ ]``.


[36/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Import Fauxton docs.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/319bb8a9
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/319bb8a9
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/319bb8a9

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 319bb8a941b7dbaaa4f4a17fbff02287b8ca9422
Parents: 302783e
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 09:15:20 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am       |   9 ++
 share/doc/src/fauxton/addons.rst  | 199 +++++++++++++++++++++++++++++++++
 share/doc/src/fauxton/index.rst   |  23 ++++
 share/doc/src/fauxton/install.rst | 109 ++++++++++++++++++
 share/doc/src/index.rst           |   1 +
 5 files changed, 341 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/319bb8a9/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 4d198e7..26fdc5e 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -83,6 +83,9 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
+    html/_sources/fauxton/addons.txt \
+    html/_sources/fauxton/index.txt \
+    html/_sources/fauxton/install.txt \
     html/_sources/install/index.html \
     html/_sources/install/freebsd.html \
     html/_sources/install/gentoo.html \
@@ -163,6 +166,9 @@ html_files = \
     html/config/services.html \
     html/config/intro.html \
     html/config/proxying.html \
+    html/fauxton/addons.html \
+    html/fauxton/index.html \
+    html/fauxton/install.html \
     html/install/index.html \
     html/install/freebsd.html \
     html/install/gentoo.html \
@@ -241,6 +247,9 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
+    ../src/fauxton/addons.rst \
+    ../src/fauxton/index.rst \
+    ../src/fauxton/install.rst \
     ../src/install/index.rst \
     ../src/install/freebsd.rst \
     ../src/install/gentoo.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/319bb8a9/share/doc/src/fauxton/addons.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/fauxton/addons.rst b/share/doc/src/fauxton/addons.rst
new file mode 100644
index 0000000..0ca8254
--- /dev/null
+++ b/share/doc/src/fauxton/addons.rst
@@ -0,0 +1,199 @@
+.. 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.
+
+
+.. _fauxton/addons:
+
+===============
+Writting Addons
+===============
+
+Addons allow you to extend Fauxton for a specific use case. Usually, they
+have the following structure::
+
+  + my_addon/
+  | ---+ assets [optional]
+  |    \ ---+ less
+  |         \ ---- my_addon.less
+  | ---+ templates/
+  |    \ ---- my_addon.html - underscore template fragments
+  | ---- resources.js - models and collections of the addon
+  | ---- routes.js - URL routing for the addon
+  | ---- views.js - views that the model provides
+
+
+Generating an Addon
+===================
+
+We have a `grunt-init` template that lets you create a skeleton addon,
+including all the boiler plate code. Run ``grunt-init tasks/addon`` and answer
+the questions it asks to create an addon::
+
+    ± grunt-init tasks/addon
+    path.existsSync is now called `fs.existsSync`.
+    Running "addon" task
+
+    Please answer the following:
+    [?] Add on Name (WickedCool) SuperAddon
+    [?] Location of add ons (app/addons)
+    [?] Do you need an assets folder?(for .less) (y/N)
+    [?] Do you need to make any changes to the above before continuing? (y/N)
+
+    Created addon SuperAddon in app/addons
+
+    Done, without errors.
+
+Once the addon is created add the name to the settings.json file to get it
+compiled and added on the next install.
+
+Routes and hooks
+================
+
+An addon can insert itself into Fauxton in two ways; via a route or via a hook.
+
+Routes
+------
+
+An addon will override an existing route should one exist, but in all other
+ways is just a normal backbone `route/view`. This is how you would add a whole
+new feature.
+
+Hooks
+-----
+
+Hooks let you modify/extend an existing feature. They modify a DOM element by
+selector for a named set of routes, for example:
+
+.. code-block:: javascript
+
+    var Search = new FauxtonAPI.addon();
+    Search.hooks = {
+      // Render additional content into the sidebar
+      "#sidebar-content": {
+        routes:[
+          "database/:database/_design/:ddoc/_search/:search",
+          "database/:database/_design/:ddoc/_view/:view",
+          "database/:database/_:handler"],
+        callback: searchSidebar
+      }
+    };
+    return Search;
+
+adds the `searchSidebar` callback to `#sidebar-content` for three routes.
+
+Hello world Addon
+=================
+
+First create the addon skeleton::
+
+    ± bbb addon
+    path.existsSync is now called `fs.existsSync`.
+    Running "addon" task
+
+    Please answer the following:
+    [?] Add on Name (WickedCool) Hello
+    [?] Location of add ons (app/addons)
+    [?] Do you need to make any changes to the above before continuing? (y/N)
+
+    Created addon Hello in app/addons
+
+    Done, without errors.
+
+In `app/addons/hello/templates/hello.html` place:
+
+.. code-block:: html
+
+    <h1>Hello!</h1>
+
+Next, we'll defined a simple view in `resources.js` (for more complex addons
+you may want to have a views.js) that renders that template:
+
+.. code-block:: javascript
+
+    define([
+      "app",
+      "api"
+    ],
+
+    function (app, FauxtonAPI) {
+      var Resources = {};
+
+      Resources.Hello = FauxtonAPI.View.extend({
+        template: "addons/hello/templates/hello"
+      });
+
+      return Resources;
+    });
+
+
+Then define a route in `routes.js` that the addon is accessible at:
+
+.. code-block:: javascript
+
+    define([
+      "app",
+      "api",
+      "addons/hello/resources"
+    ],
+
+    function(app, FauxtonAPI, Resources) {
+      var helloRoute = function () {
+        console.log('helloRoute callback yo');
+        return {
+          layout: "one_pane",
+          crumbs: [
+            {"name": "Hello","link": "_hello"}
+          ],
+          views: {
+            "#dashboard-content": new Resources.Hello({})
+          },
+          apiUrl: 'hello'
+        };
+      };
+
+      Routes = {
+        "_hello": helloRoute
+      };
+
+      return Routes;
+    });
+
+
+Then wire it all together in base.js:
+
+.. code-block:: javascript
+
+    define([
+      "app",
+      "api",
+      "addons/hello/routes"
+    ],
+
+    function(app, FauxtonAPI, HelloRoutes) {
+      var Hello = new FauxtonAPI.addon();
+      console.log('hello from hello');
+
+      Hello.initialize = function() {
+        FauxtonAPI.addHeaderLink({title: "Hello", href: "#_hello"});
+      };
+
+      Hello.Routes = HelloRoutes;
+      console.log(Hello);
+      return Hello;
+    });
+
+Once the code is in place include the add on in your `settings.json` so that it
+gets included by the `require` task. Your addon is included in one of three
+ways; a local path, a git URL or a name. Named plugins assume the plugin is in
+the Fauxton base directory, addons with a git URL will be cloned into the
+application, local paths will be copied. Addons included from a local path will
+be cleaned out by the clean task, others are left alone.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/319bb8a9/share/doc/src/fauxton/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/fauxton/index.rst b/share/doc/src/fauxton/index.rst
new file mode 100644
index 0000000..850ab0a
--- /dev/null
+++ b/share/doc/src/fauxton/index.rst
@@ -0,0 +1,23 @@
+.. 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.
+
+
+.. _fauxton:
+
+=======
+Fauxton
+=======
+
+.. toctree::
+
+   install
+   addons

http://git-wip-us.apache.org/repos/asf/couchdb/blob/319bb8a9/share/doc/src/fauxton/install.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/fauxton/install.rst b/share/doc/src/fauxton/install.rst
new file mode 100644
index 0000000..6805260
--- /dev/null
+++ b/share/doc/src/fauxton/install.rst
@@ -0,0 +1,109 @@
+.. 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.
+
+
+.. _fauxton/install:
+
+============
+Installation
+============
+
+A recent of `node.js`_ and `npm`_ is required.
+
+.. _node.js: http://nodejs.org/
+.. _npm: https://npmjs.org/doc/README.html
+
+Get the source
+--------------
+
+Clone the CouchDB repo::
+
+  $ git clone http://git-wip-us.apache.org/repos/asf/couchdb.git
+  $ cd couchdb
+
+
+Fauxton Setup
+-------------
+
+Install all dependencies::
+
+  couchdb/ $ cd src/fauxton
+  couchdb/src/fauxton/ $ npm install
+
+
+.. note::
+
+    To avoid a npm global install add ``node_modules/.bin`` to your path::
+
+      export PATH=./node_modules/.bin:$PATH
+
+    Or just use the wrappers in ``./bin/``.
+
+    Development mode, non minified files::
+
+      ./bin/grunt couchdebug
+
+    Or fully compiled install::
+
+      ./bin/grunt couchdb
+
+Dev Server
+----------
+
+Using the dev server is the easiest way to use Fauxton, specially when
+developing for it::
+
+    grunt dev
+
+Deploy Fauxton
+--------------
+
+Deploy Fauxton to your local CouchDB instance:
+
+    ./bin/grunt couchapp_deploy
+
+The Fauxton be available by http://localhost:5984/fauxton/_design/fauxton/index.html
+
+
+Understang Fauxton Code layout
+==============================
+
+Each bit of functionality is its own separate module or addon.
+
+All core modules are stored under `app/module` and any addons that are optional
+are under `app/addons`.
+
+We use `backbone.js`_ and `Backbone.layoutmanager`_ quite heavily, so best to
+get an idea how they work. Its best at this point to read through a couple of
+the modules and addons to get an idea of how they work.
+
+Two good starting points are `app/addon/config` and `app/modules/databases`.
+
+Each module must have a `base.js` file, this is read and compile when Fauxton is
+deployed.
+
+The `resource.js` file is usually for your ``Backbone.Models`` and
+``Backbone.Collections``, `view.js` for your ``Backbone.Views``.
+
+The `routes.js` is used to register a url path for your view along with what
+layout, data, breadcrumbs and api point is required for the view.
+
+.. _backbone.js: http://backbonejs.org/
+.. _Backbone.layoutmanager: https://github.com/tbranyen/backbone.layoutmanager
+
+
+ToDo items
+==========
+
+Checkout `JIRA`_  for a list of items to do.
+
+.. _JIRA: https://issues.apache.org/jira/browse/COUCHDB/component/12320406

http://git-wip-us.apache.org/repos/asf/couchdb/blob/319bb8a9/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index adabec1..6c80120 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -33,6 +33,7 @@ Contents
     replication/index
     ddocs
     query-server/index
+    fauxton/index
     api/index
     json-structure
     contributing


[28/50] [abbrv] Split API articles into small files focused on specific problem.

Posted by kx...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/ddoc/views.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/ddoc/views.rst b/share/doc/src/api/ddoc/views.rst
new file mode 100644
index 0000000..abc9e05
--- /dev/null
+++ b/share/doc/src/api/ddoc/views.rst
@@ -0,0 +1,708 @@
+.. 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.
+
+
+.. _api/ddoc/view:
+.. _api/ddoc/view.get:
+
+``GET /db/_design/design-doc/_view/view-name``
+==============================================
+
+* **Method**: ``GET /db/_design/design-doc/_view/view-name``
+* **Request**: None
+* **Response**: JSON of the documents returned by the view
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: descending
+
+    * **Description**:  Return the documents in descending by key order
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: endkey
+
+    * **Description**:  Stop returning records when the specified key is reached
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: endkey_docid
+
+    * **Description**:  Stop returning records when the specified document
+      ID is reached
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: group
+
+    * **Description**:  Group the results using the reduce function to a
+      group or single row
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: group_level
+
+    * **Description**:  Specify the group level to be used
+    * **Optional**: yes
+    * **Type**: numeric
+
+  * **Argument**: include_docs
+
+    * **Description**:  Include the full content of the documents in the return
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: inclusive_end
+
+    * **Description**:  Specifies whether the specified end key should be
+      included in the result
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: true
+
+  * **Argument**: key
+
+    * **Description**:  Return only documents that match the specified key
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: limit
+
+    * **Description**:  Limit the number of the returned documents to the
+      specified number
+    * **Optional**: yes
+    * **Type**: numeric
+
+  * **Argument**: reduce
+
+    * **Description**:  Use the reduction function
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: true
+
+  * **Argument**: skip
+
+    * **Description**:  Skip this number of records before starting to return
+      the results
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 0
+
+  * **Argument**: stale
+
+    * **Description**:  Allow the results from a stale view to be used
+    * **Optional**: yes
+    * **Type**: string
+    * **Default**:
+    * **Supported Values**
+
+      * **ok**: Allow stale views
+
+  * **Argument**: startkey
+
+    * **Description**:  Return records starting with the specified key
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: startkey_docid
+
+    * **Description**:  Return records starting with the specified document ID
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: update_seq
+
+    * **Description**:  Include the update sequence in the generated results
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+Executes the specified ``view-name`` from the specified ``design-doc``
+design document.
+
+Querying Views and Indexes
+--------------------------
+
+The definition of a view within a design document also creates an index
+based on the key information defined within each view. The production
+and use of the index significantly increases the speed of access and
+searching or selecting documents from the view.
+
+However, the index is not updated when new documents are added or
+modified in the database. Instead, the index is generated or updated,
+either when the view is first accessed, or when the view is accessed
+after a document has been updated. In each case, the index is updated
+before the view query is executed against the database.
+
+View indexes are updated incrementally in the following situations:
+
+-  A new document has been added to the database.
+
+-  A document has been deleted from the database.
+
+-  A document in the database has been updated.
+
+View indexes are rebuilt entirely when the view definition changes. To
+achieve this, a 'fingerprint' of the view definition is created when the
+design document is updated. If the fingerprint changes, then the view
+indexes are entirely rebuilt. This ensures that changes to the view
+definitions are reflected in the view indexes.
+
+.. note::
+   View index rebuilds occur when one view from the same the view group
+   (i.e. all the views defined within a single a design document) has
+   been determined as needing a rebuild. For example, if if you have a
+   design document with different views, and you update the database,
+   all three view indexes within the design document will be updated.
+
+Because the view is updated when it has been queried, it can result in a
+delay in returned information when the view is accessed, especially if
+there are a large number of documents in the database and the view index
+does not exist. There are a number of ways to mitigate, but not
+completely eliminate, these issues. These include:
+
+-  Create the view definition (and associated design documents) on your
+   database before allowing insertion or updates to the documents. If
+   this is allowed while the view is being accessed, the index can be
+   updated incrementally.
+
+-  Manually force a view request from the database. You can do this
+   either before users are allowed to use the view, or you can access
+   the view manually after documents are added or updated.
+
+-  Use the ``/db/_changes`` method to monitor for changes to the
+   database and then access the view to force the corresponding view
+   index to be updated. See :ref:`api/db/changes` for more information.
+
+-  Use a monitor with the ``update_notification`` section of the CouchDB
+   configuration file to monitor for changes to your database, and
+   trigger a view query to force the view to be updated. For more
+   information, see :ref:`update-notifications`.
+
+None of these can completely eliminate the need for the indexes to be
+rebuilt or updated when the view is accessed, but they may lessen the
+effects on end-users of the index update affecting the user experience.
+
+Another alternative is to allow users to access a 'stale' version of the
+view index, rather than forcing the index to be updated and displaying
+the updated results. Using a stale view may not return the latest
+information, but will return the results of the view query using an
+existing version of the index.
+
+For example, to access the existing stale view ``by_recipe`` in the
+``recipes`` design document:
+
+.. code-block:: text
+
+    http://couchdb:5984/recipes/_design/recipes/_view/by_recipe?stale=ok
+
+Accessing a stale view:
+
+-  Does not trigger a rebuild of the view indexes, even if there have
+   been changes since the last access.
+
+-  Returns the current version of the view index, if a current version
+   exists.
+
+-  Returns an empty result set if the given view index does exist.
+
+As an alternative, you use the ``update_after`` value to the ``stale``
+parameter. This causes the view to be returned as a stale view, but for
+the update process to be triggered after the view information has been
+returned to the client.
+
+In addition to using stale views, you can also make use of the
+``update_seq`` query argument. Using this query argument generates the
+view information including the update sequence of the database from
+which the view was generated. The returned value can be compared this to
+the current update sequence exposed in the database information
+(returned by :ref:`api/db.get`).
+
+Sorting Returned Rows
+---------------------
+
+Each element within the returned array is sorted using native UTF-8
+sorting according to the contents of the key portion of the emitted
+content. The basic order of output is as follows:
+
+-  ``null``
+
+-  ``false``
+
+-  ``true``
+
+-  Numbers
+
+-  Text (case sensitive, lowercase first)
+
+-  Arrays (according to the values of each element, in order)
+
+-  Objects (according to the values of keys, in key order)
+
+You can reverse the order of the returned view information by using the
+``descending`` query value set to true. For example, Retrieving the list
+of recipes using the ``by_title`` (limited to 5 records) view:
+
+.. code-block:: javascript
+
+    {
+       "offset" : 0,
+       "rows" : [
+          {
+             "id" : "3-tiersalmonspinachandavocadoterrine",
+             "key" : "3-tier salmon, spinach and avocado terrine",
+             "value" : [
+                null,
+                "3-tier salmon, spinach and avocado terrine"
+             ]
+          },
+          {
+             "id" : "Aberffrawcake",
+             "key" : "Aberffraw cake",
+             "value" : [
+                null,
+                "Aberffraw cake"
+             ]
+          },
+          {
+             "id" : "Adukiandorangecasserole-microwave",
+             "key" : "Aduki and orange casserole - microwave",
+             "value" : [
+                null,
+                "Aduki and orange casserole - microwave"
+             ]
+          },
+          {
+             "id" : "Aioli-garlicmayonnaise",
+             "key" : "Aioli - garlic mayonnaise",
+             "value" : [
+                null,
+                "Aioli - garlic mayonnaise"
+             ]
+          },
+          {
+             "id" : "Alabamapeanutchicken",
+             "key" : "Alabama peanut chicken",
+             "value" : [
+                null,
+                "Alabama peanut chicken"
+             ]
+          }
+       ],
+       "total_rows" : 2667
+    }
+
+Requesting the same in descending order will reverse the entire view
+content. For example the request
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_design/recipes/_view/by_title?limit=5&descending=true
+    Accept: application/json
+    Content-Type: application/json
+
+Returns the last 5 records from the view:
+
+.. code-block:: javascript
+
+    {
+       "offset" : 0,
+       "rows" : [
+          {
+             "id" : "Zucchiniinagrodolcesweet-sourcourgettes",
+             "key" : "Zucchini in agrodolce (sweet-sour courgettes)",
+             "value" : [
+                null,
+                "Zucchini in agrodolce (sweet-sour courgettes)"
+             ]
+          },
+          {
+             "id" : "Zingylemontart",
+             "key" : "Zingy lemon tart",
+             "value" : [
+                null,
+                "Zingy lemon tart"
+             ]
+          },
+          {
+             "id" : "Zestyseafoodavocado",
+             "key" : "Zesty seafood avocado",
+             "value" : [
+                null,
+                "Zesty seafood avocado"
+             ]
+          },
+          {
+             "id" : "Zabaglione",
+             "key" : "Zabaglione",
+             "value" : [
+                null,
+                "Zabaglione"
+             ]
+          },
+          {
+             "id" : "Yogurtraita",
+             "key" : "Yogurt raita",
+             "value" : [
+                null,
+                "Yogurt raita"
+             ]
+          }
+       ],
+       "total_rows" : 2667
+    }
+
+The sorting direction is applied before the filtering applied using the
+``startkey`` and ``endkey`` query arguments. For example the following
+query:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?startkey=%22carrots%22&endkey=%22egg%22
+    Accept: application/json
+    Content-Type: application/json
+
+Will operate correctly when listing all the matching entries between
+“carrots” and ``egg``. If the order of output is reversed with the
+``descending`` query argument, the view request will return no entries:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?descending=true&startkey=%22carrots%22&endkey=%22egg%22
+    Accept: application/json
+    Content-Type: application/json
+
+The returned result is empty:
+
+.. code-block:: javascript
+
+    {
+       "total_rows" : 26453,
+       "rows" : [],
+       "offset" : 21882
+    }
+
+The results will be empty because the entries in the view are reversed
+before the key filter is applied, and therefore the ``endkey`` of “egg”
+will be seen before the ``startkey`` of “carrots”, resulting in an empty
+list.
+
+Instead, you should reverse the values supplied to the ``startkey`` and
+``endkey`` parameters to match the descending sorting applied to the
+keys. Changing the previous example to:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?descending=true&startkey=%22egg%22&endkey=%22carrots%22
+    Accept: application/json
+    Content-Type: application/json
+
+Specifying Start and End Values
+-------------------------------
+
+.. todo:: Specifying Start and End Values
+
+The ``startkey`` and ``endkey`` query arguments can be used to specify
+the range of values to be displayed when querying the view.
+
+Using Limits and Skipping Rows
+------------------------------
+
+.. todo:: Using Limits and Skipping Rows
+
+TBC
+
+View Reduction and Grouping
+---------------------------
+
+.. todo:: View Reduction and Grouping
+
+TBC
+
+.. _api/ddoc/view.post:
+
+``POST /db/_design/design-doc/_view/view-name``
+===============================================
+
+* **Method**: ``POST /db/_design/design-doc/_view/view-name``
+* **Request**:  List of keys to be returned from specified view
+* **Response**:  JSON of the documents returned by the view
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: descending
+
+    * **Description**:  Return the documents in descending by key order
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: endkey
+
+    * **Description**:  Stop returning records when the specified key is reached
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: endkey_docid
+
+    * **Description**:  Stop returning records when the specified document ID
+      is reached
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: group
+
+    * **Description**:  Group the results using the reduce function to a group
+      or single row
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: group_level
+
+    * **Description**:  Specify the group level to be used
+    * **Optional**: yes
+    * **Type**: numeric
+
+  * **Argument**: include_docs
+
+    * **Description**:  Include the full content of the documents in the return
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+  * **Argument**: inclusive_end
+
+    * **Description**:  Specifies whether the specified end key should be
+      included in the result
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: true
+
+  * **Argument**: key
+
+    * **Description**:  Return only documents that match the specified key
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: limit
+
+    * **Description**:  Limit the number of the returned documents to the
+      specified number
+    * **Optional**: yes
+    * **Type**: numeric
+
+  * **Argument**: reduce
+
+    * **Description**:  Use the reduction function
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: true
+
+  * **Argument**: skip
+
+    * **Description**:  Skip this number of records before starting to return
+      the results
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 0
+
+  * **Argument**: stale
+
+    * **Description**:  Allow the results from a stale view to be used
+    * **Optional**: yes
+    * **Type**: string
+    * **Default**:
+    * **Supported Values**:
+
+      * **ok**: Allow stale views
+
+  * **Argument**: startkey
+
+    * **Description**:  Return records starting with the specified key
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: startkey_docid
+
+    * **Description**:  Return records starting with the specified document ID
+    * **Optional**: yes
+    * **Type**: string
+
+  * **Argument**: update_seq
+
+    * **Description**:  Include the update sequence in the generated results
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: false
+
+Executes the specified ``view-name`` from the specified ``design-doc``
+design document. Unlike the ``GET`` method for accessing views, the
+``POST`` method supports the specification of explicit keys to be
+retrieved from the view results. The remainder of the ``POST`` view
+functionality is identical to the :ref:`api/ddoc/view.get` API.
+
+For example, the request below will return all the recipes where the key
+for the view matches either “claret” or “clear apple cider” :
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient
+    Content-Type: application/json
+
+    {
+       "keys" : [
+          "claret",
+          "clear apple juice"
+       ]
+    }
+
+
+The returned view data contains the standard view information, but only
+where the keys match.
+
+.. code-block:: javascript
+
+    {
+       "total_rows" : 26484,
+       "rows" : [
+          {
+             "value" : [
+                "Scotch collops"
+             ],
+             "id" : "Scotchcollops",
+             "key" : "claret"
+          },
+          {
+             "value" : [
+                "Stand pie"
+             ],
+             "id" : "Standpie",
+             "key" : "clear apple juice"
+          }
+       ],
+       "offset" : 6324
+    }
+
+Multi-document Fetching
+-----------------------
+
+By combining the ``POST`` method to a given view with the
+``include_docs=true`` query argument you can obtain multiple documents
+from a database. The result is more efficient than using multiple
+:ref:`api/doc.get` requests.
+
+For example, sending the following request for ingredients matching
+“claret” and “clear apple juice”:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?include_docs=true
+    Content-Type: application/json
+
+    {
+       "keys" : [
+          "claret",
+          "clear apple juice"
+       ]
+    }
+
+Returns the full document for each recipe:
+
+.. code-block:: javascript
+
+    {
+       "offset" : 6324,
+       "rows" : [
+          {
+             "doc" : {
+                "_id" : "Scotchcollops",
+                "_rev" : "1-bcbdf724f8544c89697a1cbc4b9f0178",
+                "cooktime" : "8",
+                "ingredients" : [
+                   {
+                      "ingredient" : "onion",
+                      "ingredtext" : "onion, peeled and chopped",
+                      "meastext" : "1"
+                   },
+                ...
+                ],
+                "keywords" : [
+                   "cook method.hob, oven, grill@hob",
+                   "diet@wheat-free",
+                   "diet@peanut-free",
+                   "special collections@classic recipe",
+                   "cuisine@british traditional",
+                   "diet@corn-free",
+                   "diet@citrus-free",
+                   "special collections@very easy",
+                   "diet@shellfish-free",
+                   "main ingredient@meat",
+                   "occasion@christmas",
+                   "meal type@main",
+                   "diet@egg-free",
+                   "diet@gluten-free"
+                ],
+                "preptime" : "10",
+                "servings" : "4",
+                "subtitle" : "This recipe comes from an old recipe book of 1683 called 'The Gentlewoman's Kitchen'. This is an excellent way of making a rich and full-flavoured meat dish in a very short time.",
+                "title" : "Scotch collops",
+                "totaltime" : "18"
+             },
+             "id" : "Scotchcollops",
+             "key" : "claret",
+             "value" : [
+                "Scotch collops"
+             ]
+          },
+          {
+             "doc" : {
+                "_id" : "Standpie",
+                "_rev" : "1-bff6edf3ca2474a243023f2dad432a5a",
+                "cooktime" : "92",
+                "ingredients" : [
+    ...            ],
+                "keywords" : [
+                   "diet@dairy-free",
+                   "diet@peanut-free",
+                   "special collections@classic recipe",
+                   "cuisine@british traditional",
+                   "diet@corn-free",
+                   "diet@citrus-free",
+                   "occasion@buffet party",
+                   "diet@shellfish-free",
+                   "occasion@picnic",
+                   "special collections@lunchbox",
+                   "main ingredient@meat",
+                   "convenience@serve with salad for complete meal",
+                   "meal type@main",
+                   "cook method.hob, oven, grill@hob / oven",
+                   "diet@cow dairy-free"
+                ],
+                "preptime" : "30",
+                "servings" : "6",
+                "subtitle" : "Serve this pie with pickled vegetables and potato salad.",
+                "title" : "Stand pie",
+                "totaltime" : "437"
+             },
+             "id" : "Standpie",
+             "key" : "clear apple juice",
+             "value" : [
+                "Stand pie"
+             ]
+          }
+       ],
+       "total_rows" : 26484
+    }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/design.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/design.rst b/share/doc/src/api/design.rst
deleted file mode 100644
index 570c08e..0000000
--- a/share/doc/src/api/design.rst
+++ /dev/null
@@ -1,1306 +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.
-
-.. _api/ddoc:
-
-=======================
-Design Document Methods
-=======================
-
-In CouchDB, design documents provide the main interface for building a
-CouchDB application. The design document defines the views used to
-extract information from CouchDB through one or more views. Design
-documents are created within your CouchDB instance in the same way as
-you create database documents, but the content and definition of the
-documents is different. Design Documents are named using an ID defined
-with the design document URL path, and this URL can then be used to
-access the database contents.
-
-Views and lists operate together to provide automated (and formatted)
-output from your database.
-
-A list of the available methods and URL paths are provided below:
-
-Design Document API Calls
-
-.. _api/ddoc.get:
-
-``GET /db/_design/design-doc``
-==============================
-
-* **Method**: ``GET /db/_design/design-doc``
-* **Request**:  None
-* **Response**:  JSON of the existing design document
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Specify the revision to return
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: revs
-
-    * **Description**:  Return a list of the revisions for the document
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Supported Values**:
-
-        * **true**: Includes the revisions
-
-  * **Argument**: revs_info
-
-    * **Description**:  Return a list of detailed revision information for the
-      document
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Supported Values**:
-
-      * **true**: Includes the revisions
-
-Returns the specified design document, ``design-doc`` from the specified
-``db``. For example, to retrieve the design document ``recipes`` you
-would send the following request:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_design/recipes
-    Content-Type: application/json
-
-The returned string will be the JSON of the design document:
-
-.. code-block:: javascript
-
-    {
-       "_id" : "_design/recipes",
-       "_rev" : "5-39f56a392b86bbee57e2138921346406"
-       "language" : "javascript",
-       "views" : {
-          "by_recipe" : {
-             "map" : "function(doc) { if (doc.title != null) emit(doc.title, doc) }"
-          },
-       },
-    }
-
-A list of the revisions can be obtained by using the ``revs`` query
-argument, or an extended list of revisions using the ``revs_info`` query
-argument. This operates in the same way as for other documents. Fur
-further examples, see :ref:`api/doc.get`.
-
-.. _api/ddoc.put:
-
-``PUT /db/_design/design-doc``
-==============================
-
-* **Method**: ``PUT /db/_design/design-doc``
-* **Request**:  JSON of the design document
-* **Response**:  JSON status
-* **Admin Privileges Required**: no
-
-Upload the specified design document, ``design-doc``, to the specified
-database. The design document should follow the definition of a design
-document, as summarised in the following table.
-
-* **_id**:  Design Document ID
-* **_rev**:  Design Document Revision
-* **views**:  View
-
-  * **viewname**:  View Definition
-
-    * **map**:  Map Function for View
-    * **reduce (optional)**:  Reduce Function for View
-
-For more information on writing views, see :ref:`api/ddoc/view`.
-
-.. _api/ddoc.delete:
-
-``DELETE /db/_design/design-doc``
-=================================
-
-* **Method**: ``DELETE /db/_design/design-doc``
-* **Request**:  None
-* **Response**:  JSON of deleted design document
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Current revision of the document for validation
-    * **Optional**: yes
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``If-Match``
-
-    * **Description**: Current revision of the document for validation
-    * **Optional**: yes
-
-* **Return Codes**:
-
-  * **409**:
-    Supplied revision is incorrect or missing
-
-Delete an existing design document. Deleting a design document also
-deletes all of the associated view indexes, and recovers the
-corresponding space on disk for the indexes in question.
-
-To delete, you must specify the current revision of the design document
-using the ``rev`` query argument.
-
-For example:
-
-.. code-block:: http
-
-    DELETE http://couchdb:5984/recipes/_design/recipes?rev=2-ac58d589b37d01c00f45a4418c5a15a8
-    Content-Type: application/json
-
-The response contains the delete document ID and revision:
-
-.. code-block:: javascript
-
-    {
-       "id" : "recipe/_design/recipes"
-       "ok" : true,
-       "rev" : "3-7a05370bff53186cb5d403f861aca154",
-    }
-
-.. _api/ddoc.copy:
-
-``COPY /db/_design/design-doc``
-===============================
-
-* **Method**: ``COPY /db/_design/design-doc``
-* **Request**: None
-* **Response**: JSON of the new document and revision
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Revision to copy from
-    * **Optional**: yes
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``Destination``
-
-    * **Description**: Destination document (and optional revision)
-    * **Optional**: no
-
-The ``COPY`` command (non-standard HTTP) copies an existing design
-document to a new or existing document.
-
-The source design document is specified on the request line, with the
-``Destination`` HTTP Header of the request specifying the target
-document.
-
-Copying a Design Document
--------------------------
-
-To copy the latest version of a design document to a new document you
-specify the base document and target document:
-
-.. code-block:: http
-
-    COPY http://couchdb:5984/recipes/_design/recipes
-    Content-Type: application/json
-    Destination: /recipes/_design/recipelist
-
-The above request copies the design document ``recipes`` to the new
-design document ``recipelist``. The response is the ID and revision of
-the new document.
-
-.. code-block:: javascript
-
-    {
-       "id" : "recipes/_design/recipelist"
-       "rev" : "1-9c65296036141e575d32ba9c034dd3ee",
-    }
-
-.. note::
-   Copying a design document does automatically reconstruct the view
-   indexes. These will be recreated, as with other views, the first
-   time the new view is accessed.
-
-Copying from a Specific Revision
---------------------------------
-
-To copy *from* a specific version, use the ``rev`` argument to the query
-string:
-
-.. code-block:: http
-
-    COPY http://couchdb:5984/recipes/_design/recipes?rev=1-e23b9e942c19e9fb10ff1fde2e50e0f5
-    Content-Type: application/json
-    Destination: recipes/_design/recipelist
-
-The new design document will be created using the specified revision of
-the source document.
-
-Copying to an Existing Design Document
---------------------------------------
-
-To copy to an existing document, you must specify the current revision
-string for the target document, using the ``rev`` parameter to the
-``Destination`` HTTP Header string. For example:
-
-.. code-block:: http
-
-    COPY http://couchdb:5984/recipes/_design/recipes
-    Content-Type: application/json
-    Destination: recipes/_design/recipelist?rev=1-9c65296036141e575d32ba9c034dd3ee
-
-The return value will be the new revision of the copied document:
-
-.. code-block:: javascript
-
-    {
-       "id" : "recipes/_design/recipes"
-       "rev" : "2-55b6a1b251902a2c249b667dab1c6692",
-    }
-
-.. _api/ddoc/attachment:
-.. _api/ddoc/attachment.get:
-
-``GET /db/_design/design-doc/attachment``
-=========================================
-
-* **Method**: ``GET /db/_design/design-doc/attachment``
-* **Request**: None
-* **Response**: Returns the attachment data
-* **Admin Privileges Required**: no
-
-Returns the file attachment ``attachment`` associated with the design
-document ``/_design_/design-doc``. The raw data of the associated
-attachment is returned (just as if you were accessing a static file. The
-returned HTTP ``Content-type`` will be the same as the content type set
-when the document attachment was submitted into the database.
-
-.. _api/ddoc/attachment.put:
-
-``PUT /db/_design/design-doc/attachment``
-=========================================
-
-* **Method**: ``PUT /db/_design/design-doc/attachment``
-* **Request**: Raw document data
-* **Response**: JSON document status
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Current document revision
-    * **Optional**: no
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``Content-Length``
-
-    * **Description**: Length (bytes) of the attachment being uploaded
-    * **Optional**: no
-
-  * **Header**: ``Content-Type``
-
-    * **Description**: MIME type for the uploaded attachment
-    * **Optional**: no
-
-  * **Header**: ``If-Match``
-
-    * **Description**: Current revision of the document for validation
-    * **Optional**: yes
-
-Upload the supplied content as an attachment to the specified design
-document (``/_design/design-doc``). The ``attachment`` name provided
-must be a URL encoded string. You must also supply either the ``rev``
-query argument or the ``If-Match`` HTTP header for validation, and the
-HTTP headers (to set the attachment content type). The content type is
-used when the attachment is requested as the corresponding content-type
-in the returned document header.
-
-For example, you could upload a simple text document using the following
-request:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/_design/recipes/view.css?rev=7-f7114d4d81124b223283f3e89eee043e
-    Content-Length: 39
-    Content-Type: text/plain
-
-    div.recipetitle {
-    font-weight: bold;
-    }
-
-Or by using the ``If-Match`` HTTP header:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/FishStew/basic
-    If-Match: 7-f7114d4d81124b223283f3e89eee043e
-    Content-Length: 39
-    Content-Type: text/plain
-
-    div.recipetitle {
-    font-weight: bold;
-    }
-
-The returned JSON contains the new document information:
-
-.. code-block:: javascript
-
-    {
-       "id" : "_design/recipes"
-       "ok" : true,
-       "rev" : "8-cb2b7d94eeac76782a02396ba70dfbf5",
-    }
-
-.. note::
-   Uploading an attachment updates the corresponding document revision.
-   Revisions are tracked for the parent document, not individual attachments.
-
-.. _api/ddoc/attachment.delete:
-
-``DELETE /db/_design/design-doc/attachment``
-============================================
-
-* **Method**: ``DELETE /db/_design/design-doc/attachment``
-* **Request**: None
-* **Response**: JSON status
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: rev
-
-    * **Description**:  Current document revision
-    * **Optional**: no
-    * **Type**: string
-
-* **HTTP Headers**
-
-  * **Header**: ``If-Match``
-
-    * **Description**: Current revision of the document for validation
-    * **Optional**: yes
-
-* **Return Codes**:
-
-  * **200**:
-    Attachment deleted successfully
-  * **409**:
-    Supplied revision is incorrect or missing
-
-Deletes the attachment ``attachment`` to the specified
-``_design/design-doc``. You must supply the ``rev`` argument with the
-current revision to delete the attachment.
-
-For example to delete the attachment ``view.css`` from the design
-document ``recipes``:
-
-.. code-block:: http
-
-    DELETE http://couchdb:5984/recipes/_design/recipes/view.css?rev=9-3db559f13a845c7751d407404cdeaa4a
-
-The returned JSON contains the updated revision information for the
-parent document:
-
-.. code-block:: javascript
-
-    {
-       "id" : "_design/recipes"
-       "ok" : true,
-       "rev" : "10-f3b15bb408961f8dcc3d86c7d3b54c4c",
-    }
-
-.. _api/ddoc/info:
-.. _api/ddoc/info.get:
-
-``GET /db/_design/design-doc/_info``
-====================================
-
-* **Method**: ``GET /db/_design/design-doc/_info``
-* **Request**: None
-* **Response**: JSON of the design document information
-* **Admin Privileges Required**: no
-
-Obtains information about a given design document, including the index,
-index size and current status of the design document and associated
-index information.
-
-For example, to get the information for the ``recipes`` design document:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_design/recipes/_info
-    Content-Type: application/json
-
-This returns the following JSON structure:
-
-.. code-block:: javascript
-
-    {
-       "name" : "recipes"
-       "view_index" : {
-          "compact_running" : false,
-          "updater_running" : false,
-          "language" : "javascript",
-          "purge_seq" : 10,
-          "waiting_commit" : false,
-          "waiting_clients" : 0,
-          "signature" : "fc65594ee76087a3b8c726caf5b40687",
-          "update_seq" : 375031,
-          "disk_size" : 16491
-       },
-    }
-
-The individual fields in the returned JSON structure are detailed below:
-
-* **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
-
-.. _api/ddoc/view:
-.. _api/ddoc/view.get:
-
-``GET /db/_design/design-doc/_view/view-name``
-==============================================
-
-* **Method**: ``GET /db/_design/design-doc/_view/view-name``
-* **Request**: None
-* **Response**: JSON of the documents returned by the view
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: descending
-
-    * **Description**:  Return the documents in descending by key order
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: endkey
-
-    * **Description**:  Stop returning records when the specified key is reached
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: endkey_docid
-
-    * **Description**:  Stop returning records when the specified document
-      ID is reached
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: group
-
-    * **Description**:  Group the results using the reduce function to a
-      group or single row
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: group_level
-
-    * **Description**:  Specify the group level to be used
-    * **Optional**: yes
-    * **Type**: numeric
-
-  * **Argument**: include_docs
-
-    * **Description**:  Include the full content of the documents in the return
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: inclusive_end
-
-    * **Description**:  Specifies whether the specified end key should be
-      included in the result
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: true
-
-  * **Argument**: key
-
-    * **Description**:  Return only documents that match the specified key
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: limit
-
-    * **Description**:  Limit the number of the returned documents to the
-      specified number
-    * **Optional**: yes
-    * **Type**: numeric
-
-  * **Argument**: reduce
-
-    * **Description**:  Use the reduction function
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: true
-
-  * **Argument**: skip
-
-    * **Description**:  Skip this number of records before starting to return
-      the results
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 0
-
-  * **Argument**: stale
-
-    * **Description**:  Allow the results from a stale view to be used
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**:
-    * **Supported Values**
-
-      * **ok**: Allow stale views
-
-  * **Argument**: startkey
-
-    * **Description**:  Return records starting with the specified key
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: startkey_docid
-
-    * **Description**:  Return records starting with the specified document ID
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: update_seq
-
-    * **Description**:  Include the update sequence in the generated results
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-Executes the specified ``view-name`` from the specified ``design-doc``
-design document.
-
-Querying Views and Indexes
---------------------------
-
-The definition of a view within a design document also creates an index
-based on the key information defined within each view. The production
-and use of the index significantly increases the speed of access and
-searching or selecting documents from the view.
-
-However, the index is not updated when new documents are added or
-modified in the database. Instead, the index is generated or updated,
-either when the view is first accessed, or when the view is accessed
-after a document has been updated. In each case, the index is updated
-before the view query is executed against the database.
-
-View indexes are updated incrementally in the following situations:
-
--  A new document has been added to the database.
-
--  A document has been deleted from the database.
-
--  A document in the database has been updated.
-
-View indexes are rebuilt entirely when the view definition changes. To
-achieve this, a 'fingerprint' of the view definition is created when the
-design document is updated. If the fingerprint changes, then the view
-indexes are entirely rebuilt. This ensures that changes to the view
-definitions are reflected in the view indexes.
-
-.. note::
-   View index rebuilds occur when one view from the same the view group
-   (i.e. all the views defined within a single a design document) has
-   been determined as needing a rebuild. For example, if if you have a
-   design document with different views, and you update the database,
-   all three view indexes within the design document will be updated.
-
-Because the view is updated when it has been queried, it can result in a
-delay in returned information when the view is accessed, especially if
-there are a large number of documents in the database and the view index
-does not exist. There are a number of ways to mitigate, but not
-completely eliminate, these issues. These include:
-
--  Create the view definition (and associated design documents) on your
-   database before allowing insertion or updates to the documents. If
-   this is allowed while the view is being accessed, the index can be
-   updated incrementally.
-
--  Manually force a view request from the database. You can do this
-   either before users are allowed to use the view, or you can access
-   the view manually after documents are added or updated.
-
--  Use the ``/db/_changes`` method to monitor for changes to the
-   database and then access the view to force the corresponding view
-   index to be updated. See :ref:`api/db/changes` for more information.
-
--  Use a monitor with the ``update_notification`` section of the CouchDB
-   configuration file to monitor for changes to your database, and
-   trigger a view query to force the view to be updated. For more
-   information, see :ref:`update-notifications`.
-
-None of these can completely eliminate the need for the indexes to be
-rebuilt or updated when the view is accessed, but they may lessen the
-effects on end-users of the index update affecting the user experience.
-
-Another alternative is to allow users to access a 'stale' version of the
-view index, rather than forcing the index to be updated and displaying
-the updated results. Using a stale view may not return the latest
-information, but will return the results of the view query using an
-existing version of the index.
-
-For example, to access the existing stale view ``by_recipe`` in the
-``recipes`` design document:
-
-.. code-block:: text
-
-    http://couchdb:5984/recipes/_design/recipes/_view/by_recipe?stale=ok
-
-Accessing a stale view:
-
--  Does not trigger a rebuild of the view indexes, even if there have
-   been changes since the last access.
-
--  Returns the current version of the view index, if a current version
-   exists.
-
--  Returns an empty result set if the given view index does exist.
-
-As an alternative, you use the ``update_after`` value to the ``stale``
-parameter. This causes the view to be returned as a stale view, but for
-the update process to be triggered after the view information has been
-returned to the client.
-
-In addition to using stale views, you can also make use of the
-``update_seq`` query argument. Using this query argument generates the
-view information including the update sequence of the database from
-which the view was generated. The returned value can be compared this to
-the current update sequence exposed in the database information
-(returned by :ref:`api/db.get`).
-
-Sorting Returned Rows
----------------------
-
-Each element within the returned array is sorted using native UTF-8
-sorting according to the contents of the key portion of the emitted
-content. The basic order of output is as follows:
-
--  ``null``
-
--  ``false``
-
--  ``true``
-
--  Numbers
-
--  Text (case sensitive, lowercase first)
-
--  Arrays (according to the values of each element, in order)
-
--  Objects (according to the values of keys, in key order)
-
-You can reverse the order of the returned view information by using the
-``descending`` query value set to true. For example, Retrieving the list
-of recipes using the ``by_title`` (limited to 5 records) view:
-
-.. code-block:: javascript
-
-    {
-       "offset" : 0,
-       "rows" : [
-          {
-             "id" : "3-tiersalmonspinachandavocadoterrine",
-             "key" : "3-tier salmon, spinach and avocado terrine",
-             "value" : [
-                null,
-                "3-tier salmon, spinach and avocado terrine"
-             ]
-          },
-          {
-             "id" : "Aberffrawcake",
-             "key" : "Aberffraw cake",
-             "value" : [
-                null,
-                "Aberffraw cake"
-             ]
-          },
-          {
-             "id" : "Adukiandorangecasserole-microwave",
-             "key" : "Aduki and orange casserole - microwave",
-             "value" : [
-                null,
-                "Aduki and orange casserole - microwave"
-             ]
-          },
-          {
-             "id" : "Aioli-garlicmayonnaise",
-             "key" : "Aioli - garlic mayonnaise",
-             "value" : [
-                null,
-                "Aioli - garlic mayonnaise"
-             ]
-          },
-          {
-             "id" : "Alabamapeanutchicken",
-             "key" : "Alabama peanut chicken",
-             "value" : [
-                null,
-                "Alabama peanut chicken"
-             ]
-          }
-       ],
-       "total_rows" : 2667
-    }
-
-Requesting the same in descending order will reverse the entire view
-content. For example the request
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_design/recipes/_view/by_title?limit=5&descending=true
-    Accept: application/json
-    Content-Type: application/json
-
-Returns the last 5 records from the view:
-
-.. code-block:: javascript
-
-    {
-       "offset" : 0,
-       "rows" : [
-          {
-             "id" : "Zucchiniinagrodolcesweet-sourcourgettes",
-             "key" : "Zucchini in agrodolce (sweet-sour courgettes)",
-             "value" : [
-                null,
-                "Zucchini in agrodolce (sweet-sour courgettes)"
-             ]
-          },
-          {
-             "id" : "Zingylemontart",
-             "key" : "Zingy lemon tart",
-             "value" : [
-                null,
-                "Zingy lemon tart"
-             ]
-          },
-          {
-             "id" : "Zestyseafoodavocado",
-             "key" : "Zesty seafood avocado",
-             "value" : [
-                null,
-                "Zesty seafood avocado"
-             ]
-          },
-          {
-             "id" : "Zabaglione",
-             "key" : "Zabaglione",
-             "value" : [
-                null,
-                "Zabaglione"
-             ]
-          },
-          {
-             "id" : "Yogurtraita",
-             "key" : "Yogurt raita",
-             "value" : [
-                null,
-                "Yogurt raita"
-             ]
-          }
-       ],
-       "total_rows" : 2667
-    }
-
-The sorting direction is applied before the filtering applied using the
-``startkey`` and ``endkey`` query arguments. For example the following
-query:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?startkey=%22carrots%22&endkey=%22egg%22
-    Accept: application/json
-    Content-Type: application/json
-
-Will operate correctly when listing all the matching entries between
-“carrots” and ``egg``. If the order of output is reversed with the
-``descending`` query argument, the view request will return no entries:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?descending=true&startkey=%22carrots%22&endkey=%22egg%22
-    Accept: application/json
-    Content-Type: application/json
-
-The returned result is empty:
-
-.. code-block:: javascript
-
-    {
-       "total_rows" : 26453,
-       "rows" : [],
-       "offset" : 21882
-    }
-
-The results will be empty because the entries in the view are reversed
-before the key filter is applied, and therefore the ``endkey`` of “egg”
-will be seen before the ``startkey`` of “carrots”, resulting in an empty
-list.
-
-Instead, you should reverse the values supplied to the ``startkey`` and
-``endkey`` parameters to match the descending sorting applied to the
-keys. Changing the previous example to:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?descending=true&startkey=%22egg%22&endkey=%22carrots%22
-    Accept: application/json
-    Content-Type: application/json
-
-Specifying Start and End Values
--------------------------------
-
-.. todo:: Specifying Start and End Values
-
-The ``startkey`` and ``endkey`` query arguments can be used to specify
-the range of values to be displayed when querying the view.
-
-Using Limits and Skipping Rows
-------------------------------
-
-.. todo:: Using Limits and Skipping Rows
-
-TBC
-
-View Reduction and Grouping
----------------------------
-
-.. todo:: View Reduction and Grouping
-
-TBC
-
-.. _api/ddoc/view.post:
-
-``POST /db/_design/design-doc/_view/view-name``
-===============================================
-
-* **Method**: ``POST /db/_design/design-doc/_view/view-name``
-* **Request**:  List of keys to be returned from specified view
-* **Response**:  JSON of the documents returned by the view
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: descending
-
-    * **Description**:  Return the documents in descending by key order
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: endkey
-
-    * **Description**:  Stop returning records when the specified key is reached
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: endkey_docid
-
-    * **Description**:  Stop returning records when the specified document ID
-      is reached
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: group
-
-    * **Description**:  Group the results using the reduce function to a group
-      or single row
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: group_level
-
-    * **Description**:  Specify the group level to be used
-    * **Optional**: yes
-    * **Type**: numeric
-
-  * **Argument**: include_docs
-
-    * **Description**:  Include the full content of the documents in the return
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: inclusive_end
-
-    * **Description**:  Specifies whether the specified end key should be
-      included in the result
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: true
-
-  * **Argument**: key
-
-    * **Description**:  Return only documents that match the specified key
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: limit
-
-    * **Description**:  Limit the number of the returned documents to the
-      specified number
-    * **Optional**: yes
-    * **Type**: numeric
-
-  * **Argument**: reduce
-
-    * **Description**:  Use the reduction function
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: true
-
-  * **Argument**: skip
-
-    * **Description**:  Skip this number of records before starting to return
-      the results
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 0
-
-  * **Argument**: stale
-
-    * **Description**:  Allow the results from a stale view to be used
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**:
-    * **Supported Values**:
-
-      * **ok**: Allow stale views
-
-  * **Argument**: startkey
-
-    * **Description**:  Return records starting with the specified key
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: startkey_docid
-
-    * **Description**:  Return records starting with the specified document ID
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: update_seq
-
-    * **Description**:  Include the update sequence in the generated results
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-Executes the specified ``view-name`` from the specified ``design-doc``
-design document. Unlike the ``GET`` method for accessing views, the
-``POST`` method supports the specification of explicit keys to be
-retrieved from the view results. The remainder of the ``POST`` view
-functionality is identical to the :ref:`api/ddoc/view.get` API.
-
-For example, the request below will return all the recipes where the key
-for the view matches either “claret” or “clear apple cider” :
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient
-    Content-Type: application/json
-
-    {
-       "keys" : [
-          "claret",
-          "clear apple juice"
-       ]
-    }
-          
-
-The returned view data contains the standard view information, but only
-where the keys match.
-
-.. code-block:: javascript
-
-    {
-       "total_rows" : 26484,
-       "rows" : [
-          {
-             "value" : [
-                "Scotch collops"
-             ],
-             "id" : "Scotchcollops",
-             "key" : "claret"
-          },
-          {
-             "value" : [
-                "Stand pie"
-             ],
-             "id" : "Standpie",
-             "key" : "clear apple juice"
-          }
-       ],
-       "offset" : 6324
-    }
-
-Multi-document Fetching
------------------------
-
-By combining the ``POST`` method to a given view with the
-``include_docs=true`` query argument you can obtain multiple documents
-from a database. The result is more efficient than using multiple
-:ref:`api/doc.get` requests.
-
-For example, sending the following request for ingredients matching
-“claret” and “clear apple juice”:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_design/recipes/_view/by_ingredient?include_docs=true
-    Content-Type: application/json
-
-    {
-       "keys" : [
-          "claret",
-          "clear apple juice"
-       ]
-    }
-
-Returns the full document for each recipe:
-
-.. code-block:: javascript
-
-    {
-       "offset" : 6324,
-       "rows" : [
-          {
-             "doc" : {
-                "_id" : "Scotchcollops",
-                "_rev" : "1-bcbdf724f8544c89697a1cbc4b9f0178",
-                "cooktime" : "8",
-                "ingredients" : [
-                   {
-                      "ingredient" : "onion",
-                      "ingredtext" : "onion, peeled and chopped",
-                      "meastext" : "1"
-                   },
-                ...
-                ],
-                "keywords" : [
-                   "cook method.hob, oven, grill@hob",
-                   "diet@wheat-free",
-                   "diet@peanut-free",
-                   "special collections@classic recipe",
-                   "cuisine@british traditional",
-                   "diet@corn-free",
-                   "diet@citrus-free",
-                   "special collections@very easy",
-                   "diet@shellfish-free",
-                   "main ingredient@meat",
-                   "occasion@christmas",
-                   "meal type@main",
-                   "diet@egg-free",
-                   "diet@gluten-free"
-                ],
-                "preptime" : "10",
-                "servings" : "4",
-                "subtitle" : "This recipe comes from an old recipe book of 1683 called 'The Gentlewoman's Kitchen'. This is an excellent way of making a rich and full-flavoured meat dish in a very short time.",
-                "title" : "Scotch collops",
-                "totaltime" : "18"
-             },
-             "id" : "Scotchcollops",
-             "key" : "claret",
-             "value" : [
-                "Scotch collops"
-             ]
-          },
-          {
-             "doc" : {
-                "_id" : "Standpie",
-                "_rev" : "1-bff6edf3ca2474a243023f2dad432a5a",
-                "cooktime" : "92",
-                "ingredients" : [
-    ...            ],
-                "keywords" : [
-                   "diet@dairy-free",
-                   "diet@peanut-free",
-                   "special collections@classic recipe",
-                   "cuisine@british traditional",
-                   "diet@corn-free",
-                   "diet@citrus-free",
-                   "occasion@buffet party",
-                   "diet@shellfish-free",
-                   "occasion@picnic",
-                   "special collections@lunchbox",
-                   "main ingredient@meat",
-                   "convenience@serve with salad for complete meal",
-                   "meal type@main",
-                   "cook method.hob, oven, grill@hob / oven",
-                   "diet@cow dairy-free"
-                ],
-                "preptime" : "30",
-                "servings" : "6",
-                "subtitle" : "Serve this pie with pickled vegetables and potato salad.",
-                "title" : "Stand pie",
-                "totaltime" : "437"
-             },
-             "id" : "Standpie",
-             "key" : "clear apple juice",
-             "value" : [
-                "Stand pie"
-             ]
-          }
-       ],
-       "total_rows" : 26484
-    }
-
-.. _api/ddoc/show:
-.. _api/ddoc/show.get:
-
-``GET /db/_design/design-doc/_show/show-name``
-===============================================
-
-.. todo:: GET /db/_design/design-doc/_show/show-name
-
-* **Method**: ``GET /db/_design/design-doc/_show/show-name``
-* **Request**:  None
-* **Response**:  Returns the result of the show
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: details
-
-    * **Description**:  Indicates whether details should be included
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: format
-
-    * **Description**:  Format of the returned information
-    * **Optional**: yes
-    * **Type**: string
-
-.. _api/ddoc/show/doc.post:
-
-``POST /db/_design/design-doc/_show/show-name/doc``
-===================================================
-
-.. todo:: POST /db/_design/design-doc/_show/show-name/doc
-
-* **Method**: ``POST /db/_design/design-doc/_show/show-name``
-* **Request**:  Custom data
-* **Response**:  Returns the result of the show
-* **Admin Privileges Required**: no
-
-.. _api/ddoc/list/ddoc:
-.. _api/ddoc/list/ddoc.get:
-
-``GET /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
-=========================================================================
-
-.. todo:: GET /db/_design/design-doc/_list/list-name/other-design-doc/view-name
-
-* **Method**: ``GET /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
-* **Request**:  TBC
-* **Response**:  TBC
-* **Admin Privileges Required**: no
-
-.. _api/ddoc/list/ddoc.post:
-
-``POST /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
-==========================================================================
-
-.. todo:: POST /db/_design/design-doc/_list/list-name/other-design-doc/view-name
-
-* **Method**: ``POST /db/_design/design-doc/_list/list-name/other-design-doc/view-name``
-* **Request**:  TBC
-* **Response**:  TBC
-* **Admin Privileges Required**: no
-
-.. _api/ddoc/list:
-.. _api/ddoc/list.get:
-
-``GET /db/_design/design-doc/_list/list-name/view-name``
-========================================================
-
-.. todo:: GET /db/_design/design-doc/_list/list-name/view-name
-
-* **Method**: ``GET /db/_design/design-doc/_list/list-name/view-name``
-* **Request**:  TBC
-* **Response**:  TBC
-* **Admin Privileges Required**: no
-
-.. _api/ddoc/list.post:
-
-``POST /db/_design/design-doc/_list/list-name/view-name``
-=========================================================
-
-.. todo:: POST /db/_design/design-doc/_list/list-name/view-name
-
-* **Method**: ``POST /db/_design/design-doc/_list/list-name/view-name``
-* **Request**:  TBC
-* **Response**:  TBC
-* **Admin Privileges Required**: no
-
-.. _api/ddoc/update/doc:
-.. _api/ddoc/update/doc.put:
-
-``PUT /db/_design/design-doc/_update/updatename/doc``
-=====================================================
-
-.. todo:: POST /db/_design/design-doc/_update/updatename/doc
-
-* **Method**: ``POST /db/_design/design-doc/_update/updatename/doc``
-* **Request**:  TBC
-* **Response**:  TBC
-* **Admin Privileges Required**: no
-
-.. _api/ddoc/update:
-.. _api/ddoc/update.post:
-
-``POST /db/_design/design-doc/_update/updatename``
-==================================================
-
-.. todo:: PUT /db/_design/design-doc/_update/updatename/doc
-
-* **Method**: ``PUT /db/_design/design-doc/_update/updatename/doc``
-* **Request**:  TBC
-* **Response**:  TBC
-* **Admin Privileges Required**: no
-
-.. _api/ddoc/rewrite:
-
-``ALL /db/_design/design-doc/_rewrite/rewrite-name/anything``
-=============================================================
-
-.. todo:: ALL /db/_design/design-doc/_rewrite/rewrite-name/anything
-
-* **Method**: ``ALL /db/_design/design-doc/_rewrite/rewrite-name/anything``
-* **Request**:  TBC
-* **Response**:  TBC
-* **Admin Privileges Required**: no

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/document/attachments.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/document/attachments.rst b/share/doc/src/api/document/attachments.rst
new file mode 100644
index 0000000..4af8e8c
--- /dev/null
+++ b/share/doc/src/api/document/attachments.rst
@@ -0,0 +1,242 @@
+.. 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.
+
+
+.. _api/doc/attachment:
+.. _api/doc/attachment.get:
+
+``GET /db/doc/attachment``
+==========================
+
+* **Method**: ``GET /db/doc/attachment``
+* **Request**: None
+* **Response**: Returns the attachment data
+* **Admin Privileges Required**: no
+
+Returns the file attachment ``attachment`` associated with the document
+``doc``. The raw data of the associated attachment is returned (just as
+if you were accessing a static file. The returned HTTP ``Content-type``
+will be the same as the content type set when the document attachment
+was submitted into the database.
+
+.. _api/doc/attachment/range:
+
+HTTP Range Requests
+-------------------
+
+HTTP allows you to specify byte ranges for requests. This allows the
+implementation of resumable downloads and skippable audio and video
+streams alike. This is available for all attachments inside CouchDB.
+
+This is just a real quick run through how this looks under the hood.
+Usually, you will have larger binary files to serve from CouchDB, like
+MP3s and videos, but to make things a little more obvious, I use a text
+file here (Note that I use the ``application/octet-stream`` Content-Type
+instead of ``text/plain``).
+
+.. code-block:: bash
+
+    shell> cat file.txt
+    My hovercraft is full of eels!
+
+Now let's store this text file as an attachment in CouchDB. First, we
+create a database:
+
+.. code-block:: bash
+
+    shell> curl -X PUT http://127.0.0.1:5984/test
+    {"ok":true}
+
+Then we create a new document and the file attachment in one go:
+
+.. code-block:: bash
+
+    shell> curl -X PUT http://127.0.0.1:5984/test/doc/file.txt \
+                -H "Content-Type: application/octet-stream" -d@file.txt
+    {"ok":true,"id":"doc","rev":"1-287a28fa680ae0c7fb4729bf0c6e0cf2"}
+
+Now we can request the whole file easily:
+
+.. code-block:: bash
+
+    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt
+    My hovercraft is full of eels!
+
+But say we only want the first 13 bytes:
+
+.. code-block:: bash
+
+    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt \
+                -H "Range: bytes=0-12"
+    My hovercraft
+
+HTTP supports many ways to specify single and even multiple byte
+ranges. Read all about it in `RFC 2616`_.
+
+.. note::
+   Databases that have been created with CouchDB 1.0.2 or earlier will
+   support range requests in |version|, but they are using a less-optimal
+   algorithm. If you plan to make heavy use of this feature, make sure
+   to compact your database with CouchDB |version| to take advantage of a
+   better algorithm to find byte ranges.
+
+.. _RFC 2616: http://tools.ietf.org/html/rfc2616#section-14.27
+
+
+.. _api/doc/attachment.put:
+
+``PUT /db/doc/attachment``
+==========================
+
+* **Method**: ``PUT /db/doc/attachment``
+* **Request**: Raw document data
+* **Response**: JSON document status
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Current document revision
+    * **Optional**: no
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``Content-Length``
+
+    * **Description**: Length (bytes) of the attachment being uploaded
+    * **Optional**: no
+
+  * **Header**: ``Content-Type``
+
+    * **Description**: MIME type for the uploaded attachment
+    * **Optional**: no
+
+  * **Header**: ``If-Match``
+
+    * **Description**: Current revision of the document for validation
+    * **Optional**: yes
+
+* **Return Codes**:
+
+  * **201**:
+    Attachment has been accepted
+
+Upload the supplied content as an attachment to the specified document
+(``doc``). The ``attachment`` name provided must be a URL encoded
+string. You must also supply either the ``rev`` query argument or the
+``If-Match`` HTTP header for validation, and the HTTP headers (to set
+the attachment content type). The content type is used when the
+attachment is requested as the corresponding content-type in the
+returned document header.
+
+For example, you could upload a simple text document using the following
+request:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/FishStew/basic?rev=8-a94cb7e50ded1e06f943be5bfbddf8ca
+    Content-Length: 10
+    Content-Type: text/plain
+
+    Roast it
+
+Or by using the ``If-Match`` HTTP header:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/recipes/FishStew/basic
+    If-Match: 8-a94cb7e50ded1e06f943be5bfbddf8ca
+    Content-Length: 10
+    Content-Type: text/plain
+
+    Roast it
+
+The returned JSON contains the new document information:
+
+.. code-block:: javascript
+
+    {
+       "id" : "FishStew",
+       "ok" : true,
+       "rev" : "9-247bb19a41bfd9bfdaf5ee6e2e05be74"
+    }
+
+.. note:: Uploading an attachment updates the corresponding document revision.
+   Revisions are tracked for the parent document, not individual
+   attachments.
+
+Updating an Existing Attachment
+-------------------------------
+
+Uploading an attachment using an existing attachment name will update
+the corresponding stored content of the database. Since you must supply
+the revision information to add an attachment to a document, this serves
+as validation to update the existing attachment.
+
+.. _api/doc/attachment.delete:
+
+``DELETE /db/doc/attachment``
+=============================
+
+* **Method**: ``DELETE /db/doc/attachment``
+* **Request**: None
+* **Response**: JSON status
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: rev
+
+    * **Description**:  Current document revision
+    * **Optional**: no
+    * **Type**: string
+
+* **HTTP Headers**
+
+  * **Header**: ``If-Match``
+
+    * **Description**: Current revision of the document for validation
+    * **Optional**: yes
+
+* **Return Codes**:
+
+  * **200**:
+    Attachment deleted successfully
+  * **409**:
+    Supplied revision is incorrect or missing
+
+Deletes the attachment ``attachment`` to the specified ``doc``. You must
+supply the ``rev`` argument with the current revision to delete the
+attachment.
+
+For example to delete the attachment ``basic`` from the recipe
+``FishStew``:
+
+.. code-block:: http
+
+    DELETE http://couchdb:5984/recipes/FishStew/basic?rev=9-247bb19a41bfd9bfdaf5ee6e2e05be74
+    Content-Type: application/json
+
+
+
+The returned JSON contains the updated revision information:
+
+.. code-block:: javascript
+
+    {
+       "id" : "FishStew",
+       "ok" : true,
+       "rev" : "10-561bf6b1e27615cee83d1f48fa65dd3e"
+    }
+
+.. _JSON object: #table-couchdb-api-db_db-json-changes
+.. _POST: #couchdb-api-dbdoc_db_post


[23/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Move api basics to the related group of articles.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/2c747953
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/2c747953
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/2c747953

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 2c747953fd3214bb71d3d528d95c149e42116ab8
Parents: fab08a2
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 13:51:59 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am     |   6 +-
 share/doc/src/api-basics.rst    | 463 -----------------------------------
 share/doc/src/api/basics.rst    | 462 ++++++++++++++++++++++++++++++++++
 share/doc/src/api/index.rst     |  43 ++++
 share/doc/src/api/reference.rst |  42 ----
 share/doc/src/index.rst         |   3 +-
 share/doc/src/intro.rst         |   2 +-
 7 files changed, 510 insertions(+), 511 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c747953/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 743cd4f..c822195 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -46,6 +46,7 @@ html_files = \
     html/_images/futon-overview.png \
     html/_images/futon-replform.png \
     html/_sources/api/authn.txt \
+    html/_sources/api/basics.txt \
     html/_sources/api/configuration.txt \
     html/_sources/api/database.txt \
     html/_sources/api/design.txt \
@@ -67,7 +68,6 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
-    html/_sources/api-basics.txt \
     html/_sources/changelog.txt \
     html/_sources/changes.txt \
     html/_sources/contributing.txt \
@@ -102,6 +102,7 @@ html_files = \
     html/_static/up.png \
     html/_static/websupport.js \
     html/api/authn.html \
+    html/api/basics.html \
     html/api/configuration.html \
     html/api/database.html \
     html/api/design.html \
@@ -123,7 +124,6 @@ html_files = \
     html/config/services.html \
     html/config/intro.html \
     html/config/proxying.html \
-    html/api-basics.html \
     html/changelog.html \
     html/changes.html \
     html/ddocs.html \
@@ -156,6 +156,7 @@ image_files = \
 
 src_files = \
     ../src/api/authn.rst \
+    ../src/api/basics.rst \
     ../src/api/configuration.rst \
     ../src/api/database.rst \
     ../src/api/design.rst \
@@ -177,7 +178,6 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
-    ../src/api-basics.rst \
     ../src/changelog.rst \
     ../src/changes.rst \
     ../src/contributing.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c747953/share/doc/src/api-basics.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api-basics.rst b/share/doc/src/api-basics.rst
deleted file mode 100644
index 8ffd83b..0000000
--- a/share/doc/src/api-basics.rst
+++ /dev/null
@@ -1,463 +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.
-
-.. _api-basics:
-
-==========
-API Basics
-==========
-
-The CouchDB API is the primary method of interfacing to a CouchDB
-instance. Requests are made using HTTP and requests are used to request
-information from the database, store new data, and perform views and
-formatting of the information stored within the documents.
-
-Requests to the API can be categorised by the different areas of the
-CouchDB system that you are accessing, and the HTTP method used to send
-the request. Different methods imply different operations, for example
-retrieval of information from the database is typically handled by the
-``GET`` operation, while updates are handled by either a ``POST`` or
-``PUT`` request. There are some differences between the information that
-must be supplied for the different methods. For a guide to the basic
-HTTP methods and request structure, see :ref:`api-format`.
-
-For nearly all operations, the submitted data, and the returned data
-structure, is defined within a JavaScript Object Notation (JSON) object.
-Basic information on the content and data types for JSON are provided in
-:ref:`json`.
-
-Errors when accessing the CouchDB API are reported using standard HTTP
-Status Codes. A guide to the generic codes returned by CouchDB are
-provided in :ref:`errors`.
-
-When accessing specific areas of the CouchDB API, specific information
-and examples on the HTTP methods and request, JSON structures, and error
-codes are provided. For a guide to the different areas of the API, see
-:ref:`api-overview`.
-
-.. _api-format:
-
-Request Format and Responses
-============================
-
-CouchDB supports the following HTTP request methods:
-
--  ``GET``
-
-   Request the specified item. As with normal HTTP requests, the format
-   of the URL defines what is returned. With CouchDB this can include
-   static items, database documents, and configuration and statistical
-   information. In most cases the information is returned in the form of
-   a JSON document.
-
--  ``HEAD``
-
-   The ``HEAD`` method is used to get the HTTP header of a ``GET``
-   request without the body of the response.
-
--  ``POST``
-
-   Upload data. Within CouchDB ``POST`` is used to set values, including
-   uploading documents, setting document values, and starting certain
-   administration commands.
-
--  ``PUT``
-
-   Used to put a specified resource. In CouchDB ``PUT`` is used to
-   create new objects, including databases, documents, views and design
-   documents.
-
--  ``DELETE``
-
-   Deletes the specified resource, including documents, views, and
-   design documents.
-
--  ``COPY``
-
-   A special method that can be used to copy documents and objects.
-
-If you use the an unsupported HTTP request type with a URL that does not
-support the specified type, a 405 error will be returned, listing the
-supported HTTP methods. For example:
-
-.. code-block:: javascript
-
-    {
-        "error":"method_not_allowed",
-        "reason":"Only GET,HEAD allowed"
-    }
-          
-
-The CouchDB design document API and the functions when returning HTML
-(for example as part of a show or list) enables you to include custom
-HTTP headers through the ``headers`` block of the return object.
-
-HTTP Headers
-============
-
-Because CouchDB uses HTTP for all communication, you need to ensure that
-the correct HTTP headers are supplied (and processed on retrieval) so
-that you get the right format and encoding. Different environments and
-clients will be more or less strict on the effect of these HTTP headers
-(especially when not present). Where possible you should be as specific
-as possible.
-
-Request Headers
----------------
-
--  ``Content-type``
-
-   Specifies the content type of the information being supplied within
-   the request. The specification uses MIME type specifications. For the
-   majority of requests this will be JSON (``application/json``). For
-   some settings the MIME type will be plain text. When uploading
-   attachments it should be the corresponding MIME type for the
-   attachment or binary (``application/octet-stream``).
-
-   The use of the ``Content-type`` on a request is highly recommended.
-
--  ``Accept``
-
-   Specifies the list of accepted data types to be returned by the
-   server (i.e. that are accepted/understandable by the client). The
-   format should be a list of one or more MIME types, separated by
-   colons.
-
-   For the majority of requests the definition should be for JSON data
-   (``application/json``). For attachments you can either specify the
-   MIME type explicitly, or use ``*/*`` to specify that all file types
-   are supported. If the ``Accept`` header is not supplied, then the
-   ``*/*`` MIME type is assumed (i.e. client accepts all formats).
-
-   The use of ``Accept`` in queries for CouchDB is not required, but is
-   highly recommended as it helps to ensure that the data returned can
-   be processed by the client.
-
-   If you specify a data type using the ``Accept`` header, CouchDB will
-   honor the specified type in the ``Content-type`` header field
-   returned. For example, if you explicitly request ``application/json``
-   in the ``Accept`` of a request, the returned HTTP headers will use
-   the value in the returned ``Content-type`` field.
-
-   For example, when sending a request without an explicit ``Accept``
-   header, or when specifying ``*/*``:
-
-   .. code-block:: http
-
-       GET /recipes HTTP/1.1
-       Host: couchdb:5984
-       Accept: */*
-
-   The returned headers are:
-
-   .. code-block:: http
-
-       Server: CouchDB/1.0.1 (Erlang OTP/R13B)
-       Date: Thu, 13 Jan 2011 13:39:34 GMT
-       Content-Type: text/plain;charset=utf-8
-       Content-Length: 227
-       Cache-Control: must-revalidate
-
-   Note that the returned content type is ``text/plain`` even though the
-   information returned by the request is in JSON format.
-
-   Explicitly specifying the ``Accept`` header:
-
-   .. code-block:: http
-
-       GET /recipes HTTP/1.1
-       Host: couchdb:5984
-       Accept: application/json
-
-   The headers returned include the ``application/json`` content type:
-
-   .. code-block:: http
-
-       Server: CouchDB/|version| (Erlang OTP/R13B)
-       Date: Thu, 13 Jan 2011 13:40:11 GMT
-       Content-Type: application/json
-       Content-Length: 227
-       Cache-Control: must-revalidate
-
-Response Headers
-----------------
-
-Response headers are returned by the server when sending back content
-and include a number of different header fields, many of which are
-standard HTTP response header and have no significance to CouchDB
-operation. The list of response headers important to CouchDB are listed
-below.
-
--  ``Content-type``
-
-   Specifies the MIME type of the returned data. For most request, the
-   returned MIME type is ``text/plain``. All text is encoded in Unicode
-   (UTF-8), and this is explicitly stated in the returned
-   ``Content-type``, as ``text/plain;charset=utf-8``.
-
--  ``Cache-control``
-
-   The cache control HTTP response header provides a suggestion for
-   client caching mechanisms on how to treat the returned information.
-   CouchDB typically returns the ``must-revalidate``, which indicates
-   that the information should be revalidated if possible. This is used
-   to ensure that the dynamic nature of the content is correctly
-   updated.
-
--  ``Content-length``
-
-   The length (in bytes) of the returned content.
-
--  ``Etag``
-
-   The ``Etag`` HTTP header field is used to show the revision for a
-   document, or a view.
-
-   ETags have been assigned to a map/reduce group (the collection of
-   views in a single design document). Any change to any of the indexes
-   for those views would generate a new ETag for all view URL's in a
-   single design doc, even if that specific view's results had not
-   changed.
-
-   Each ``_view`` URL has its own ETag which only gets updated when
-   changes are made to the database that effect that index. If the
-   index for that specific view does not change, that view keeps the
-   original ETag head (therefore sending back 304 Not Modified more
-   often).
-
-.. _json:
-
-JSON Basics
-===========
-
-The majority of requests and responses to CouchDB use the JavaScript
-Object Notation (JSON) for formatting the content and structure of the
-data and responses.
-
-JSON is used because it is the simplest and easiest to use solution for
-working with data within a web browser, as JSON structures can be
-evaluated and used as JavaScript objects within the web browser
-environment. JSON also integrates with the server-side JavaScript used
-within CouchDB.
-
-JSON supports the same basic types as supported by JavaScript, these
-are:
-
--  Number (either integer or floating-point).
-
--  String; this should be enclosed by double-quotes and supports Unicode
-   characters and backslash escaping. For example:
-
-   .. code-block:: javascript
-
-       "A String"
-
--  Boolean - a ``true`` or ``false`` value. You can use these strings
-   directly. For example:
-
-   .. code-block:: javascript
-
-       { "value": true}
-
--  Array - a list of values enclosed in square brackets. For example:
-
-   .. code-block:: javascript
-
-       ["one", "two", "three"]
-
--  Object - a set of key/value pairs (i.e. an associative array, or
-   hash). The key must be a string, but the value can be any of the
-   supported JSON values. For example:
-
-   .. code-block:: javascript
-
-       {
-          "servings" : 4,
-          "subtitle" : "Easy to make in advance, and then cook when ready",
-          "cooktime" : 60,
-          "title" : "Chicken Coriander"
-       }
-           
-
-   In CouchDB, the JSON object is used to represent a variety of
-   structures, including the main CouchDB document.
-
-Parsing JSON into a JavaScript object is supported through the
-``JSON.parse()`` function in JavaScript, or through various libraries that
-will perform the parsing of the content into a JavaScript object for
-you. Libraries for parsing and generating JSON are available in many
-languages, including Perl, Python, Ruby, Erlang and others.
-
-.. warning::
-   Care should be taken to ensure that your JSON structures are
-   valid, invalid structures will cause CouchDB to return an HTTP status code
-   of 500 (server error).
-
-.. _errors:
-
-HTTP Status Codes
-=================
-
-With the interface to CouchDB working through HTTP, error codes and
-statuses are reported using a combination of the HTTP status code
-number, and corresponding data in the body of the response data.
-
-A list of the error codes returned by CouchDB, and generic descriptions
-of the related errors are provided below. The meaning of different
-status codes for specific request types are provided in the
-corresponding API call reference.
-
--  ``200 - OK``
-
-   Request completed successfully.
-
--  ``201 - Created``
-
-   Document created successfully.
-
--  ``202 - Accepted``
-
-   Request has been accepted, but the corresponding operation may not
-   have completed. This is used for background operations, such as
-   database compaction.
-
--  ``304 - Not Modified``
-
-   The additional content requested has not been modified. This is used
-   with the ETag system to identify the version of information returned.
-
--  ``400 - Bad Request``
-
-   Bad request structure. The error can indicate an error with the
-   request URL, path or headers. Differences in the supplied MD5 hash
-   and content also trigger this error, as this may indicate message
-   corruption.
-
--  ``401 - Unauthorized``
-
-   The item requested was not available using the supplied
-   authorization, or authorization was not supplied.
-
--  ``403 - Forbidden``
-
-   The requested item or operation is forbidden.
-
--  ``404 - Not Found``
-
-   The requested content could not be found. The content will include
-   further information, as a JSON object, if available. The structure
-   will contain two keys, ``error`` and ``reason``. For example:
-
-   .. code-block:: javascript
-
-       {"error":"not_found","reason":"no_db_file"}
-
--  ``405 - Resource Not Allowed``
-
-   A request was made using an invalid HTTP request type for the URL
-   requested. For example, you have requested a ``PUT`` when a ``POST``
-   is required. Errors of this type can also triggered by invalid URL
-   strings.
-
--  ``406 - Not Acceptable``
-
-   The requested content type is not supported by the server.
-
--  ``409 - Conflict``
-
-   Request resulted in an update conflict.
-
--  ``412 - Precondition Failed``
-
-   The request headers from the client and the capabilities of the
-   server do not match.
-
--  ``415 - Bad Content Type``
-
-   The content types supported, and the content type of the information
-   being requested or submitted indicate that the content type is not
-   supported.
-
--  ``416 - Requested Range Not Satisfiable``
-
-   The range specified in the request header cannot be satisfied by the
-   server.
-
--  ``417 - Expectation Failed``
-
-   When sending documents in bulk, the bulk load operation failed.
-
--  ``500 - Internal Server Error``
-
-   The request was invalid, either because the supplied JSON was
-   invalid, or invalid information was supplied as part of the request.
-
-HTTP Range Requests
-===================
-
-HTTP allows you to specify byte ranges for requests. This allows the
-implementation of resumable downloads and skippable audio and video
-streams alike. This is available for all attachments inside CouchDB.
-
-This is just a real quick run through how this looks under the hood.
-Usually, you will have larger binary files to serve from CouchDB, like
-MP3s and videos, but to make things a little more obvious, I use a text
-file here (Note that I use the ``application/octet-stream`` Content-Type
-instead of ``text/plain``).
-
-.. code-block:: bash
-
-    shell> cat file.txt
-    My hovercraft is full of eels!
-
-Now let's store this text file as an attachment in CouchDB. First, we
-create a database:
-
-.. code-block:: bash
-
-    shell> curl -X PUT http://127.0.0.1:5984/test
-    {"ok":true}
-
-Then we create a new document and the file attachment in one go:
-
-.. code-block:: bash
-
-    shell> curl -X PUT http://127.0.0.1:5984/test/doc/file.txt \
-                -H "Content-Type: application/octet-stream" -d@file.txt
-    {"ok":true,"id":"doc","rev":"1-287a28fa680ae0c7fb4729bf0c6e0cf2"}
-
-Now we can request the whole file easily:
-
-.. code-block:: bash
-
-    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt
-    My hovercraft is full of eels!
-
-But say we only want the first 13 bytes:
-
-.. code-block:: bash
-
-    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt \
-                -H "Range: bytes=0-12"
-    My hovercraft
-
-HTTP supports many ways to specify single and even multiple byte
-ranges. Read all about it in `RFC 2616`_.
-
-.. note::
-   Databases that have been created with CouchDB 1.0.2 or earlier will
-   support range requests in |version|, but they are using a less-optimal
-   algorithm. If you plan to make heavy use of this feature, make sure
-   to compact your database with CouchDB |version| to take advantage of a
-   better algorithm to find byte ranges.
-
-.. _RFC 2616: http://tools.ietf.org/html/rfc2616#section-14.27

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c747953/share/doc/src/api/basics.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/basics.rst b/share/doc/src/api/basics.rst
new file mode 100644
index 0000000..83b1445
--- /dev/null
+++ b/share/doc/src/api/basics.rst
@@ -0,0 +1,462 @@
+.. 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.
+
+.. _api/basics:
+
+==========
+API Basics
+==========
+
+The CouchDB API is the primary method of interfacing to a CouchDB
+instance. Requests are made using HTTP and requests are used to request
+information from the database, store new data, and perform views and
+formatting of the information stored within the documents.
+
+Requests to the API can be categorised by the different areas of the
+CouchDB system that you are accessing, and the HTTP method used to send
+the request. Different methods imply different operations, for example
+retrieval of information from the database is typically handled by the
+``GET`` operation, while updates are handled by either a ``POST`` or
+``PUT`` request. There are some differences between the information that
+must be supplied for the different methods. For a guide to the basic
+HTTP methods and request structure, see :ref:`api/format`.
+
+For nearly all operations, the submitted data, and the returned data
+structure, is defined within a JavaScript Object Notation (JSON) object.
+Basic information on the content and data types for JSON are provided in
+:ref:`json`.
+
+Errors when accessing the CouchDB API are reported using standard HTTP
+Status Codes. A guide to the generic codes returned by CouchDB are
+provided in :ref:`errors`.
+
+When accessing specific areas of the CouchDB API, specific information
+and examples on the HTTP methods and request, JSON structures, and error
+codes are provided.
+
+.. _api/format:
+
+Request Format and Responses
+============================
+
+CouchDB supports the following HTTP request methods:
+
+-  ``GET``
+
+   Request the specified item. As with normal HTTP requests, the format
+   of the URL defines what is returned. With CouchDB this can include
+   static items, database documents, and configuration and statistical
+   information. In most cases the information is returned in the form of
+   a JSON document.
+
+-  ``HEAD``
+
+   The ``HEAD`` method is used to get the HTTP header of a ``GET``
+   request without the body of the response.
+
+-  ``POST``
+
+   Upload data. Within CouchDB ``POST`` is used to set values, including
+   uploading documents, setting document values, and starting certain
+   administration commands.
+
+-  ``PUT``
+
+   Used to put a specified resource. In CouchDB ``PUT`` is used to
+   create new objects, including databases, documents, views and design
+   documents.
+
+-  ``DELETE``
+
+   Deletes the specified resource, including documents, views, and
+   design documents.
+
+-  ``COPY``
+
+   A special method that can be used to copy documents and objects.
+
+If you use the an unsupported HTTP request type with a URL that does not
+support the specified type, a 405 error will be returned, listing the
+supported HTTP methods. For example:
+
+.. code-block:: javascript
+
+    {
+        "error":"method_not_allowed",
+        "reason":"Only GET,HEAD allowed"
+    }
+          
+
+The CouchDB design document API and the functions when returning HTML
+(for example as part of a show or list) enables you to include custom
+HTTP headers through the ``headers`` block of the return object.
+
+HTTP Headers
+============
+
+Because CouchDB uses HTTP for all communication, you need to ensure that
+the correct HTTP headers are supplied (and processed on retrieval) so
+that you get the right format and encoding. Different environments and
+clients will be more or less strict on the effect of these HTTP headers
+(especially when not present). Where possible you should be as specific
+as possible.
+
+Request Headers
+---------------
+
+-  ``Content-type``
+
+   Specifies the content type of the information being supplied within
+   the request. The specification uses MIME type specifications. For the
+   majority of requests this will be JSON (``application/json``). For
+   some settings the MIME type will be plain text. When uploading
+   attachments it should be the corresponding MIME type for the
+   attachment or binary (``application/octet-stream``).
+
+   The use of the ``Content-type`` on a request is highly recommended.
+
+-  ``Accept``
+
+   Specifies the list of accepted data types to be returned by the
+   server (i.e. that are accepted/understandable by the client). The
+   format should be a list of one or more MIME types, separated by
+   colons.
+
+   For the majority of requests the definition should be for JSON data
+   (``application/json``). For attachments you can either specify the
+   MIME type explicitly, or use ``*/*`` to specify that all file types
+   are supported. If the ``Accept`` header is not supplied, then the
+   ``*/*`` MIME type is assumed (i.e. client accepts all formats).
+
+   The use of ``Accept`` in queries for CouchDB is not required, but is
+   highly recommended as it helps to ensure that the data returned can
+   be processed by the client.
+
+   If you specify a data type using the ``Accept`` header, CouchDB will
+   honor the specified type in the ``Content-type`` header field
+   returned. For example, if you explicitly request ``application/json``
+   in the ``Accept`` of a request, the returned HTTP headers will use
+   the value in the returned ``Content-type`` field.
+
+   For example, when sending a request without an explicit ``Accept``
+   header, or when specifying ``*/*``:
+
+   .. code-block:: http
+
+       GET /recipes HTTP/1.1
+       Host: couchdb:5984
+       Accept: */*
+
+   The returned headers are:
+
+   .. code-block:: http
+
+       Server: CouchDB/1.0.1 (Erlang OTP/R13B)
+       Date: Thu, 13 Jan 2011 13:39:34 GMT
+       Content-Type: text/plain;charset=utf-8
+       Content-Length: 227
+       Cache-Control: must-revalidate
+
+   Note that the returned content type is ``text/plain`` even though the
+   information returned by the request is in JSON format.
+
+   Explicitly specifying the ``Accept`` header:
+
+   .. code-block:: http
+
+       GET /recipes HTTP/1.1
+       Host: couchdb:5984
+       Accept: application/json
+
+   The headers returned include the ``application/json`` content type:
+
+   .. code-block:: http
+
+       Server: CouchDB/|version| (Erlang OTP/R13B)
+       Date: Thu, 13 Jan 2011 13:40:11 GMT
+       Content-Type: application/json
+       Content-Length: 227
+       Cache-Control: must-revalidate
+
+Response Headers
+----------------
+
+Response headers are returned by the server when sending back content
+and include a number of different header fields, many of which are
+standard HTTP response header and have no significance to CouchDB
+operation. The list of response headers important to CouchDB are listed
+below.
+
+-  ``Content-type``
+
+   Specifies the MIME type of the returned data. For most request, the
+   returned MIME type is ``text/plain``. All text is encoded in Unicode
+   (UTF-8), and this is explicitly stated in the returned
+   ``Content-type``, as ``text/plain;charset=utf-8``.
+
+-  ``Cache-control``
+
+   The cache control HTTP response header provides a suggestion for
+   client caching mechanisms on how to treat the returned information.
+   CouchDB typically returns the ``must-revalidate``, which indicates
+   that the information should be revalidated if possible. This is used
+   to ensure that the dynamic nature of the content is correctly
+   updated.
+
+-  ``Content-length``
+
+   The length (in bytes) of the returned content.
+
+-  ``Etag``
+
+   The ``Etag`` HTTP header field is used to show the revision for a
+   document, or a view.
+
+   ETags have been assigned to a map/reduce group (the collection of
+   views in a single design document). Any change to any of the indexes
+   for those views would generate a new ETag for all view URL's in a
+   single design doc, even if that specific view's results had not
+   changed.
+
+   Each ``_view`` URL has its own ETag which only gets updated when
+   changes are made to the database that effect that index. If the
+   index for that specific view does not change, that view keeps the
+   original ETag head (therefore sending back 304 Not Modified more
+   often).
+
+.. _json:
+
+JSON Basics
+===========
+
+The majority of requests and responses to CouchDB use the JavaScript
+Object Notation (JSON) for formatting the content and structure of the
+data and responses.
+
+JSON is used because it is the simplest and easiest to use solution for
+working with data within a web browser, as JSON structures can be
+evaluated and used as JavaScript objects within the web browser
+environment. JSON also integrates with the server-side JavaScript used
+within CouchDB.
+
+JSON supports the same basic types as supported by JavaScript, these
+are:
+
+-  Number (either integer or floating-point).
+
+-  String; this should be enclosed by double-quotes and supports Unicode
+   characters and backslash escaping. For example:
+
+   .. code-block:: javascript
+
+       "A String"
+
+-  Boolean - a ``true`` or ``false`` value. You can use these strings
+   directly. For example:
+
+   .. code-block:: javascript
+
+       { "value": true}
+
+-  Array - a list of values enclosed in square brackets. For example:
+
+   .. code-block:: javascript
+
+       ["one", "two", "three"]
+
+-  Object - a set of key/value pairs (i.e. an associative array, or
+   hash). The key must be a string, but the value can be any of the
+   supported JSON values. For example:
+
+   .. code-block:: javascript
+
+       {
+          "servings" : 4,
+          "subtitle" : "Easy to make in advance, and then cook when ready",
+          "cooktime" : 60,
+          "title" : "Chicken Coriander"
+       }
+           
+
+   In CouchDB, the JSON object is used to represent a variety of
+   structures, including the main CouchDB document.
+
+Parsing JSON into a JavaScript object is supported through the
+``JSON.parse()`` function in JavaScript, or through various libraries that
+will perform the parsing of the content into a JavaScript object for
+you. Libraries for parsing and generating JSON are available in many
+languages, including Perl, Python, Ruby, Erlang and others.
+
+.. warning::
+   Care should be taken to ensure that your JSON structures are
+   valid, invalid structures will cause CouchDB to return an HTTP status code
+   of 500 (server error).
+
+.. _errors:
+
+HTTP Status Codes
+=================
+
+With the interface to CouchDB working through HTTP, error codes and
+statuses are reported using a combination of the HTTP status code
+number, and corresponding data in the body of the response data.
+
+A list of the error codes returned by CouchDB, and generic descriptions
+of the related errors are provided below. The meaning of different
+status codes for specific request types are provided in the
+corresponding API call reference.
+
+-  ``200 - OK``
+
+   Request completed successfully.
+
+-  ``201 - Created``
+
+   Document created successfully.
+
+-  ``202 - Accepted``
+
+   Request has been accepted, but the corresponding operation may not
+   have completed. This is used for background operations, such as
+   database compaction.
+
+-  ``304 - Not Modified``
+
+   The additional content requested has not been modified. This is used
+   with the ETag system to identify the version of information returned.
+
+-  ``400 - Bad Request``
+
+   Bad request structure. The error can indicate an error with the
+   request URL, path or headers. Differences in the supplied MD5 hash
+   and content also trigger this error, as this may indicate message
+   corruption.
+
+-  ``401 - Unauthorized``
+
+   The item requested was not available using the supplied
+   authorization, or authorization was not supplied.
+
+-  ``403 - Forbidden``
+
+   The requested item or operation is forbidden.
+
+-  ``404 - Not Found``
+
+   The requested content could not be found. The content will include
+   further information, as a JSON object, if available. The structure
+   will contain two keys, ``error`` and ``reason``. For example:
+
+   .. code-block:: javascript
+
+       {"error":"not_found","reason":"no_db_file"}
+
+-  ``405 - Resource Not Allowed``
+
+   A request was made using an invalid HTTP request type for the URL
+   requested. For example, you have requested a ``PUT`` when a ``POST``
+   is required. Errors of this type can also triggered by invalid URL
+   strings.
+
+-  ``406 - Not Acceptable``
+
+   The requested content type is not supported by the server.
+
+-  ``409 - Conflict``
+
+   Request resulted in an update conflict.
+
+-  ``412 - Precondition Failed``
+
+   The request headers from the client and the capabilities of the
+   server do not match.
+
+-  ``415 - Bad Content Type``
+
+   The content types supported, and the content type of the information
+   being requested or submitted indicate that the content type is not
+   supported.
+
+-  ``416 - Requested Range Not Satisfiable``
+
+   The range specified in the request header cannot be satisfied by the
+   server.
+
+-  ``417 - Expectation Failed``
+
+   When sending documents in bulk, the bulk load operation failed.
+
+-  ``500 - Internal Server Error``
+
+   The request was invalid, either because the supplied JSON was
+   invalid, or invalid information was supplied as part of the request.
+
+HTTP Range Requests
+===================
+
+HTTP allows you to specify byte ranges for requests. This allows the
+implementation of resumable downloads and skippable audio and video
+streams alike. This is available for all attachments inside CouchDB.
+
+This is just a real quick run through how this looks under the hood.
+Usually, you will have larger binary files to serve from CouchDB, like
+MP3s and videos, but to make things a little more obvious, I use a text
+file here (Note that I use the ``application/octet-stream`` Content-Type
+instead of ``text/plain``).
+
+.. code-block:: bash
+
+    shell> cat file.txt
+    My hovercraft is full of eels!
+
+Now let's store this text file as an attachment in CouchDB. First, we
+create a database:
+
+.. code-block:: bash
+
+    shell> curl -X PUT http://127.0.0.1:5984/test
+    {"ok":true}
+
+Then we create a new document and the file attachment in one go:
+
+.. code-block:: bash
+
+    shell> curl -X PUT http://127.0.0.1:5984/test/doc/file.txt \
+                -H "Content-Type: application/octet-stream" -d@file.txt
+    {"ok":true,"id":"doc","rev":"1-287a28fa680ae0c7fb4729bf0c6e0cf2"}
+
+Now we can request the whole file easily:
+
+.. code-block:: bash
+
+    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt
+    My hovercraft is full of eels!
+
+But say we only want the first 13 bytes:
+
+.. code-block:: bash
+
+    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt \
+                -H "Range: bytes=0-12"
+    My hovercraft
+
+HTTP supports many ways to specify single and even multiple byte
+ranges. Read all about it in `RFC 2616`_.
+
+.. note::
+   Databases that have been created with CouchDB 1.0.2 or earlier will
+   support range requests in |version|, but they are using a less-optimal
+   algorithm. If you plan to make heavy use of this feature, make sure
+   to compact your database with CouchDB |version| to take advantage of a
+   better algorithm to find byte ranges.
+
+.. _RFC 2616: http://tools.ietf.org/html/rfc2616#section-14.27

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c747953/share/doc/src/api/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/index.rst b/share/doc/src/api/index.rst
new file mode 100644
index 0000000..398a058
--- /dev/null
+++ b/share/doc/src/api/index.rst
@@ -0,0 +1,43 @@
+.. 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.
+
+.. _api:
+
+API Reference
+=============
+
+The components of the API URL path help determine the part of the
+CouchDB server that is being accessed. The result is the structure of
+the URL request both identifies and effectively describes the area of
+the database you are accessing.
+
+As with all URLs, the individual components are separated by a forward
+slash.
+
+As a general rule, URL components and JSON fields starting with the
+``_`` (underscore) character represent a special component or entity
+within the server or returned object. For example, the URL fragment
+``/_all_dbs`` gets a list of all of the databases in a CouchDB instance.
+
+This reference is structured according to the URL structure, as below.
+
+.. toctree::
+   :maxdepth: 2
+
+   basics
+   database
+   documents
+   design
+   local
+   configuration
+   authn
+   misc

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c747953/share/doc/src/api/reference.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/reference.rst b/share/doc/src/api/reference.rst
deleted file mode 100644
index 59b3536..0000000
--- a/share/doc/src/api/reference.rst
+++ /dev/null
@@ -1,42 +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.
-
-.. _api-overview:
-
-API Reference
-=============
-
-The components of the API URL path help determine the part of the
-CouchDB server that is being accessed. The result is the structure of
-the URL request both identifies and effectively describes the area of
-the database you are accessing.
-
-As with all URLs, the individual components are separated by a forward
-slash.
-
-As a general rule, URL components and JSON fields starting with the
-``_`` (underscore) character represent a special component or entity
-within the server or returned object. For example, the URL fragment
-``/_all_dbs`` gets a list of all of the databases in a CouchDB instance.
-
-This reference is structured according to the URL structure, as below.
-
-.. toctree::
-   :maxdepth: 2
-
-   database
-   documents
-   local
-   design
-   misc
-   configuration
-   authn

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c747953/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index b51c853..eef82ca 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -28,14 +28,13 @@ Contents
     :numbered:
 
     intro
-    api-basics
     config/index
     replication
     replicator
     ddocs
     query-servers
     changes
-    api/reference
+    api/index
     json-structure
     contributing
     changelog

http://git-wip-us.apache.org/repos/asf/couchdb/blob/2c747953/share/doc/src/intro.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/intro.rst b/share/doc/src/intro.rst
index 8a831ee..faf6bcc 100644
--- a/share/doc/src/intro.rst
+++ b/share/doc/src/intro.rst
@@ -303,7 +303,7 @@ document ID that was returned:
      "_rev":"1-33b9fbce46930280dab37d672bbc8bb9",
      "company":"Example, Inc."}
 
-The API samples in the :ref:`api-basics` show the HTTP command, URL and any
+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.


[18/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Fix references.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/d6f745d6
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/d6f745d6
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/d6f745d6

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: d6f745d604df5723bd79714db9f1be1d756c6cae
Parents: 7315da0
Author: Alexander Shorin <kx...@apache.org>
Authored: Mon Jul 22 07:14:17 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/config/externals.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/d6f745d6/share/doc/src/config/externals.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/externals.rst b/share/doc/src/config/externals.rst
index 4f0d4e9..2b857cd 100644
--- a/share/doc/src/config/externals.rst
+++ b/share/doc/src/config/externals.rst
@@ -101,7 +101,7 @@ see :ref:`http-proxying`. For further background on the OS Daemon service, see
 .. _CouchDB Externals API: http://davispj.com/2010/09/26/new-couchdb-externals-api.html
 
 
-.. _config/os_daemons_settings:
+.. _config/os_daemon_settings:
 
 ``[os_daemon_settings]`` :: OS Daemons settings
 ===============================================
@@ -131,7 +131,7 @@ Delay in seconds between :ref:`os_daemon <config/os_daemons>` restarts::
 
 
 .. _update-notifications:
-.. _config/update-notification:
+.. _config/update_notification:
 
 ``[update_notification]`` :: Update notifications
 =================================================


[44/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add Paul Joseph Davis's guide to externals API.

http://davispj.com/2010/09/26/new-couchdb-externals-api.html


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/0ece2b65
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/0ece2b65
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/0ece2b65

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 0ece2b65af75d19a870a5e54e1eb7fcc5a70fd5e
Parents: f2a31b5
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 11:31:15 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 11:31:15 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am |   3 +
 share/doc/src/externals.rst | 266 +++++++++++++++++++++++++++++++++++++++
 share/doc/src/index.rst     |   1 +
 3 files changed, 270 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/0ece2b65/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 18f1c41..6583682 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -104,6 +104,7 @@ html_files = \
     html/_sources/replications/replicator.txt \
     html/_sources/changelog.txt \
     html/_sources/contributing.txt \
+    html/_sources/externals.txt \
     html/_sources/index.txt \
     html/_sources/intro.txt \
     html/_sources/json-structure.txt \
@@ -188,6 +189,7 @@ html_files = \
     html/replications/protocol.html \
     html/replications/replicator.html \
     html/changelog.html \
+    html/externals.html \
     html/index.html \
     html/intro.html \
     html/json-structure.html \
@@ -272,6 +274,7 @@ src_files = \
     ../src/replication/replicator.rst \
     ../src/changelog.rst \
     ../src/contributing.rst \
+    ../src/externals.rst \
     ../src/index.rst \
     ../src/intro.rst \
     ../src/json-structure.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/0ece2b65/share/doc/src/externals.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/externals.rst b/share/doc/src/externals.rst
new file mode 100644
index 0000000..10ed34a
--- /dev/null
+++ b/share/doc/src/externals.rst
@@ -0,0 +1,266 @@
+.. 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.
+
+
+.. _externals:
+
+=====================
+CouchDB Externals API
+=====================
+
+:Author: Paul Joseph Davis
+:Date: 2010-09-26
+
+For a bit of background, CouchDB has had an API for managing external OS
+processes [1] that are capable of handling HTTP requests for a given
+URL prefix. These OS processes communicate with CouchDB using JSON over
+stdio. They're dead simple to write and provide CouchDB users an easy way to
+extend CouchDB functionality.
+
+Even though they're dead simple to write, there are a few issues. The
+implementation in CouchDB does not provide fancy pooling semantics. The
+current API is explicitly synchronous which prevents people from writing
+event driven code in an external handler. In the end, they may be simple,
+but their simplicity is also quite limiting.
+
+During CouchCamp a few weeks ago I had multiple discussions with various people
+that wanted to see the _externals API modified in slight ways that weren't
+mutually compatible. After having multiple discussions with multiple people
+we formed a general consensus on what a new API could look like.
+
+The New Hotness
+---------------
+
+So the first idea for improving the _external API was to make CouchDB act as
+a reverse proxy. This would allow people to write an HTTP server that was as
+simple or as complicated as they wanted. It will allow people to change their
+networking configuration more easily and also allow for external processes to
+be hosted on nodes other than the one running CouchDB. Bottom line, it not
+only allows us to have similar semantics as _externals, it provides a lot more
+fringe benefits as well. I'm always a fan of extra awesomeness.
+
+After hitting on the idea of adding a reverse proxy, people quickly pointed
+out that it would require users to start manually managing their external
+processes using something like Runit [2] or Supervisord [3]. After some
+more discussions I ran into people that wanted something like _externals that
+didn't handle HTTP requests. After that it was easy to see that adding a second
+feature that managed OS processes was the way to go.
+
+I spent this weekend implementing both of these features. Both are at the stage
+of working but requiring more testing. In the case of the HTTP proxy I have no
+tests because I can't decide how to test the thing. If you have ideas, I'd
+sure like to hear them.
+
+[Update]: I woke up the other morning realizing that I was being an idiot and
+that Erlang is awesome. There's no reason that I can't have an HTTP client,
+proxy, and server all hosted in the same process. So that's what I did. It
+turns out to be a fairly nice way of configuring matching assertions between
+the client and the server to test the proxy transmissions.
+
+The code for both features is in this branch:
+
+    http://github.com/davisp/couchdb/tree/new_externals
+
+How does it work? - HTTP Proxying
+---------------------------------
+
+To configure a proxy handler, edit your local.ini and add a section like such:
+
+    [httpd_global_handlers]
+    _fti = {couch_httpd_proxy, handle_proxy_req, <<"http://127.0.0.1:5985">>}
+
+This would be approximately what you'd need to do to get CouchDB-Lucene handled
+through this interface. The URL you use to access a query would be:
+
+    http://127.0.0.1:5984/_fti/db_name/_design/foo/by_content?q=hello
+
+A couple things to note here. Anything in the path after the configured proxy
+name ("_fti" in this case) will be appended to the configured destination URL
+("http://127.0.0.1:5985" in this case). The query string and any associated
+body will also be proxied transparently.
+
+Also, of note is that there's nothing that limits on what resources can be
+proxied. You're free to choose any destination that the CouchDB node is capable
+of communicating with.
+
+How does it work? - OS Daemons
+------------------------------
+
+The second part of the new API gives CouchDB simple OS process management. When
+CouchDB boots it will start each configured OS daemon. If one of these daemons
+fails at some point, it will be restarted. If one of these daemons fails too
+often, CouchDB will stop attempting to start it.
+
+OS daemons are one-to-one. For each daemon, CouchDB will make sure that exactly
+one instance of it is alive. If you have something where you want multiple
+processes, you need to either tell CouchDB about each one, or have a main
+process that forks off the required sub-processes.
+
+To configure an OS daemon, add this to your local.ini::
+
+    [os_daemons]
+    my_daemon = /path/to/command -with args
+
+Configuration API
++++++++++++++++++
+
+As an added benefit, because stdio is now free, I implemented a simple API
+that OS daemons can use to read the configuration of their CouchDB host. This
+way you can have them store their configuration inside CouchDB's config system
+if you desire. Or they can peek at things like the bind_address and port that
+CouchDB is using.
+
+A request for a config section looks like this::
+
+    ["get", "os_daemons"]\n
+
+And the response::
+
+    {"my_daemon": "/path/to/command -with args"}\n
+
+Or to get a specific key::
+
+    ["get", "os_daemons", "my_daemon"]\n
+
+And the response::
+
+    "/path/to/command -with args"\n
+
+All requests and responses are terminated with a newline (indicated by \n).
+
+Logging API
++++++++++++
+
+There's also an API for adding messages to CouchDB's logs. Its simply::
+
+    ["log", $MESG]\n
+
+Where $MESG is any arbitrary JSON. There is no response from this command. As
+with the config API, the trailing "\n" represents a newline byte.
+
+Dynamic Daemons
++++++++++++++++
+
+The OS daemons react in real time to changes to the configuration system. If
+you set or delete keys in the os_daemons section, the corresponding daemons
+will be started or killed as appropriate.
+
+Neat. But So What?
+------------------
+
+It was suggested that a good first demo would be  a Node.js [5] handler. So, I
+present to you a "Hello, World" Node.js handler. Also, remember that this
+currently relies on code in my fork on GitHub [6].
+
+File `node-hello-world.js`::
+
+    var http = require('http');
+    var sys = require('sys');
+
+    // Send a log message to be included in CouchDB's
+    // log files.
+
+    var log = function(mesg) {
+      console.log(JSON.stringify(["log", mesg]));
+    }
+
+    // The Node.js example HTTP server
+
+    var server = http.createServer(function (req, resp) {
+      resp.writeHead(200, {'Content-Type': 'text/plain'});
+      resp.end('Hello World\n');
+      log(req.method + " " + req.url);
+    })
+
+    // We use stdin in a couple ways. First, we
+    // listen for data that will be the requested
+    // port information. We also listen for it
+    // to close which indicates that CouchDB has
+    // exited and that means its time for us to
+    // exit as well.
+
+    var stdin = process.openStdin();
+
+    stdin.on('data', function(d) {
+      server.listen(parseInt(JSON.parse(d)));
+    });
+
+    stdin.on('end', function () {
+      process.exit(0);
+    });
+
+    // Send the request for the port to listen on.
+
+    console.log(JSON.stringify(["get", "node_hello", "port"]));
+
+File `local.ini` (Just add these to what you have)::
+
+    [log]
+    level = info
+
+    [os_daemons]
+    node_hello = /path/to/node-hello-world.js
+
+    [node_hello]
+    port = 8000
+
+    [httpd_global_handlers]
+    _hello = {couch_httpd_proxy, handle_proxy_req, <<"http://127.0.0.1:8000">>}
+
+And then start CouchDB and try::
+
+    $ curl -v http://127.0.0.1:5984/_hello
+    * About to connect() to 127.0.0.1 port 5984 (#0)
+    *   Trying 127.0.0.1... connected
+    * Connected to 127.0.0.1 (127.0.0.1) port 5984 (#0)
+    > GET /_hello HTTP/1.1
+    > User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3
+    > Host: 127.0.0.1:5984
+    > Accept: */*
+    >
+    < HTTP/1.1 200
+    < Transfer-Encoding: chunked
+    < Server: CouchDB/1.3.0 (Erlang OTP/R14B)
+    < Date: Mon, 27 Sep 2010 01:13:37 GMT
+    < Content-Type: text/plain
+    < Connection: keep-alive
+    <
+    Hello World
+    * Connection #0 to host 127.0.0.1 left intact
+    * Closing connection #0
+
+The corresponding CouchDB logs look like::
+
+    Apache CouchDB 1.3.0 (LogLevel=info) is starting.
+    Apache CouchDB has started. Time to relax.
+    [info] [<0.31.0>] Apache CouchDB has started on http://127.0.0.1:5984/
+    [info] [<0.105.0>] 127.0.0.1 - - 'GET' /_hello 200
+    [info] [<0.95.0>] Daemon "node-hello" :: GET /
+
+
+[1]:  http://wiki.apache.org/couchdb/ExternalProcesses
+[2]:  http://smarden.org/runit/
+[3]:  http://supervisord.org/
+[4]:  http://www.mikealrogers.com/
+[5]:  http://nodejs.org/
+[6]:  http://github.com/davisp/couchdb/tree/new_externals
+
+
+Copyright Notice
+----------------
+
+Copyright 2008-2010 Paul Joseph Davis
+
+License
+-------
+
+http://creativecommons.org/licenses/by/3.0/

http://git-wip-us.apache.org/repos/asf/couchdb/blob/0ece2b65/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index c95da25..1cc84af 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -32,6 +32,7 @@ Contents
     config/index
     replication/index
     couchapp/index
+    externals
     query-server/index
     fauxton/index
     api/index


[05/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Revert HTTP range requests as attachments API subsection.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/5be91ece
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/5be91ece
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/5be91ece

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 5be91ece4af11f470203ab14fea8cecc867dca04
Parents: 485d001
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 21:16:26 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/documents.rst | 64 ++++++++++++++++++++++++++++++++++++
 1 file changed, 64 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/5be91ece/share/doc/src/api/documents.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/documents.rst b/share/doc/src/api/documents.rst
index ac2c763..a1ca0ab 100644
--- a/share/doc/src/api/documents.rst
+++ b/share/doc/src/api/documents.rst
@@ -831,6 +831,70 @@ if you were accessing a static file. The returned HTTP ``Content-type``
 will be the same as the content type set when the document attachment
 was submitted into the database.
 
+.. _api/doc/attachment/range:
+
+HTTP Range Requests
+-------------------
+
+HTTP allows you to specify byte ranges for requests. This allows the
+implementation of resumable downloads and skippable audio and video
+streams alike. This is available for all attachments inside CouchDB.
+
+This is just a real quick run through how this looks under the hood.
+Usually, you will have larger binary files to serve from CouchDB, like
+MP3s and videos, but to make things a little more obvious, I use a text
+file here (Note that I use the ``application/octet-stream`` Content-Type
+instead of ``text/plain``).
+
+.. code-block:: bash
+
+    shell> cat file.txt
+    My hovercraft is full of eels!
+
+Now let's store this text file as an attachment in CouchDB. First, we
+create a database:
+
+.. code-block:: bash
+
+    shell> curl -X PUT http://127.0.0.1:5984/test
+    {"ok":true}
+
+Then we create a new document and the file attachment in one go:
+
+.. code-block:: bash
+
+    shell> curl -X PUT http://127.0.0.1:5984/test/doc/file.txt \
+                -H "Content-Type: application/octet-stream" -d@file.txt
+    {"ok":true,"id":"doc","rev":"1-287a28fa680ae0c7fb4729bf0c6e0cf2"}
+
+Now we can request the whole file easily:
+
+.. code-block:: bash
+
+    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt
+    My hovercraft is full of eels!
+
+But say we only want the first 13 bytes:
+
+.. code-block:: bash
+
+    shell> curl -X GET http://127.0.0.1:5984/test/doc/file.txt \
+                -H "Range: bytes=0-12"
+    My hovercraft
+
+HTTP supports many ways to specify single and even multiple byte
+ranges. Read all about it in `RFC 2616`_.
+
+.. note::
+   Databases that have been created with CouchDB 1.0.2 or earlier will
+   support range requests in |version|, but they are using a less-optimal
+   algorithm. If you plan to make heavy use of this feature, make sure
+   to compact your database with CouchDB |version| to take advantage of a
+   better algorithm to find byte ranges.
+
+.. _RFC 2616: http://tools.ietf.org/html/rfc2616#section-14.27
+
+
 .. _api/doc/attachment.put:
 
 ``PUT /db/doc/attachment``


[34/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Wrong extension.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/e22a833c
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/e22a833c
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/e22a833c

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: e22a833c95310948cfceb4e317af66954ca75bfe
Parents: 319bb8a
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 09:15:49 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/e22a833c/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 26fdc5e..1179968 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -86,11 +86,11 @@ html_files = \
     html/_sources/fauxton/addons.txt \
     html/_sources/fauxton/index.txt \
     html/_sources/fauxton/install.txt \
-    html/_sources/install/index.html \
-    html/_sources/install/freebsd.html \
-    html/_sources/install/gentoo.html \
-    html/_sources/install/unix.html \
-    html/_sources/install/windows.html \
+    html/_sources/install/index.txt \
+    html/_sources/install/freebsd.txt \
+    html/_sources/install/gentoo.txt \
+    html/_sources/install/unix.txt \
+    html/_sources/install/windows.txt \
     html/_sources/query-server/index.txt \
     html/_sources/query-server/erlang.txt \
     html/_sources/query-server/javascript.txt \


[39/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Fix typo in autogenerated content.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/c9c775cc
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/c9c775cc
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/c9c775cc

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: c9c775ccdaaed8307f8b469cdb494ba04e779998
Parents: 2c3d449
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 04:47:43 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am | 54 ++++++++++++++++++++--------------------
 1 file changed, 27 insertions(+), 27 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/c9c775cc/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index abb9097..589fe95 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -45,30 +45,30 @@ html_files = \
     html/_images/futon-editeddoc.png \
     html/_images/futon-overview.png \
     html/_images/futon-replform.png \
-    html/_source/api/basics.txt \
-    html/_source/api/index.txt \
-    html/_source/api/local.txt \
-    html/_source/api/database/all-docs.txt \
-    html/_source/api/database/bulk-docs.txt \
-    html/_source/api/database/changes.txt \
-    html/_source/api/database/common.txt \
-    html/_source/api/database/compact.txt \
-    html/_source/api/database/index.txt \
-    html/_source/api/database/misc.txt \
-    html/_source/api/database/security.txt \
-    html/_source/api/database/temp-views.txt \
-    html/_source/api/document/attachments.txt \
-    html/_source/api/document/common.txt \
-    html/_source/api/document/index.txt \
-    html/_source/api/ddoc/common.txt \
-    html/_source/api/ddoc/index.txt \
-    html/_source/api/ddoc/render.txt \
-    html/_source/api/ddoc/rewrites.txt \
-    html/_source/api/ddoc/views.txt \
-    html/_source/api/server/authn.txt \
-    html/_source/api/server/common.txt \
-    html/_source/api/server/configuration.txt \
-    html/_source/api/server/index.txt \
+    html/_sources/api/basics.txt \
+    html/_sources/api/index.txt \
+    html/_sources/api/local.txt \
+    html/_sources/api/database/all-docs.txt \
+    html/_sources/api/database/bulk-docs.txt \
+    html/_sources/api/database/changes.txt \
+    html/_sources/api/database/common.txt \
+    html/_sources/api/database/compact.txt \
+    html/_sources/api/database/index.txt \
+    html/_sources/api/database/misc.txt \
+    html/_sources/api/database/security.txt \
+    html/_sources/api/database/temp-views.txt \
+    html/_sources/api/document/attachments.txt \
+    html/_sources/api/document/common.txt \
+    html/_sources/api/document/index.txt \
+    html/_sources/api/ddoc/common.txt \
+    html/_sources/api/ddoc/index.txt \
+    html/_sources/api/ddoc/render.txt \
+    html/_sources/api/ddoc/rewrites.txt \
+    html/_sources/api/ddoc/views.txt \
+    html/_sources/api/server/authn.txt \
+    html/_sources/api/server/common.txt \
+    html/_sources/api/server/configuration.txt \
+    html/_sources/api/server/index.txt \
     html/_sources/config/auth.txt \
     html/_sources/config/compaction.txt \
     html/_sources/config/couchdb.txt \
@@ -83,9 +83,9 @@ html_files = \
     html/_sources/config/services.txt \
     html/_sources/config/intro.txt \
     html/_sources/config/proxying.txt \
-    html/_source/install/index.html \
-    html/_source/install/unix.html \
-    html/_source/install/windows.html \
+    html/_sources/install/index.html \
+    html/_sources/install/unix.html \
+    html/_sources/install/windows.html \
     html/_sources/query-server/index.txt \
     html/_sources/query-server/erlang.txt \
     html/_sources/query-server/javascript.txt \


[26/50] [abbrv] Split API articles into small files focused on specific problem.

Posted by kx...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/misc.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/misc.rst b/share/doc/src/api/misc.rst
deleted file mode 100644
index bfbf1ad..0000000
--- a/share/doc/src/api/misc.rst
+++ /dev/null
@@ -1,898 +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.
-
-.. _api/misc:
-
-=====================
-Miscellaneous Methods
-=====================
-
-The CouchDB Miscellaneous interface provides the basic interface to a
-CouchDB server for obtaining CouchDB information and getting and setting
-configuration information.
-
-A list of the available methods and URL paths are provided below:
-
-+--------+-------------------------+-------------------------------------------+
-| Method | Path                    | Description                               |
-+========+=========================+===========================================+
-| GET    | /                       |  Get the welcome message and version      |
-|        |                         |  information                              |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_active_tasks          |  Obtain a list of the tasks running in the|
-|        |                         |  server                                   |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_all_dbs               |  Get a list of all the DBs                |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_db_updates            |  A feed of database events                |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_log                   |  Return the server log file               |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /_replicate             |  Set or cancel replication                |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /_restart               |  Restart the server                       |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_stats                 |  Return server statistics                 |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_utils                 |  CouchDB administration interface (Futon) |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_uuids                 |  Get generated UUIDs from the server      |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /favicon.ico            |  Get the site icon                        |
-+--------+-------------------------+-------------------------------------------+
-
-.. _api/misc/root:
-.. _api/misc/root.get:
-
-``GET /``
-=========
-
-* **Method**: ``GET /``
-* **Request**: None
-* **Response**: Welcome message and version
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-Accessing the root of a CouchDB instance returns meta information about
-the instance. The response is a JSON structure containing information
-about the server, including a welcome message and the version of the
-server.
-
-.. code-block:: javascript
-
-    {
-       "couchdb" : "Welcome",
-       "version" : "1.0.1"
-    }
-
-.. _api/misc/active_tasks:
-.. _api/misc/active_tasks.get:
-
-``GET /_active_tasks``
-======================
-
-* **Method**: ``GET /_active_tasks``
-* **Request**: None
-* **Response**: List of running tasks, including the task type, name, status
-  and process ID
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-You can obtain a list of active tasks by using the ``/_active_tasks``
-URL. The result is a JSON array of the currently running tasks, with
-each task being described with a single object. For example:
-
-.. code-block:: javascript
-
-    [
-       {
-        "pid" : "<0.11599.0>",
-        "status" : "Copied 0 of 18369 changes (0%)",
-        "task" : "recipes",
-        "type" : "Database Compaction"
-        }
-    ]
-
-The returned structure includes the following fields for each task:
-
-* **tasks** [array]: Active Task
-
-  * **pid**:Process ID
-  * **status**: Task status message
-  * **task**: Task name
-  * **type**: Operation Type
-
-For operation type, valid values include:
-
--  ``Database Compaction``
-
--  ``Replication``
-
--  ``View Group Compaction``
-
--  ``View Group Indexer``
-
-.. _api/misc/all_dbs:
-.. _api/misc/all_dbs.get:
-
-``GET /_all_dbs``
-=================
-
-* **Method**: ``GET /_all_dbs``
-* **Request**: None
-* **Response**: JSON list of DBs
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-Returns a list of all the databases in the CouchDB instance. For
-example:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/_all_dbs
-    Accept: application/json
-
-The return is a JSON array:
-
-.. code-block:: javascript
-
-    [
-       "_users",
-       "contacts",
-       "docs",
-       "invoices",
-       "locations"
-    ]
-
-
-.. _api/misc/db_updates:
-.. _api/misc/db_updates.get:
-
-``GET /_db_updates``
-====================
-
-* **Method**: ``GET /_db_updates``
-* **Request**: None
-* **Admin Privileges Required**: yes
-* **Query Arguments**:
-
-  * **Argument**: feed
-
-    * **Description**: Format of the response feed
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**: longpoll
-    * **Supported Values**:
-
-      * **longpoll**: Closes the connection after the first event.
-      * **continuous**: Send a line of JSON per event. Keeps the socket open until ``timeout``.
-      * **eventsource**: Like, ``continuous``, but sends the events in EventSource format. See http://dev.w3.org/html5/eventsource/ for details,
-
-  * **Argument**: timeout
-
-    * **Description**: Number of seconds until CouchDB closes the connection.
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 60
-
-  * **Argument**: heartbeat
-
-    * **Description**: Whether CouchDB will send a newline character (``\n``) on ``timeout``.
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: true
-
-* **Return Codes**:
-
-  * **200**
-    Request completed successfully.
-
-Returns a list of all database events in the CouchDB instance.
-
-A database event is one of `created`, `updated`, `deleted`.
-
-For example:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/_db_events?feed=continuous
-    Accept: application/json
-
-.. code-block:: javascript
-
-    {"dbname":"my-database", "type":"created"}
-    {"dbname":"my-database", "type":"updated"}
-    {"dbname":"another-database", "type":"created"}
-    {"dbname":"my-database", "type":"deleted"}
-    {"dbname":"another-database", "type":"updated"}
-
-
-.. _api/misc/log:
-.. _api/misc/log.get:
-
-``GET /_log``
-=============
-
-* **Method**: ``GET /_log``
-* **Request**: None
-* **Response**: Log content
-* **Admin Privileges Required**: yes
-* **Query Arguments**:
-
-  * **Argument**: bytes
-
-    * **Description**:  Bytes to be returned
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 1000
-
-  * **Argument**: offset
-
-    * **Description**:  Offset in bytes where the log tail should be started
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 0
-
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-Gets the CouchDB log, equivalent to accessing the local log file of the
-corresponding CouchDB instance.
-
-When you request the log, the response is returned as plain (UTF-8)
-text, with an HTTP ``Content-type`` header as ``text/plain``.
-
-For example, the request:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/_log
-    Accept: */*
-
-The raw text is returned:
-
-.. code-block:: text
-
-    [Wed, 27 Oct 2010 10:49:42 GMT] [info] [<0.23338.2>] 192.168.0.2 - - 'PUT' /authdb 401
-    [Wed, 27 Oct 2010 11:02:19 GMT] [info] [<0.23428.2>] 192.168.0.116 - - 'GET' /recipes/FishStew 200
-    [Wed, 27 Oct 2010 11:02:19 GMT] [info] [<0.23428.2>] 192.168.0.116 - - 'GET' /_session 200
-    [Wed, 27 Oct 2010 11:02:19 GMT] [info] [<0.24199.2>] 192.168.0.116 - - 'GET' / 200
-    [Wed, 27 Oct 2010 13:03:38 GMT] [info] [<0.24207.2>] 192.168.0.116 - - 'GET' /_log?offset=5 200
-
-If you want to pick out specific parts of the log information you can
-use the ``bytes`` argument, which specifies the number of bytes to be
-returned, and ``offset``, which specifies where the reading of the log
-should start, counted back from the end. For example, if you use the
-following request:
-
-.. code-block:: http
-
-    GET /_log?bytes=500&offset=2000
-
-Reading of the log will start at 2000 bytes from the end of the log, and
-500 bytes will be shown.
-
-.. _api/misc/replicate:
-.. _api/misc/replicate.post:
-
-``POST /_replicate``
-====================
-
-.. todo:: POST /_replicate :: what response is?
-
-* **Method**: ``POST /_replicate``
-* **Request**: Replication specification
-* **Response**: TBD
-* **Admin Privileges Required**: yes
-* **Query Arguments**:
-
-  * **Argument**: bytes
-
-    * **Description**:  Bytes to be returned
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 1000
-
-  * **Argument**: offset
-
-    * **Description**:  Offset in bytes where the log tail should be started
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 0
-
-* **Return Codes**:
-
-  * **200**:
-    Replication request successfully completed
-  * **202**:
-    Continuous replication request has been accepted
-  * **404**:
-    Either the source or target DB is not found
-  * **500**:
-    JSON specification was invalid
-
-Request, configure, or stop, a replication operation.
-
-The specification of the replication request is controlled through the
-JSON content of the request. The JSON should be an object with the
-fields defining the source, target and other options. The fields of the
-JSON request are shown in the table below:
-
-* **cancel (optional)**:  Cancels the replication
-* **continuous (optional)**:  Configure the replication to be continuous
-* **create_target (optional)**:  Creates the target database
-* **doc_ids (optional)**:  Array of document IDs to be synchronized
-* **proxy (optional)**:  Address of a proxy server through which replication
-  should occur
-* **source**:  Source database name or URL
-* **target**:  Target database name or URL
-
-Replication Operation
----------------------
-
-The aim of the replication is that at the end of the process, all active
-documents on the source database are also in the destination database
-and all documents that were deleted in the source databases are also
-deleted (if they exist) on the destination database.
-
-Replication can be described as either push or pull replication:
-
--  *Pull replication* is where the ``source`` is the remote CouchDB
-   instance, and the ``destination`` is the local database.
-
-   Pull replication is the most useful solution to use if your source
-   database has a permanent IP address, and your destination (local)
-   database may have a dynamically assigned IP address (for example,
-   through DHCP). This is particularly important if you are replicating
-   to a mobile or other device from a central server.
-
--  *Push replication* is where the ``source`` is a local database, and
-   ``destination`` is a remote database.
-
-Specifying the Source and Target Database
------------------------------------------
-
-You must use the URL specification of the CouchDB database if you want
-to perform replication in either of the following two situations:
-
--  Replication with a remote database (i.e. another instance of CouchDB
-   on the same host, or a different host)
-
--  Replication with a database that requires authentication
-
-For example, to request replication between a database local to the
-CouchDB instance to which you send the request, and a remote database
-you might use the following request:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/_replicate
-    Content-Type: application/json
-    Accept: application/json
-
-    {
-       "source" : "recipes",
-       "target" : "http://coucdb-remote:5984/recipes",
-    }
-
-
-In all cases, the requested databases in the ``source`` and ``target``
-specification must exist. If they do not, an error will be returned
-within the JSON object:
-
-.. code-block:: javascript
-
-    {
-       "error" : "db_not_found"
-       "reason" : "could not open http://couchdb-remote:5984/ol1ka/",
-    }
-
-You can create the target database (providing your user credentials
-allow it) by adding the ``create_target`` field to the request object:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/_replicate
-    Content-Type: application/json
-    Accept: application/json
-
-    {
-       "create_target" : true
-       "source" : "recipes",
-       "target" : "http://couchdb-remote:5984/recipes",
-    }
-
-The ``create_target`` field is not destructive. If the database already
-exists, the replication proceeds as normal.
-
-Single Replication
-------------------
-
-You can request replication of a database so that the two databases can
-be synchronized. By default, the replication process occurs one time and
-synchronizes the two databases together. For example, you can request a
-single synchronization between two databases by supplying the ``source``
-and ``target`` fields within the request JSON content.
-
-.. code-block:: http
-
-    POST http://couchdb:5984/_replicate
-    Content-Type: application/json
-    Accept: application/json
-
-    {
-       "source" : "recipes",
-       "target" : "recipes-snapshot",
-    }
-
-In the above example, the databases ``recipes`` and ``recipes-snapshot``
-will be synchronized. These databases are local to the CouchDB instance
-where the request was made. The response will be a JSON structure
-containing the success (or failure) of the synchronization process, and
-statistics about the process:
-
-.. code-block:: javascript
-
-    {
-       "ok" : true,
-       "history" : [
-          {
-             "docs_read" : 1000,
-             "session_id" : "52c2370f5027043d286daca4de247db0",
-             "recorded_seq" : 1000,
-             "end_last_seq" : 1000,
-             "doc_write_failures" : 0,
-             "start_time" : "Thu, 28 Oct 2010 10:24:13 GMT",
-             "start_last_seq" : 0,
-             "end_time" : "Thu, 28 Oct 2010 10:24:14 GMT",
-             "missing_checked" : 0,
-             "docs_written" : 1000,
-             "missing_found" : 1000
-          }
-       ],
-       "session_id" : "52c2370f5027043d286daca4de247db0",
-       "source_last_seq" : 1000
-    }
-
-The structure defines the replication status, as described in the table
-below:
-
-* **history [array]**:  Replication History
-
-  * **doc_write_failures**:  Number of document write failures
-  * **docs_read**:  Number of documents read
-  * **docs_written**:  Number of documents written to target
-  * **end_last_seq**:  Last sequence number in changes stream
-  * **end_time**:  Date/Time replication operation completed
-  * **missing_checked**:  Number of missing documents checked
-  * **missing_found**:  Number of missing documents found
-  * **recorded_seq**:  Last recorded sequence number
-  * **session_id**:  Session ID for this replication operation
-  * **start_last_seq**:  First sequence number in changes stream
-  * **start_time**:  Date/Time replication operation started
-
-* **ok**:  Replication status
-* **session_id**:  Unique session ID
-* **source_last_seq**:  Last sequence number read from source database
-
-Continuous Replication
-----------------------
-
-Synchronization of a database with the previously noted methods happens
-only once, at the time the replicate request is made. To have the target
-database permanently replicated from the source, you must set the
-``continuous`` field of the JSON object within the request to true.
-
-With continuous replication changes in the source database are
-replicated to the target database in perpetuity until you specifically
-request that replication ceases.
-
-.. code-block:: http
-
-    POST http://couchdb:5984/_replicate
-    Content-Type: application/json
-    Accept: application/json
-
-    {
-       "continuous" : true
-       "source" : "recipes",
-       "target" : "http://couchdb-remote:5984/recipes",
-    }
-
-Changes will be replicated between the two databases as long as a
-network connection is available between the two instances.
-
-.. note::
-   Two keep two databases synchronized with each other, you need to set
-   replication in both directions; that is, you must replicate from
-   ``databasea`` to ``databaseb``, and separately from ``databaseb`` to
-   ``databasea``.
-
-Canceling Continuous Replication
---------------------------------
-
-You can cancel continuous replication by adding the ``cancel`` field to
-the JSON request object and setting the value to true. Note that the
-structure of the request must be identical to the original for the
-cancellation request to be honoured. For example, if you requested
-continuous replication, the cancellation request must also contain the
-``continuous`` field.
-
-For example, the replication request:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/_replicate
-    Content-Type: application/json
-    Accept: application/json
-
-    {
-       "source" : "recipes",
-       "target" : "http://couchdb-remote:5984/recipes",
-       "create_target" : true,
-       "continuous" : true
-    }
-
-Must be canceled using the request:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/_replicate
-    Content-Type: application/json
-    Accept: application/json
-
-    {
-        "cancel" : true,
-        "continuous" : true
-        "create_target" : true,
-        "source" : "recipes",
-        "target" : "http://couchdb-remote:5984/recipes",
-    }
-
-Requesting cancellation of a replication that does not exist results in
-a 404 error.
-
-.. _api/misc/restart:
-.. _api/misc/restart.post:
-
-``POST /_restart``
-==================
-
-* **Method**: ``POST /_restart``
-* **Request**: None
-* **Response**: JSON status message
-* **Admin Privileges Required**: yes
-* **HTTP Headers**:
-
-  * **Header**: ``Content-Type``
-
-    * **Description**: Request content type
-    * **Optional**: no
-    * **Value**: :mimetype:`application/json`
-
-* **Return Codes**:
-
-  * **200**:
-    Replication request successfully completed
-
-Restarts the CouchDB instance. You must be authenticated as a user with
-administration privileges for this to work.
-
-For example:
-
-.. code-block:: http
-
-    POST http://admin:password@couchdb:5984/_restart
-
-The return value (if the server has not already restarted) is a JSON
-status object indicating that the request has been received:
-
-.. code-block:: javascript
-
-    {
-       "ok" : true,
-    }
-
-If the server has already restarted, the header may be returned, but no
-actual data is contained in the response.
-
-.. _api/misc/stats:
-.. _api/misc/stats.get:
-
-``GET /_stats``
-===============
-
-* **Method**: ``GET /_stats``
-* **Request**: None
-* **Response**: Server statistics
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-The ``_stats`` method returns a JSON object containing the statistics
-for the running server. The object is structured with top-level sections
-collating the statistics for a range of entries, with each individual
-statistic being easily identified, and the content of each statistic is
-self-describing. For example, the request time statistics, within the
-``couchdb`` section are structured as follows:
-
-.. code-block:: javascript
-
-    {
-       "couchdb" : {
-    ...
-          "request_time" : {
-             "stddev" : "27.509",
-             "min" : "0.333333333333333",
-             "max" : "152",
-             "current" : "400.976",
-             "mean" : "10.837",
-             "sum" : "400.976",
-             "description" : "length of a request inside CouchDB without MochiWeb"
-          },
-    ...
-        }
-    }
-
-
-The fields provide the current, minimum and maximum, and a collection of
-statistical means and quantities. The quantity in each case is not
-defined, but the descriptions below provide
-
-The statistics are divided into the following top-level sections:
-
--  ``couchdb``: Describes statistics specific to the internals of CouchDB.
-
-   +-------------------------+-------------------------------------------------------+----------------+
-   | Statistic ID            | Description                                           | Unit           |
-   +=========================+=======================================================+================+
-   | ``auth_cache_hits``     | Number of authentication cache hits                   | number         |
-   +-------------------------+-------------------------------------------------------+----------------+
-   | ``auth_cache_misses``   | Number of authentication cache misses                 | number         |
-   +-------------------------+-------------------------------------------------------+----------------+
-   | ``database_reads``      | Number of times a document was read from a database   | number         |
-   +-------------------------+-------------------------------------------------------+----------------+
-   | ``database_writes``     | Number of times a database was changed                | number         |
-   +-------------------------+-------------------------------------------------------+----------------+
-   | ``open_databases``      | Number of open databases                              | number         |
-   +-------------------------+-------------------------------------------------------+----------------+
-   | ``open_os_files``       | Number of file descriptors CouchDB has open           | number         |
-   +-------------------------+-------------------------------------------------------+----------------+
-   | ``request_time``        | Length of a request inside CouchDB without MochiWeb   | milliseconds   |
-   +-------------------------+-------------------------------------------------------+----------------+
-
--  ``httpd_request_methods``
-
-   +----------------+----------------------------------+----------+
-   | Statistic ID   | Description                      | Unit     |
-   +================+==================================+==========+
-   | ``COPY``       | Number of HTTP COPY requests     | number   |
-   +----------------+----------------------------------+----------+
-   | ``DELETE``     | Number of HTTP DELETE requests   | number   |
-   +----------------+----------------------------------+----------+
-   | ``GET``        | Number of HTTP GET requests      | number   |
-   +----------------+----------------------------------+----------+
-   | ``HEAD``       | Number of HTTP HEAD requests     | number   |
-   +----------------+----------------------------------+----------+
-   | ``POST``       | Number of HTTP POST requests     | number   |
-   +----------------+----------------------------------+----------+
-   | ``PUT``        | Number of HTTP PUT requests      | number   |
-   +----------------+----------------------------------+----------+
-
--  ``httpd_status_codes``
-
-   +----------------+------------------------------------------------------+----------+
-   | Statistic ID   | Description                                          | Unit     |
-   +================+======================================================+==========+
-   | ``200``        | Number of HTTP 200 OK responses                      | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``201``        | Number of HTTP 201 Created responses                 | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``202``        | Number of HTTP 202 Accepted responses                | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``301``        | Number of HTTP 301 Moved Permanently responses       | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``304``        | Number of HTTP 304 Not Modified responses            | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``400``        | Number of HTTP 400 Bad Request responses             | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``401``        | Number of HTTP 401 Unauthorized responses            | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``403``        | Number of HTTP 403 Forbidden responses               | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``404``        | Number of HTTP 404 Not Found responses               | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``405``        | Number of HTTP 405 Method Not Allowed responses      | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``409``        | Number of HTTP 409 Conflict responses                | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``412``        | Number of HTTP 412 Precondition Failed responses     | number   |
-   +----------------+------------------------------------------------------+----------+
-   | ``500``        | Number of HTTP 500 Internal Server Error responses   | number   |
-   +----------------+------------------------------------------------------+----------+
-
--  ``httpd``
-
-   +----------------------------------+----------------------------------------------+----------+
-   | Statistic ID                     | Description                                  | Unit     |
-   +==================================+==============================================+==========+
-   | ``bulk_requests``                | Number of bulk requests                      | number   |
-   +----------------------------------+----------------------------------------------+----------+
-   | ``clients_requesting_changes``   | Number of clients for continuous _changes    | number   |
-   +----------------------------------+----------------------------------------------+----------+
-   | ``requests``                     | Number of HTTP requests                      | number   |
-   +----------------------------------+----------------------------------------------+----------+
-   | ``temporary_view_reads``         | Number of temporary view reads               | number   |
-   +----------------------------------+----------------------------------------------+----------+
-   | ``view_reads``                   | Number of view reads                         | number   |
-   +----------------------------------+----------------------------------------------+----------+
-
-You can also access individual statistics by quoting the statistics
-sections and statistic ID as part of the URL path. For example, to get
-the ``request_time`` statistics, you can use:
-
-.. code-block:: http
-
-    GET /_stats/couchdb/request_time
-
-This returns an entire statistics object, as with the full request, but
-containing only the request individual statistic. Hence, the returned
-structure is as follows:
-
-.. code-block:: javascript
-
-    {
-       "couchdb" : {
-          "request_time" : {
-             "stddev" : 7454.305,
-             "min" : 1,
-             "max" : 34185,
-             "current" : 34697.803,
-             "mean" : 1652.276,
-             "sum" : 34697.803,
-             "description" : "length of a request inside CouchDB without MochiWeb"
-          }
-       }
-    }
-
-.. _api/misc/utils:
-.. _api/misc/utils.get:
-
-``GET /_utils``
-===============
-
-* **Method**: ``GET /_utils``
-* **Request**: None
-* **Response**: Administration interface
-* **Admin Privileges Required**: no
-
-Accesses the built-in Futon administration interface for CouchDB.
-
-.. _api/misc/uuids:
-.. _api/misc/uuids.get:
-
-``GET /_uuids``
-===============
-
-* **Method**: ``GET /_uuids``
-* **Request**: None
-* **Response**: List of UUIDs
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: count
-
-    * **Description**:  Number of UUIDs to return
-    * **Optional**: yes
-    * **Type**: numeric
-
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-Requests one or more Universally Unique Identifiers (UUIDs) from the
-CouchDB instance. The response is a JSON object providing a list of
-UUIDs. For example:
-
-.. code-block:: javascript
-
-    {
-       "uuids" : [
-          "7e4b5a14b22ec1cf8e58b9cdd0000da3"
-       ]
-    }
-
-You can use the ``count`` argument to specify the number of UUIDs to be
-returned. For example:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/_uuids?count=5
-
-Returns:
-
-.. code-block:: javascript
-
-    {
-       "uuids" : [
-          "c9df0cdf4442f993fc5570225b405a80",
-          "c9df0cdf4442f993fc5570225b405bd2",
-          "c9df0cdf4442f993fc5570225b405e42",
-          "c9df0cdf4442f993fc5570225b4061a0",
-          "c9df0cdf4442f993fc5570225b406a20"
-       ]
-    }
-
-The UUID type is determined by the :ref:`UUID algorithm <config/uuids/algorithm>`
-setting in the CouchDB configuration.
-
-The UUID type could be changed in anytime through
-:ref:`Config API <api/config/section/key.put>`. For example, changing the UUID
-type to ``random`` use next HTTP request:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/_config/uuids/algorithm
-    Content-Type: application/json
-    Accept: */*
-
-    "random"
-
-When obtaining a list of UUIDs you'll see the changes:
-
-.. code-block:: javascript
-
-    {
-       "uuids" : [
-          "031aad7b469956cf2826fcb2a9260492",
-          "6ec875e15e6b385120938df18ee8e496",
-          "cff9e881516483911aa2f0e98949092d",
-          "b89d37509d39dd712546f9510d4a9271",
-          "2e0dbf7f6c4ad716f21938a016e4e59f"
-       ]
-    }
-
-
-.. _api/misc/favicon:
-.. _api/misc/favicon.get:
-
-``GET /favicon.ico``
-====================
-
-* **Method**: ``GET /favicon.ico``
-* **Request**: None
-* **Response**: Binary content for the `favicon.ico` site icon
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-  * **404**:
-    The requested content could not be found. The returned content will include
-    further information, as a JSON object, if available.
-
-Returns the site icon. The return ``Content-Type`` header is
-:mimetype:`image/x-icon`, and the content stream is the image data.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/server/authn.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/server/authn.rst b/share/doc/src/api/server/authn.rst
new file mode 100644
index 0000000..083a262
--- /dev/null
+++ b/share/doc/src/api/server/authn.rst
@@ -0,0 +1,460 @@
+.. 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.
+
+.. _api/auth:
+
+======================
+Authentication Methods
+======================
+
+The CouchDB Authentication methods provide an interface for obtaining
+session and authorization data.
+
+A list of the available methods and URL paths are provided below:
+
++--------+-------------------------+-------------------------------------------+
+| Method | Path                    | Description                               |
++========+=========================+===========================================+
+| GET    | /_session               | Returns cookie based login user           |
+|        |                         | information                               |
++--------+-------------------------+-------------------------------------------+
+| POST   | /_session               | Do cookie based user login                |
++--------+-------------------------+-------------------------------------------+
+| DELETE | /_session               | Logout cookie based user                  |
++--------+-------------------------+-------------------------------------------+
+
+.. note:: We're also strongly recommend you to
+   :ref:`setup SSL <config/ssl>` to improve all authentication methods security.
+
+
+.. _api/auth/basic:
+
+Basic Authentication
+====================
+
+`Basic authentication`_ (:rfc:`2617`) is a quick and simple way to be
+authenticated by CouchDB. The main flaw of this simplicity is the need to send
+user credentials with each request which may be insecure and hurts operations
+performance (since CouchDB must compute password hash with every request):
+
+.. code-block:: http
+
+    GET / HTTP/1.1
+    Authorization: Basic cm9vdDpyZWxheA==
+    Host: localhost:5984
+    Accept: application/json
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
+    Date: Mon, 03 Dec 2012 00:44:47 GMT
+    Content-Type: application/json
+    Content-Length: 177
+    Cache-Control: must-revalidate
+
+.. code-block:: javascript
+
+    {
+      "couchdb":"Welcome",
+      "uuid":"0a959b9b8227188afc2ac26ccdf345a6",
+      "version":"1.3.0",
+      "vendor": {
+        "version":"1.3.0",
+        "name":"The Apache Software Foundation"
+      }
+    }
+
+.. _Basic authentication: http://en.wikipedia.org/wiki/Basic_access_authentication
+
+
+.. _api/auth/cookie:
+
+Cookie Authentication
+=====================
+
+For cookie authentication (:rfc:`2109`) CouchDB generates a one-time token that
+the client can use for next requests to CouchDB. When CouchDB sees non expired
+the token in a subsequent request, it will authenticate user by this token
+without requesting the password again. By default, cookies are valid for
+10 minutes, but it's :ref:`adjustable <config/couch_httpd_auth/timeout>`.
+Also it's possible to make cookies
+:ref:`persistent <config/couch_httpd_auth/allow_persistent_cookies>`
+
+To obtain the first token and thus authenticate a user for the first time, the
+`username` and `password` must be sent to the
+:ref:`_session API <api/auth/session>`.
+
+.. _api/auth/session:
+.. _api/auth/session.post:
+
+``POST /_session``
+------------------
+
+* **Method**: ``POST /_session``
+* **Request**: User credentials
+* **Response**: User information
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: next
+
+    * **Description**: Enforces redirect after successful login
+    * **Optional**: yes
+    * **Value**: Relative path from server root
+
+* **HTTP Headers**
+
+  * **Header**: ``Content-Type``
+
+    * **Description**: Credentials data format
+    * **Optional**: no
+    * **Value**: ``application/x-www-form-urlencoded``
+
+* **Return Codes**:
+
+  * **200**:
+    Successfully authenticated
+
+  * **302**:
+    Redirect after successful authentication
+
+  * **401**:
+    Username or password wasn't recognized
+
+Initiates new session for specified user credentials by providing `Cookie`
+value. Credentials should be defined in ``application/x-www-form-urlencoded``
+format with `name` and `password` fields.
+
+.. code-block:: http
+
+    POST /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Content-Length: 24
+    Content-Type: application/x-www-form-urlencoded
+
+.. code-block:: text
+
+    name=root&password=relax
+
+In case of success will be returned next response:
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Set-Cookie: AuthSession=cm9vdDo1MEJCRkYwMjq0LO0ylOIwShrgt8y-UkhI-c6BGw; Version=1; Path=/; HttpOnly
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
+    Date: Mon, 03 Dec 2012 01:23:14 GMT
+    Content-Type: application/json
+    Content-Length: 43
+    Cache-Control: must-revalidate
+
+.. code-block:: javascript
+
+    {"ok":true,"name":null,"roles":["_admin"]}
+
+If ``next`` query parameter was provided the response will trigger redirection
+to the specified location in case of successful authentication:
+
+.. code-block:: http
+
+    GET /_session?next=/blog/_design/sofa/_rewrite/recent-posts HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+
+.. code-block:: http
+
+    HTTP/1.1 302 Moved Temporarily
+    Set-Cookie: AuthSession=cm9vdDo1MEJDMDEzRTp7Vu5GKCkTxTVxwXbpXsBARQWnhQ; Version=1; Path=/; HttpOnly
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
+    Location: http://localhost:5984/blog/_design/sofa/_rewrite/recent-posts
+    Date: Mon, 03 Dec 2012 01:32:46 GMT
+    Content-Type: application/json
+    Content-Length: 43
+    Cache-Control: must-revalidate
+
+.. code-block:: javascript
+
+    {"ok":true,"name":null,"roles":["_admin"]}
+
+
+.. _api/auth/session.get:
+
+``GET /_session``
+-----------------
+
+* **Method**: ``GET /_session``
+* **Request**: None
+* **Response**: User information
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: basic
+
+    * **Description**: Accept `Basic Auth` by requesting this resource
+    * **Optional**: yes
+    * **Value**: ``true``
+
+* **Return Codes**:
+
+  * **200**:
+    Successfully authenticated.
+
+  * **401**:
+    Username or password wasn't recognized.
+
+Returns complete information about authenticated user:
+
+.. code-block:: http
+
+    GET /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Cookie: AuthSession=cm9vdDo1MEJDMDQxRDpqb-Ta9QfP9hpdPjHLxNTKg_Hf9w
+
+.. code-block:: javascript
+
+    {
+        "info": {
+            "authenticated": "cookie",
+            "authentication_db": "_users",
+            "authentication_handlers": [
+                "oauth",
+                "cookie",
+                "default"
+            ]
+        },
+        "ok": true,
+        "userCtx": {
+            "name": "root",
+            "roles": [
+                "_admin"
+            ]
+        }
+    }
+
+This information contains :ref:`userctx_object`, authentication method and
+available ones and authentication database.
+
+.. _api/auth/session.delete:
+
+``DELETE /_session``
+--------------------
+
+* **Method**: ``DELETE /_session``
+* **Request**: None
+* **Response**: Status
+* **Admin Privileges Required**: no
+
+* **Return Codes**:
+
+  * **200**:
+    Successfully close session.
+
+  * **401**:
+    Username or password wasn't recognized.
+
+Closes user's session. If everything is ok, the response is:
+
+.. code-block:: javascript
+
+    {"ok":true}
+
+
+.. _api/auth/proxy:
+
+Proxy Authentication
+====================
+
+.. note::
+   To use this authentication method make sure that the
+   ``{couch_httpd_auth, proxy_authentication_handler}`` value in added to
+   the list of the active
+   :ref:`authentication handlers <config/httpd/authentication_handlers>`:
+
+   .. code-block:: ini
+
+      [httpd]
+      authentication_handlers = {couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, proxy_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
+
+
+`Proxy authentication` is very useful in case when your application is already
+uses some external authentication service and you won't duplicate users and
+their roles in CouchDB.
+
+This authentication method allows creation of a :ref:`userctx_object` for
+remotely authenticated user. By default, the client just need to pass specific
+headers to CouchDB with related request:
+
+- :ref:`X-Auth-CouchDB-UserName <config/couch_httpd_auth/x_auth_username>`:
+  username;
+- :ref:`X-Auth-CouchDB-Roles <config/couch_httpd_auth/x_auth_roles>`:
+  list of user roles separated by a comma (``,``);
+- :ref:`X-Auth-CouchDB-Token <config/couch_httpd_auth/x_auth_token>`:
+  authentication token. Optional, but strongly recommended to
+  :ref:`force token be required <config/couch_httpd_auth/proxy_use_secret>`
+  to prevent requests from untrusted sources.
+
+.. code-block:: http
+
+    GET /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Content-Type: application/json; charset=utf-8
+    X-Auth-CouchDB-Roles: users,blogger
+    X-Auth-CouchDB-UserName: foo
+
+CouchDB sends the response:
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Cache-Control: must-revalidate
+    Content-Length: 190
+    Content-Type: application/json
+    Date: Fri, 14 Jun 2013 10:16:03 GMT
+    Server: CouchDB/1.3.0 (Erlang OTP/R15B03)
+
+.. code-block:: javascript
+
+    {
+        "info": {
+            "authenticated": "proxy",
+            "authentication_db": "_users",
+            "authentication_handlers": [
+                "oauth",
+                "cookie",
+                "proxy",
+                "default"
+            ]
+        },
+        "ok": true,
+        "userCtx": {
+            "name": "foo",
+            "roles": [
+                "users",
+                "blogger"
+            ]
+        }
+    }
+
+
+Note, that you don't need to request :ref:`session <api/auth/session>` resource
+to be authenticated by this method if all required HTTP headers are provided.
+
+
+.. _api/auth/oauth:
+
+OAuth Authentication
+====================
+
+CouchDB supports OAuth 1.0 authentication (:rfc:`5849`). OAuth provides a method
+for clients to access server resources  without sharing real credentials
+(username and password).
+
+First, :ref:`configure oauth <config/oauth>`, by setting consumer and token
+with their secrets and binding token to real CouchDB username.
+
+Probably, it's not good idea to work with plain curl, let use some scripting
+language like Python:
+
+.. code-block:: python
+
+  #!/usr/bin/env python2
+  from oauth import oauth # pip install oauth
+  import httplib
+
+  URL = 'http://localhost:5984/_session'
+  CONSUMER_KEY = 'consumer1'
+  CONSUMER_SECRET = 'sekr1t'
+  TOKEN = 'token1'
+  SECRET = 'tokensekr1t'
+
+  consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
+  token = oauth.OAuthToken(TOKEN, SECRET)
+  req = oauth.OAuthRequest.from_consumer_and_token(
+      consumer,
+      token=token,
+      http_method='GET',
+      http_url=URL,
+      parameters={}
+  )
+  req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,token)
+
+  headers = req.to_header()
+  headers['Accept'] = 'application/json'
+
+  con = httplib.HTTPConnection('localhost', 5984)
+  con.request('GET', URL, headers=headers)
+  resp = con.getresponse()
+  print resp.read()
+
+or Ruby:
+
+.. code-block:: ruby
+
+  #!/usr/bin/env ruby
+
+  require 'oauth' # gem install oauth
+
+  URL = 'http://localhost:5984'
+  CONSUMER_KEY = 'consumer1'
+  CONSUMER_SECRET = 'sekr1t'
+  TOKEN = 'token1'
+  SECRET = 'tokensekr1t'
+
+  @consumer = OAuth::Consumer.new CONSUMER_KEY,
+                                  CONSUMER_SECRET,
+                                  {:site => URL}
+
+  @access_token = OAuth::AccessToken.new(@consumer, TOKEN, SECRET)
+
+  puts @access_token.get('/_session').body
+
+
+Both snippets produces similar request and response pair:
+
+.. code-block:: http
+
+    GET /_session HTTP/1.1
+    Host: localhost:5984
+    Accept: application/json
+    Authorization: OAuth realm="", oauth_nonce="81430018", oauth_timestamp="1374561749", oauth_consumer_key="consumer1", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="token1", oauth_signature="o4FqJ8%2B9IzUpXH%2Bk4rgnv7L6eTY%3D"
+
+.. code-block:: http
+
+    HTTP/1.1 200 OK
+    Cache-Control : must-revalidate
+    Content-Length : 167
+    Content-Type : application/json
+    Date : Tue, 23 Jul 2013 06:51:15 GMT
+    Server : CouchDB/1.3.1 (Erlang OTP/R16B)
+
+.. code-block:: javascript
+
+  {
+    "ok": true,
+    "info": {
+      "authenticated": "oauth"
+      "authentication_db": "_users",
+      "authentication_handlers": ["oauth", "cookie", "default"]
+    },
+    "userCtx": {
+      "name": "couchdb_username",
+      "roles": []
+    }
+  }
+
+There we'd requested the :ref:`_session <api/auth/session>` resource to ensure
+that authentication was successful and target CouchDB username is correct.
+Change the target URL to request required resource.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/server/common.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/server/common.rst b/share/doc/src/api/server/common.rst
new file mode 100644
index 0000000..d57de61
--- /dev/null
+++ b/share/doc/src/api/server/common.rst
@@ -0,0 +1,862 @@
+.. 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.
+
+
+.. _api/server/root:
+.. _api/server/root.get:
+
+``GET /``
+=========
+
+* **Method**: ``GET /``
+* **Request**: None
+* **Response**: Welcome message and version
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+Accessing the root of a CouchDB instance returns meta information about
+the instance. The response is a JSON structure containing information
+about the server, including a welcome message and the version of the
+server.
+
+.. code-block:: javascript
+
+    {
+       "couchdb" : "Welcome",
+       "version" : "1.0.1"
+    }
+
+.. _api/server/active_tasks:
+.. _api/server/active_tasks.get:
+
+``GET /_active_tasks``
+======================
+
+* **Method**: ``GET /_active_tasks``
+* **Request**: None
+* **Response**: List of running tasks, including the task type, name, status
+  and process ID
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+You can obtain a list of active tasks by using the ``/_active_tasks``
+URL. The result is a JSON array of the currently running tasks, with
+each task being described with a single object. For example:
+
+.. code-block:: javascript
+
+    [
+       {
+        "pid" : "<0.11599.0>",
+        "status" : "Copied 0 of 18369 changes (0%)",
+        "task" : "recipes",
+        "type" : "Database Compaction"
+        }
+    ]
+
+The returned structure includes the following fields for each task:
+
+* **tasks** [array]: Active Task
+
+  * **pid**:Process ID
+  * **status**: Task status message
+  * **task**: Task name
+  * **type**: Operation Type
+
+For operation type, valid values include:
+
+-  ``Database Compaction``
+
+-  ``Replication``
+
+-  ``View Group Compaction``
+
+-  ``View Group Indexer``
+
+.. _api/server/all_dbs:
+.. _api/server/all_dbs.get:
+
+``GET /_all_dbs``
+=================
+
+* **Method**: ``GET /_all_dbs``
+* **Request**: None
+* **Response**: JSON list of DBs
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+Returns a list of all the databases in the CouchDB instance. For
+example:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/_all_dbs
+    Accept: application/json
+
+The return is a JSON array:
+
+.. code-block:: javascript
+
+    [
+       "_users",
+       "contacts",
+       "docs",
+       "invoices",
+       "locations"
+    ]
+
+
+.. _api/server/db_updates:
+.. _api/server/db_updates.get:
+
+``GET /_db_updates``
+====================
+
+* **Method**: ``GET /_db_updates``
+* **Request**: None
+* **Admin Privileges Required**: yes
+* **Query Arguments**:
+
+  * **Argument**: feed
+
+    * **Description**: Format of the response feed
+    * **Optional**: yes
+    * **Type**: string
+    * **Default**: longpoll
+    * **Supported Values**:
+
+      * **longpoll**: Closes the connection after the first event.
+      * **continuous**: Send a line of JSON per event. Keeps the socket open
+        until ``timeout``.
+      * **eventsource**: Like, ``continuous``, but sends the events in
+        `EventSource <http://dev.w3.org/html5/eventsource/>`_ format.
+
+  * **Argument**: timeout
+
+    * **Description**: Number of seconds until CouchDB closes the connection.
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 60
+
+  * **Argument**: heartbeat
+
+    * **Description**: Whether CouchDB will send a newline character (``\n``)
+      on ``timeout``.
+    * **Optional**: yes
+    * **Type**: boolean
+    * **Default**: true
+
+* **Return Codes**:
+
+  * **200**
+    Request completed successfully.
+
+Returns a list of all database events in the CouchDB instance.
+
+A database event is one of `created`, `updated`, `deleted`.
+
+For example:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/_db_events?feed=continuous
+    Accept: application/json
+
+.. code-block:: javascript
+
+    {"dbname":"my-database", "type":"created"}
+    {"dbname":"my-database", "type":"updated"}
+    {"dbname":"another-database", "type":"created"}
+    {"dbname":"my-database", "type":"deleted"}
+    {"dbname":"another-database", "type":"updated"}
+
+
+.. _api/server/log:
+.. _api/server/log.get:
+
+``GET /_log``
+=============
+
+* **Method**: ``GET /_log``
+* **Request**: None
+* **Response**: Log content
+* **Admin Privileges Required**: yes
+* **Query Arguments**:
+
+  * **Argument**: bytes
+
+    * **Description**:  Bytes to be returned
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 1000
+
+  * **Argument**: offset
+
+    * **Description**:  Offset in bytes where the log tail should be started
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 0
+
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+Gets the CouchDB log, equivalent to accessing the local log file of the
+corresponding CouchDB instance.
+
+When you request the log, the response is returned as plain (UTF-8)
+text, with an HTTP ``Content-type`` header as ``text/plain``.
+
+For example, the request:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/_log
+    Accept: */*
+
+The raw text is returned:
+
+.. code-block:: text
+
+    [Wed, 27 Oct 2010 10:49:42 GMT] [info] [<0.23338.2>] 192.168.0.2 - - 'PUT' /authdb 401
+    [Wed, 27 Oct 2010 11:02:19 GMT] [info] [<0.23428.2>] 192.168.0.116 - - 'GET' /recipes/FishStew 200
+    [Wed, 27 Oct 2010 11:02:19 GMT] [info] [<0.23428.2>] 192.168.0.116 - - 'GET' /_session 200
+    [Wed, 27 Oct 2010 11:02:19 GMT] [info] [<0.24199.2>] 192.168.0.116 - - 'GET' / 200
+    [Wed, 27 Oct 2010 13:03:38 GMT] [info] [<0.24207.2>] 192.168.0.116 - - 'GET' /_log?offset=5 200
+
+If you want to pick out specific parts of the log information you can
+use the ``bytes`` argument, which specifies the number of bytes to be
+returned, and ``offset``, which specifies where the reading of the log
+should start, counted back from the end. For example, if you use the
+following request:
+
+.. code-block:: http
+
+    GET /_log?bytes=500&offset=2000
+
+Reading of the log will start at 2000 bytes from the end of the log, and
+500 bytes will be shown.
+
+.. _api/server/replicate:
+.. _api/server/replicate.post:
+
+``POST /_replicate``
+====================
+
+.. todo:: POST /_replicate :: what response is?
+
+* **Method**: ``POST /_replicate``
+* **Request**: Replication specification
+* **Response**: TBD
+* **Admin Privileges Required**: yes
+* **Query Arguments**:
+
+  * **Argument**: bytes
+
+    * **Description**:  Bytes to be returned
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 1000
+
+  * **Argument**: offset
+
+    * **Description**:  Offset in bytes where the log tail should be started
+    * **Optional**: yes
+    * **Type**: numeric
+    * **Default**: 0
+
+* **Return Codes**:
+
+  * **200**:
+    Replication request successfully completed
+  * **202**:
+    Continuous replication request has been accepted
+  * **404**:
+    Either the source or target DB is not found
+  * **500**:
+    JSON specification was invalid
+
+Request, configure, or stop, a replication operation.
+
+The specification of the replication request is controlled through the
+JSON content of the request. The JSON should be an object with the
+fields defining the source, target and other options. The fields of the
+JSON request are shown in the table below:
+
+* **cancel (optional)**:  Cancels the replication
+* **continuous (optional)**:  Configure the replication to be continuous
+* **create_target (optional)**:  Creates the target database
+* **doc_ids (optional)**:  Array of document IDs to be synchronized
+* **proxy (optional)**:  Address of a proxy server through which replication
+  should occur
+* **source**:  Source database name or URL
+* **target**:  Target database name or URL
+
+Replication Operation
+---------------------
+
+The aim of the replication is that at the end of the process, all active
+documents on the source database are also in the destination database
+and all documents that were deleted in the source databases are also
+deleted (if they exist) on the destination database.
+
+Replication can be described as either push or pull replication:
+
+-  *Pull replication* is where the ``source`` is the remote CouchDB
+   instance, and the ``destination`` is the local database.
+
+   Pull replication is the most useful solution to use if your source
+   database has a permanent IP address, and your destination (local)
+   database may have a dynamically assigned IP address (for example,
+   through DHCP). This is particularly important if you are replicating
+   to a mobile or other device from a central server.
+
+-  *Push replication* is where the ``source`` is a local database, and
+   ``destination`` is a remote database.
+
+Specifying the Source and Target Database
+-----------------------------------------
+
+You must use the URL specification of the CouchDB database if you want
+to perform replication in either of the following two situations:
+
+-  Replication with a remote database (i.e. another instance of CouchDB
+   on the same host, or a different host)
+
+-  Replication with a database that requires authentication
+
+For example, to request replication between a database local to the
+CouchDB instance to which you send the request, and a remote database
+you might use the following request:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/_replicate
+    Content-Type: application/json
+    Accept: application/json
+
+    {
+       "source" : "recipes",
+       "target" : "http://coucdb-remote:5984/recipes",
+    }
+
+
+In all cases, the requested databases in the ``source`` and ``target``
+specification must exist. If they do not, an error will be returned
+within the JSON object:
+
+.. code-block:: javascript
+
+    {
+       "error" : "db_not_found"
+       "reason" : "could not open http://couchdb-remote:5984/ol1ka/",
+    }
+
+You can create the target database (providing your user credentials
+allow it) by adding the ``create_target`` field to the request object:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/_replicate
+    Content-Type: application/json
+    Accept: application/json
+
+    {
+       "create_target" : true
+       "source" : "recipes",
+       "target" : "http://couchdb-remote:5984/recipes",
+    }
+
+The ``create_target`` field is not destructive. If the database already
+exists, the replication proceeds as normal.
+
+Single Replication
+------------------
+
+You can request replication of a database so that the two databases can
+be synchronized. By default, the replication process occurs one time and
+synchronizes the two databases together. For example, you can request a
+single synchronization between two databases by supplying the ``source``
+and ``target`` fields within the request JSON content.
+
+.. code-block:: http
+
+    POST http://couchdb:5984/_replicate
+    Content-Type: application/json
+    Accept: application/json
+
+    {
+       "source" : "recipes",
+       "target" : "recipes-snapshot",
+    }
+
+In the above example, the databases ``recipes`` and ``recipes-snapshot``
+will be synchronized. These databases are local to the CouchDB instance
+where the request was made. The response will be a JSON structure
+containing the success (or failure) of the synchronization process, and
+statistics about the process:
+
+.. code-block:: javascript
+
+    {
+       "ok" : true,
+       "history" : [
+          {
+             "docs_read" : 1000,
+             "session_id" : "52c2370f5027043d286daca4de247db0",
+             "recorded_seq" : 1000,
+             "end_last_seq" : 1000,
+             "doc_write_failures" : 0,
+             "start_time" : "Thu, 28 Oct 2010 10:24:13 GMT",
+             "start_last_seq" : 0,
+             "end_time" : "Thu, 28 Oct 2010 10:24:14 GMT",
+             "missing_checked" : 0,
+             "docs_written" : 1000,
+             "missing_found" : 1000
+          }
+       ],
+       "session_id" : "52c2370f5027043d286daca4de247db0",
+       "source_last_seq" : 1000
+    }
+
+The structure defines the replication status, as described in the table
+below:
+
+* **history [array]**:  Replication History
+
+  * **doc_write_failures**:  Number of document write failures
+  * **docs_read**:  Number of documents read
+  * **docs_written**:  Number of documents written to target
+  * **end_last_seq**:  Last sequence number in changes stream
+  * **end_time**:  Date/Time replication operation completed
+  * **missing_checked**:  Number of missing documents checked
+  * **missing_found**:  Number of missing documents found
+  * **recorded_seq**:  Last recorded sequence number
+  * **session_id**:  Session ID for this replication operation
+  * **start_last_seq**:  First sequence number in changes stream
+  * **start_time**:  Date/Time replication operation started
+
+* **ok**:  Replication status
+* **session_id**:  Unique session ID
+* **source_last_seq**:  Last sequence number read from source database
+
+Continuous Replication
+----------------------
+
+Synchronization of a database with the previously noted methods happens
+only once, at the time the replicate request is made. To have the target
+database permanently replicated from the source, you must set the
+``continuous`` field of the JSON object within the request to true.
+
+With continuous replication changes in the source database are
+replicated to the target database in perpetuity until you specifically
+request that replication ceases.
+
+.. code-block:: http
+
+    POST http://couchdb:5984/_replicate
+    Content-Type: application/json
+    Accept: application/json
+
+    {
+       "continuous" : true
+       "source" : "recipes",
+       "target" : "http://couchdb-remote:5984/recipes",
+    }
+
+Changes will be replicated between the two databases as long as a
+network connection is available between the two instances.
+
+.. note::
+   Two keep two databases synchronized with each other, you need to set
+   replication in both directions; that is, you must replicate from
+   ``databasea`` to ``databaseb``, and separately from ``databaseb`` to
+   ``databasea``.
+
+Canceling Continuous Replication
+--------------------------------
+
+You can cancel continuous replication by adding the ``cancel`` field to
+the JSON request object and setting the value to true. Note that the
+structure of the request must be identical to the original for the
+cancellation request to be honoured. For example, if you requested
+continuous replication, the cancellation request must also contain the
+``continuous`` field.
+
+For example, the replication request:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/_replicate
+    Content-Type: application/json
+    Accept: application/json
+
+    {
+       "source" : "recipes",
+       "target" : "http://couchdb-remote:5984/recipes",
+       "create_target" : true,
+       "continuous" : true
+    }
+
+Must be canceled using the request:
+
+.. code-block:: http
+
+    POST http://couchdb:5984/_replicate
+    Content-Type: application/json
+    Accept: application/json
+
+    {
+        "cancel" : true,
+        "continuous" : true
+        "create_target" : true,
+        "source" : "recipes",
+        "target" : "http://couchdb-remote:5984/recipes",
+    }
+
+Requesting cancellation of a replication that does not exist results in
+a 404 error.
+
+.. _api/server/restart:
+.. _api/server/restart.post:
+
+``POST /_restart``
+==================
+
+* **Method**: ``POST /_restart``
+* **Request**: None
+* **Response**: JSON status message
+* **Admin Privileges Required**: yes
+* **HTTP Headers**:
+
+  * **Header**: ``Content-Type``
+
+    * **Description**: Request content type
+    * **Optional**: no
+    * **Value**: :mimetype:`application/json`
+
+* **Return Codes**:
+
+  * **200**:
+    Replication request successfully completed
+
+Restarts the CouchDB instance. You must be authenticated as a user with
+administration privileges for this to work.
+
+For example:
+
+.. code-block:: http
+
+    POST http://admin:password@couchdb:5984/_restart
+
+The return value (if the server has not already restarted) is a JSON
+status object indicating that the request has been received:
+
+.. code-block:: javascript
+
+    {
+       "ok" : true,
+    }
+
+If the server has already restarted, the header may be returned, but no
+actual data is contained in the response.
+
+.. _api/server/stats:
+.. _api/server/stats.get:
+
+``GET /_stats``
+===============
+
+* **Method**: ``GET /_stats``
+* **Request**: None
+* **Response**: Server statistics
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+The ``_stats`` method returns a JSON object containing the statistics
+for the running server. The object is structured with top-level sections
+collating the statistics for a range of entries, with each individual
+statistic being easily identified, and the content of each statistic is
+self-describing. For example, the request time statistics, within the
+``couchdb`` section are structured as follows:
+
+.. code-block:: javascript
+
+    {
+       "couchdb" : {
+    ...
+          "request_time" : {
+             "stddev" : "27.509",
+             "min" : "0.333333333333333",
+             "max" : "152",
+             "current" : "400.976",
+             "mean" : "10.837",
+             "sum" : "400.976",
+             "description" : "length of a request inside CouchDB without MochiWeb"
+          },
+    ...
+        }
+    }
+
+
+The fields provide the current, minimum and maximum, and a collection of
+statistical means and quantities. The quantity in each case is not
+defined, but the descriptions below provide
+
+The statistics are divided into the following top-level sections:
+
+-  ``couchdb``: Describes statistics specific to the internals of CouchDB.
+
+   +-------------------------+-------------------------------------------------------+----------------+
+   | Statistic ID            | Description                                           | Unit           |
+   +=========================+=======================================================+================+
+   | ``auth_cache_hits``     | Number of authentication cache hits                   | number         |
+   +-------------------------+-------------------------------------------------------+----------------+
+   | ``auth_cache_misses``   | Number of authentication cache misses                 | number         |
+   +-------------------------+-------------------------------------------------------+----------------+
+   | ``database_reads``      | Number of times a document was read from a database   | number         |
+   +-------------------------+-------------------------------------------------------+----------------+
+   | ``database_writes``     | Number of times a database was changed                | number         |
+   +-------------------------+-------------------------------------------------------+----------------+
+   | ``open_databases``      | Number of open databases                              | number         |
+   +-------------------------+-------------------------------------------------------+----------------+
+   | ``open_os_files``       | Number of file descriptors CouchDB has open           | number         |
+   +-------------------------+-------------------------------------------------------+----------------+
+   | ``request_time``        | Length of a request inside CouchDB without MochiWeb   | milliseconds   |
+   +-------------------------+-------------------------------------------------------+----------------+
+
+-  ``httpd_request_methods``
+
+   +----------------+----------------------------------+----------+
+   | Statistic ID   | Description                      | Unit     |
+   +================+==================================+==========+
+   | ``COPY``       | Number of HTTP COPY requests     | number   |
+   +----------------+----------------------------------+----------+
+   | ``DELETE``     | Number of HTTP DELETE requests   | number   |
+   +----------------+----------------------------------+----------+
+   | ``GET``        | Number of HTTP GET requests      | number   |
+   +----------------+----------------------------------+----------+
+   | ``HEAD``       | Number of HTTP HEAD requests     | number   |
+   +----------------+----------------------------------+----------+
+   | ``POST``       | Number of HTTP POST requests     | number   |
+   +----------------+----------------------------------+----------+
+   | ``PUT``        | Number of HTTP PUT requests      | number   |
+   +----------------+----------------------------------+----------+
+
+-  ``httpd_status_codes``
+
+   +----------------+------------------------------------------------------+----------+
+   | Statistic ID   | Description                                          | Unit     |
+   +================+======================================================+==========+
+   | ``200``        | Number of HTTP 200 OK responses                      | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``201``        | Number of HTTP 201 Created responses                 | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``202``        | Number of HTTP 202 Accepted responses                | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``301``        | Number of HTTP 301 Moved Permanently responses       | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``304``        | Number of HTTP 304 Not Modified responses            | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``400``        | Number of HTTP 400 Bad Request responses             | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``401``        | Number of HTTP 401 Unauthorized responses            | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``403``        | Number of HTTP 403 Forbidden responses               | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``404``        | Number of HTTP 404 Not Found responses               | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``405``        | Number of HTTP 405 Method Not Allowed responses      | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``409``        | Number of HTTP 409 Conflict responses                | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``412``        | Number of HTTP 412 Precondition Failed responses     | number   |
+   +----------------+------------------------------------------------------+----------+
+   | ``500``        | Number of HTTP 500 Internal Server Error responses   | number   |
+   +----------------+------------------------------------------------------+----------+
+
+-  ``httpd``
+
+   +----------------------------------+----------------------------------------------+----------+
+   | Statistic ID                     | Description                                  | Unit     |
+   +==================================+==============================================+==========+
+   | ``bulk_requests``                | Number of bulk requests                      | number   |
+   +----------------------------------+----------------------------------------------+----------+
+   | ``clients_requesting_changes``   | Number of clients for continuous _changes    | number   |
+   +----------------------------------+----------------------------------------------+----------+
+   | ``requests``                     | Number of HTTP requests                      | number   |
+   +----------------------------------+----------------------------------------------+----------+
+   | ``temporary_view_reads``         | Number of temporary view reads               | number   |
+   +----------------------------------+----------------------------------------------+----------+
+   | ``view_reads``                   | Number of view reads                         | number   |
+   +----------------------------------+----------------------------------------------+----------+
+
+You can also access individual statistics by quoting the statistics
+sections and statistic ID as part of the URL path. For example, to get
+the ``request_time`` statistics, you can use:
+
+.. code-block:: http
+
+    GET /_stats/couchdb/request_time
+
+This returns an entire statistics object, as with the full request, but
+containing only the request individual statistic. Hence, the returned
+structure is as follows:
+
+.. code-block:: javascript
+
+    {
+       "couchdb" : {
+          "request_time" : {
+             "stddev" : 7454.305,
+             "min" : 1,
+             "max" : 34185,
+             "current" : 34697.803,
+             "mean" : 1652.276,
+             "sum" : 34697.803,
+             "description" : "length of a request inside CouchDB without MochiWeb"
+          }
+       }
+    }
+
+.. _api/server/utils:
+.. _api/server/utils.get:
+
+``GET /_utils``
+===============
+
+* **Method**: ``GET /_utils``
+* **Request**: None
+* **Response**: Administration interface
+* **Admin Privileges Required**: no
+
+Accesses the built-in Futon administration interface for CouchDB.
+
+.. _api/server/uuids:
+.. _api/server/uuids.get:
+
+``GET /_uuids``
+===============
+
+* **Method**: ``GET /_uuids``
+* **Request**: None
+* **Response**: List of UUIDs
+* **Admin Privileges Required**: no
+* **Query Arguments**:
+
+  * **Argument**: count
+
+    * **Description**:  Number of UUIDs to return
+    * **Optional**: yes
+    * **Type**: numeric
+
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+Requests one or more Universally Unique Identifiers (UUIDs) from the
+CouchDB instance. The response is a JSON object providing a list of
+UUIDs. For example:
+
+.. code-block:: javascript
+
+    {
+       "uuids" : [
+          "7e4b5a14b22ec1cf8e58b9cdd0000da3"
+       ]
+    }
+
+You can use the ``count`` argument to specify the number of UUIDs to be
+returned. For example:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/_uuids?count=5
+
+Returns:
+
+.. code-block:: javascript
+
+    {
+       "uuids" : [
+          "c9df0cdf4442f993fc5570225b405a80",
+          "c9df0cdf4442f993fc5570225b405bd2",
+          "c9df0cdf4442f993fc5570225b405e42",
+          "c9df0cdf4442f993fc5570225b4061a0",
+          "c9df0cdf4442f993fc5570225b406a20"
+       ]
+    }
+
+The UUID type is determined by the :ref:`UUID algorithm <config/uuids/algorithm>`
+setting in the CouchDB configuration.
+
+The UUID type could be changed in anytime through
+:ref:`Config API <api/config/section/key.put>`. For example, changing the UUID
+type to ``random`` use next HTTP request:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/_config/uuids/algorithm
+    Content-Type: application/json
+    Accept: */*
+
+    "random"
+
+When obtaining a list of UUIDs you'll see the changes:
+
+.. code-block:: javascript
+
+    {
+       "uuids" : [
+          "031aad7b469956cf2826fcb2a9260492",
+          "6ec875e15e6b385120938df18ee8e496",
+          "cff9e881516483911aa2f0e98949092d",
+          "b89d37509d39dd712546f9510d4a9271",
+          "2e0dbf7f6c4ad716f21938a016e4e59f"
+       ]
+    }
+
+
+.. _api/server/favicon:
+.. _api/server/favicon.get:
+
+``GET /favicon.ico``
+====================
+
+* **Method**: ``GET /favicon.ico``
+* **Request**: None
+* **Response**: Binary content for the `favicon.ico` site icon
+* **Admin Privileges Required**: no
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+  * **404**:
+    The requested content could not be found. The returned content will include
+    further information, as a JSON object, if available.
+
+Returns the site icon. The return ``Content-Type`` header is
+:mimetype:`image/x-icon`, and the content stream is the image data.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/server/configuration.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/server/configuration.rst b/share/doc/src/api/server/configuration.rst
new file mode 100644
index 0000000..9fdec09
--- /dev/null
+++ b/share/doc/src/api/server/configuration.rst
@@ -0,0 +1,307 @@
+.. 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.
+
+.. _api/config:
+
+=====================
+Configuration Methods
+=====================
+
+The CouchDB API Server Configuration Methods provide an interface to
+query and update the various configuration values within a running
+CouchDB instance.
+
+A list of the available methods and URL paths are provided below:
+
++--------+-------------------------+-------------------------------------------+
+| Method | Path                    | Description                               |
++========+=========================+===========================================+
+| GET    | /_config                | Obtain a list of the entire server        |
+|        |                         | configuration                             |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_config/section        | Get all the configuration values for the  |
+|        |                         | specified section                         |
++--------+-------------------------+-------------------------------------------+
+| GET    | /_config/section/key    | Get a specific section/configuration value|
++--------+-------------------------+-------------------------------------------+
+| PUT    | /_config/section/key    | Set the specified configuration value     |
++--------+-------------------------+-------------------------------------------+
+| DELETE | /_config/section/key    | Delete the current setting                |
++--------+-------------------------+-------------------------------------------+
+
+.. _api/config.get:
+
+``GET /_config``
+================
+
+* **Method**: ``GET /_config``
+* **Request**: None
+* **Response**: Returns a structure configuration name and value pairs,
+  organized by section
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+Returns the entire CouchDB server configuration as a JSON structure. The
+structure is organized by different configuration sections, with
+individual values.
+
+For example, to get the configuration for a server:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/_config
+    Accept: application/json
+
+The response is the JSON structure:
+
+.. code-block:: javascript
+
+    {
+       "query_server_config" : {
+          "reduce_limit" : "true"
+       },
+       "couchdb" : {
+          "os_process_timeout" : "5000",
+          "max_attachment_chunk_size" : "4294967296",
+          "max_document_size" : "4294967296",
+          "uri_file" : "/var/lib/couchdb/couch.uri",
+          "max_dbs_open" : "100",
+          "view_index_dir" : "/var/lib/couchdb",
+          "util_driver_dir" : "/usr/lib64/couchdb/erlang/lib/couch-1.0.1/priv/lib",
+          "database_dir" : "/var/lib/couchdb",
+          "delayed_commits" : "true"
+       },
+       "attachments" : {
+          "compressible_types" : "text/*, application/javascript, application/json,  application/xml",
+          "compression_level" : "8"
+       },
+       "uuids" : {
+          "algorithm" : "utc_random"
+       },
+       "daemons" : {
+          "view_manager" : "{couch_view, start_link, []}",
+          "auth_cache" : "{couch_auth_cache, start_link, []}",
+          "uuids" : "{couch_uuids, start, []}",
+          "stats_aggregator" : "{couch_stats_aggregator, start, []}",
+          "query_servers" : "{couch_query_servers, start_link, []}",
+          "httpd" : "{couch_httpd, start_link, []}",
+          "stats_collector" : "{couch_stats_collector, start, []}",
+          "db_update_notifier" : "{couch_db_update_notifier_sup, start_link, []}",
+          "external_manager" : "{couch_external_manager, start_link, []}"
+       },
+       "stats" : {
+          "samples" : "[0, 60, 300, 900]",
+          "rate" : "1000"
+       },
+       "httpd" : {
+          "vhost_global_handlers" : "_utils, _uuids, _session, _oauth, _users",
+          "secure_rewrites" : "true",
+          "authentication_handlers" : "{couch_httpd_oauth, oauth_authentication_handler},
+                                       {couch_httpd_auth, cookie_authentication_handler},
+                                       {couch_httpd_auth, default_authentication_handler}",
+          "port" : "5984",
+          "default_handler" : "{couch_httpd_db, handle_request}",
+          "allow_jsonp" : "false",
+          "bind_address" : "192.168.0.2",
+          "max_connections" : "2048"
+       },
+       "query_servers" : {
+          "javascript" : "/usr/bin/couchjs /usr/share/couchdb/server/main.js"
+       },
+       "couch_httpd_auth" : {
+          "authentication_db" : "_users",
+          "require_valid_user" : "false",
+          "authentication_redirect" : "/_utils/session.html",
+          "timeout" : "600",
+          "auth_cache_size" : "50"
+       },
+       "httpd_db_handlers" : {
+          "_design" : "{couch_httpd_db, handle_design_req}",
+          "_compact" : "{couch_httpd_db, handle_compact_req}",
+          "_view_cleanup" : "{couch_httpd_db, handle_view_cleanup_req}",
+          "_temp_view" : "{couch_httpd_view, handle_temp_view_req}",
+          "_changes" : "{couch_httpd_db, handle_changes_req}"
+       },
+       "replicator" : {
+          "max_http_sessions" : "10",
+          "max_http_pipeline_size" : "10"
+       },
+       "log" : {
+          "include_sasl" : "true",
+          "level" : "info",
+          "file" : "/var/log/couchdb/couch.log"
+       },
+       "httpd_design_handlers" : {
+          "_update" : "{couch_httpd_show, handle_doc_update_req}",
+          "_show" : "{couch_httpd_show, handle_doc_show_req}",
+          "_info" : "{couch_httpd_db,   handle_design_info_req}",
+          "_list" : "{couch_httpd_show, handle_view_list_req}",
+          "_view" : "{couch_httpd_view, handle_view_req}",
+          "_rewrite" : "{couch_httpd_rewrite, handle_rewrite_req}"
+       },
+       "httpd_global_handlers" : {
+          "_replicate" : "{couch_httpd_misc_handlers, handle_replicate_req}",
+          "/" : "{couch_httpd_misc_handlers, handle_welcome_req, <<\"Welcome\">>}",
+          "_config" : "{couch_httpd_misc_handlers, handle_config_req}",
+          "_utils" : "{couch_httpd_misc_handlers, handle_utils_dir_req, \"/usr/share/couchdb/www\"}",
+          "_active_tasks" : "{couch_httpd_misc_handlers, handle_task_status_req}",
+          "_session" : "{couch_httpd_auth, handle_session_req}",
+          "_log" : "{couch_httpd_misc_handlers, handle_log_req}",
+          "favicon.ico" : "{couch_httpd_misc_handlers, handle_favicon_req, \"/usr/share/couchdb/www\"}",
+          "_all_dbs" : "{couch_httpd_misc_handlers, handle_all_dbs_req}",
+          "_oauth" : "{couch_httpd_oauth, handle_oauth_req}",
+          "_restart" : "{couch_httpd_misc_handlers, handle_restart_req}",
+          "_uuids" : "{couch_httpd_misc_handlers, handle_uuids_req}",
+          "_stats" : "{couch_httpd_stats_handlers, handle_stats_req}"
+       }
+    }
+        
+
+.. _api/config/section:
+.. _api/config/section.get:
+
+``GET /_config/section``
+========================
+
+* **Method**: ``GET /_config/section``
+* **Request**: None
+* **Response**: All the configuration values within a specified section
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+Gets the configuration structure for a single section. For example, to
+retrieve the CouchDB configuration section values:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/_config/couchdb
+    Accept: application/json
+
+The returned JSON contains just the configuration values for this
+section:
+
+.. code-block:: javascript
+
+    {
+       "os_process_timeout" : "5000",
+       "max_attachment_chunk_size" : "4294967296",
+       "max_document_size" : "4294967296",
+       "uri_file" : "/var/lib/couchdb/couch.uri",
+       "max_dbs_open" : "100",
+       "view_index_dir" : "/var/lib/couchdb",
+       "util_driver_dir" : "/usr/lib64/couchdb/erlang/lib/couch-1.0.1/priv/lib",
+       "database_dir" : "/var/lib/couchdb",
+       "delayed_commits" : "true"
+    }
+
+.. _api/config/section/key:
+.. _api/config/section/key.get:
+
+``GET /_config/section/key``
+============================
+
+* **Method**: ``GET /_config/section/key``
+* **Request**: None
+* **Response**: Value of the specified key/section
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **200**:
+    Request completed successfully.
+
+Gets a single configuration value from within a specific configuration
+section. For example, to obtain the current log level:
+
+.. code-block:: http
+
+    GET http://couchdb:5984/_config/log/level
+    Accept: application/json
+
+Returns the string of the log level:
+
+.. code-block:: javascript
+
+    "info"
+
+.. note::
+   The returned value will be the JSON of the value, which may be a
+   string or numeric value, or an array or object. Some client
+   environments may not parse simple strings or numeric values as valid JSON.
+
+.. _api/config/section/key.put:
+
+``PUT /_config/section/key``
+============================
+
+* **Method**: ``PUT /_config/section/key``
+* **Request**: Value structure
+* **Response**: Previous value
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **200**:
+    Configuration option updated successfully
+
+  * **500**:
+    Error setting configuration
+
+Updates a configuration value. The new value should be supplied in the
+request body in the corresponding JSON format. For example, if you are
+setting a string value, you must supply a valid JSON string.
+
+For example, to set the function used to generate UUIDs by the
+``GET /_uuids`` API call to use the ``utc_random`` generator:
+
+.. code-block:: http
+
+    PUT http://couchdb:5984/_config/uuids/algorithm
+    Content-Type: application/json
+
+    "utc_random"
+
+The return value will be empty, with the response code indicating the
+success or failure of the configuration setting.
+
+.. _api/config/section/key.delete:
+
+``DELETE /_config/section/key``
+===============================
+
+* **Method**: ``DELETE /_config/section/key``
+* **Request**: None
+* **Response**: Previous value
+* **Admin Privileges Required**: yes
+* **Return Codes**:
+
+  * **409**:
+    Supplied revision is incorrect or missing
+
+Deletes a configuration value. The returned JSON will be the value of
+the configuration parameter before it was deleted. For example, to
+delete the UUID parameter:
+
+.. code-block:: http
+
+    DELETE http://couchdb:5984/_config/uuids/algorithm
+    Content-Type: application/json
+
+The returned value is the last configured UUID function:
+
+.. code-block:: javascript
+
+    "random"


[38/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add query server protocol definition.

COUCHDB-1657


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/11bf3d2a
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/11bf3d2a
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/11bf3d2a

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 11bf3d2a57c9a46e7f28644177b562b5e9092743
Parents: e22a833
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 10:41:03 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am             |   3 +
 share/doc/src/ddocs.rst                 |   2 +
 share/doc/src/query-server/index.rst    |   1 +
 share/doc/src/query-server/protocol.rst | 967 +++++++++++++++++++++++++++
 4 files changed, 973 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/11bf3d2a/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 1179968..322b9db 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -94,6 +94,7 @@ html_files = \
     html/_sources/query-server/index.txt \
     html/_sources/query-server/erlang.txt \
     html/_sources/query-server/javascript.txt \
+    html/_sources/query-server/protocol.txt \
     html/_sources/replications/conflicts.txt \
     html/_sources/replications/index.txt \
     html/_sources/replications/intro.txt \
@@ -177,6 +178,7 @@ html_files = \
     html/query-server/index.html \
     html/query-server/erlang.html \
     html/query-server/javascript.html \
+    html/query-server/protocol.html \
     html/replications/conflicts.html \
     html/replications/index.html \
     html/replications/intro.html \
@@ -258,6 +260,7 @@ src_files = \
     ../src/query-server/index.rst \
     ../src/query-server/erlang.rst \
     ../src/query-server/javascript.rst \
+    ../src/query-server/protocol.rst \
     ../src/replication/conflicts.rst \
     ../src/replication/index.rst \
     ../src/replication/intro.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/11bf3d2a/share/doc/src/ddocs.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/ddocs.rst b/share/doc/src/ddocs.rst
index 45a3773..2c1a490 100644
--- a/share/doc/src/ddocs.rst
+++ b/share/doc/src/ddocs.rst
@@ -534,6 +534,8 @@ and we can change filter behavior with easy::
 Combining filters with `continuous` feed allows to create powerful event-driven
 systems.
 
+.. _viewfilter:
+
 View filters
 ------------
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/11bf3d2a/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
index 8112549..b16e0ac 100644
--- a/share/doc/src/query-server/index.rst
+++ b/share/doc/src/query-server/index.rst
@@ -33,6 +33,7 @@ are assumed to be of type `javascript`, as are ad hoc queries that are POSTed to
 .. toctree::
    :maxdepth: 2
 
+   protocol
    javascript
    erlang
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/11bf3d2a/share/doc/src/query-server/protocol.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/query-server/protocol.rst b/share/doc/src/query-server/protocol.rst
new file mode 100644
index 0000000..9bc72e7
--- /dev/null
+++ b/share/doc/src/query-server/protocol.rst
@@ -0,0 +1,967 @@
+.. 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/protocol:
+
+=====================
+Query Server Protocol
+=====================
+
+The `Query server` is external process that communicates with CouchDB by JSON
+protocol through stdio interface and processed all design functions calls:
+`views`, `shows`, `lists`, `filters`, `updates` and `validate_doc_update`.
+
+CouchDB communicates with Query Server process though stdio interface by JSON
+messages that terminated by newline character. Messages that are sent to QS
+always `array`-typed that could be matched by the pattern
+``[<command>, <*arguments>]\n``.
+
+.. note::
+   To simplify examples reading we'd omitted trailing ``\n`` character to let
+   Sphinx highlight them well. Also, all examples contains formatted JSON values
+   while real data transfers in compact mode without formatting spaces.
+
+.. _qs/reset:
+
+``reset``
+=========
+
+:Command: ``reset``
+:Arguments: :ref:`Query server state <config/query_server_config>` (optional)
+:Returns: ``true``
+
+This resets the state of the Query Server and makes it forget all previous
+input. If applicable, this is the point to run garbage collection.
+
+CouchDB sends::
+
+    ["reset"]
+
+The Query Server answers::
+
+    true
+
+To set up new Query Server state the second argument is used with object data.
+This argument is used
+
+CouchDB sends::
+
+    ["reset", {"reduce_limit": true, "timeout": 5000}]
+
+The Query Server answers::
+
+    true
+
+
+.. _qs/add_lib:
+
+``add_lib``
+===========
+
+:Command: ``add_lib``
+:Arguments: CommonJS library object by ``views/lib`` path
+:Returns: ``true``
+
+Adds :ref:`CommonJS <commonjs>` library to Query Server state for further usage
+in `map` functions.
+
+CouchDB sends::
+
+  [
+    "add_lib",
+    {
+      "utils": "exports.MAGIC = 42;"
+    }
+  ]
+
+The Query Server answers::
+
+  true
+
+
+.. note::
+
+   This library shouldn't have any side effects nor track his own state
+   or you'll have a lot of happy debugging time if something went wrong.
+   Remember, that complete index rebuilding is heavy cost operation and this is
+   the only way to fix your mistakes with shared state.
+
+.. _qs/add_fun:
+
+``add_fun``
+-----------
+
+:Command: ``add_fun``
+:Arguments: Map function source code.
+:Returns: ``true``
+
+When creating or updating a view, the Query Server gets sent the view function
+for evaluation. The Query Server should parse/compile/evaluate the function he
+receives to make it callable later. If this fails, the Query Server returns an
+error. CouchDB might store several functions before sending in any actual
+documents.
+
+CouchDB sends::
+
+    [
+      "add_fun",
+      "function(doc) { if(doc.score > 50) emit(null, {'player_name': doc.name}); }"
+    ]
+
+The Query Server answers::
+
+    true
+
+
+.. _qs/map_doc:
+
+``map_doc``
+===========
+
+:Command: ``map_doc``
+:Arguments: Document object
+:Returns: Array of key-value pairs per applied :ref:`function <qs/add_fun>`
+
+When the view function is stored in the Query Server, CouchDB starts sending in
+all the documents in the database, one at a time. The Query Server calls the
+previously stored functions one after another with the document and stores its
+result. When all functions have been called, the result is returned as a JSON
+string.
+
+CouchDB sends::
+
+    [
+      "map_doc",
+      {
+        "_id": "8877AFF9789988EE",
+        "_rev": "3-235256484",
+        "name": "John Smith",
+        "score": 60
+      }
+    ]
+
+If the function above is the only function stored, the Query Server answers::
+
+    [
+      [
+        [null, {"player_name": "John Smith"}]
+      ]
+    ]
+
+That is, an array with the result for every function for the given document.
+
+If a document is to be excluded from the view, the array should be empty.
+
+CouchDB sends::
+
+    [
+      "map_doc",
+      {
+        "_id": "9590AEB4585637FE",
+        "_rev": "1-674684684",
+        "name": "Jane Parker",
+        "score": 43
+      }
+    ]
+
+The Query Server answers::
+
+    [[]]
+
+
+.. _qs/reduce:
+
+``reduce``
+==========
+
+:Command: ``reduce``
+:Arguments:
+  - Reduce function source
+  - Array of :ref:`map function <mapfun>` results where each item represented
+    in format ``[[key, id-of-doc], value]``
+:Returns: Array with pair values: ``true`` and another array with reduced result
+
+If the view has a reduce function defined, CouchDB will enter into the reduce
+phase. The view server will receive a list of reduce functions and some map
+results on which it can apply them.
+
+CouchDB sends::
+
+  [
+    "reduce",
+    [
+      "function(k, v) { return sum(v); }"
+    ],
+    [
+      [[1, "699b524273605d5d3e9d4fd0ff2cb272"], 10],
+      [[2, "c081d0f69c13d2ce2050d684c7ba2843"], 20],
+      [[null, "foobar"], 3]
+    ]
+  ]
+
+The Query Server answers::
+
+  [
+    true,
+    [33]
+  ]
+
+Note that even though the view server receives the map results in the form
+``[[key, id-of-doc], value]``, the function may receive them in a different
+form. For example, the JavaScript Query Server applies functions on the list of
+keys and the list of values.
+
+.. _qs/rereduce:
+
+``rereduce``
+============
+
+:Command: ``rereduce``
+:Arguments: List of values.
+
+When building a view, CouchDB will apply the reduce step directly to the output
+of the map step and the rereduce step to the output of a previous reduce step.
+
+CouchDB will send a list of values, with no keys or document ids, to the
+rereduce step.
+
+CouchDB sends::
+
+  [
+    "rereduce",
+    [
+      "function(k, v, r) { return sum(v); }"
+    ],
+    [
+      33,
+      55,
+      66
+    ]
+  ]
+
+The Query Server answers::
+
+  [
+    true,
+    [154]
+  ]
+
+
+.. _qs/ddoc:
+
+``ddoc``
+========
+
+:Command: ``ddoc``
+:Arguments: Array of objects.
+
+  - First phase (ddoc initialization):
+
+    - ``"new"``
+    - Design document ``_id``
+    - Design document object
+
+  - Second phase (design function execution):
+
+    - Design document ``_id``
+    - Function path as an array of object keys
+    - Array of function arguments
+
+:Returns:
+
+  - First phase (ddoc initialization): ``true``
+  - Second phase (design function execution): custom object depending on
+    executed function
+
+
+
+This command acts in two phases: `ddoc` registration and `design function`
+execution.
+
+On first phase CouchDB sends full design document content to the Query Server to
+let him cache it be ``_id`` value for further functions execution.
+
+To do this, CouchDB sends::
+
+  [
+    "ddoc",
+    "new",
+    "_design/temp",
+    {
+      "_id": "_design/temp",
+      "_rev": "8-d7379de23a751dc2a19e5638a7bbc5cc",
+      "language": "javascript",
+      "shows": {
+        "request": "function(doc,req){ return {json: req}; }",
+        "hello": "function(doc,req){ return {body: 'Hello, ' + (doc || {})._id + '!'}; }"
+      }
+    }
+  ]
+
+The Query Server answers::
+
+  true
+
+
+After than this design document is ready to serve next subcommands - that's the
+second phase.
+
+.. note::
+
+   Each ``ddoc`` subcommand is the root design document key, so they are not
+   actually subcommands, but first elements of the JSON path that may be handled
+   and processed.
+
+   The pattern for subcommand execution is common:
+
+   ``["ddoc", <design_doc_id>, [<subcommand>, <funcname>], [<argument1>, <argument2>, ...]]``
+
+
+.. _qs/ddoc/shows:
+
+``shows``
+---------
+
+:Command: ``ddoc``
+:SubCommand: ``shows``
+:Arguments:
+
+  - Document object or ``null`` if document `id` wasn't specified in request
+  - :ref:`request_object`
+
+:Returns: Array with two elements:
+
+  - ``"resp"``
+  - :ref:`response_object`
+
+Executes :ref:`show function <showfun>`.
+
+Couchdb sends::
+
+  [
+    "ddoc",
+    "_design/temp",
+    [
+        "shows",
+        "doc"
+    ],
+    [
+      null,
+      {
+        "info": {
+          "db_name": "test",
+          "doc_count": 8,
+          "doc_del_count": 0,
+          "update_seq": 105,
+          "purge_seq": 0,
+          "compact_running": false,
+          "disk_size": 15818856,
+          "data_size": 1535048,
+          "instance_start_time": "1359952188595857",
+          "disk_format_version": 6,
+          "committed_update_seq": 105
+        },
+        "id": null,
+        "uuid": "169cb4cc82427cc7322cb4463d0021bb",
+        "method": "GET",
+        "requested_path": [
+          "api",
+          "_design",
+          "temp",
+          "_show",
+          "request"
+        ],
+        "path": [
+          "api",
+          "_design",
+          "temp",
+          "_show",
+          "request"
+        ],
+        "raw_path": "/api/_design/temp/_show/request",
+        "query": {},
+        "headers": {
+          "Accept": "*/*",
+          "Host": "localhost:5984",
+          "User-Agent": "curl/7.26.0"
+        },
+        "body": "undefined",
+        "peer": "127.0.0.1",
+        "form": {},
+        "cookie": {},
+        "userCtx": {
+          "db": "api",
+          "name": null,
+          "roles": [
+            "_admin"
+          ]
+        },
+        "secObj": {}
+      }
+    ]
+  ]
+
+The Query Server sends::
+
+  [
+    "resp",
+    {
+      "body": "Hello, undefined!"
+    }
+  ]
+
+
+.. _qs/ddoc/lists:
+
+``lists``
+---------
+
+:Command: ``ddoc``
+:SubCommand: ``lists``
+:Arguments:
+
+  - :ref:`view_head_info_object`:
+  - :ref:`request_object`
+
+:Returns: Array. See below for details.
+
+Executes :ref:`list function <listfun>`.
+
+The communication protocol for `list` functions is a bit complex so let's use
+some example to have a talk about real things.
+
+Let assume, that we have view function, that emits document's `id-rev` pairs::
+
+  function(doc) {
+    emit(doc._id, doc._rev);
+  }
+
+And we'd like to emulate ``_all_docs`` JSON response with list function. Our
+*first* version of the list functions will be the next::
+
+  function(head, req){
+    start({'headers': {'Content-Type': 'application/json'}});
+    var resp = head;
+    var rows = [];
+    while(row=getRow()){
+      rows.push(row);
+    }
+    resp.rows = rows;
+    return toJSON(resp);
+  }
+
+The whole communication session during list function execution could be divided
+on three parts:
+
+#. Initialization
+
+   The first returned object from list function is an array of next structure::
+
+      ["start", <chunks>, <headers>]
+
+   Where ``<chunks>`` is an array of text chunks that will be sent to client
+   and ``<headers>`` is an object with response HTTP headers.
+
+   This message sends from Query Server to the CouchDB on :js:func:`start` call
+   which initialize HTTP response to the client::
+
+     [
+       "start",
+       [],
+       {
+         "headers": {
+           "Content-Type": "application/json"
+         }
+       }
+     ]
+
+   After this, the list function may start to process view rows.
+
+#. View Processing
+
+   Since view result could be extremely large, it's not wise to pass all his
+   rows with single command. Instead of this, CouchDB send view rows one by one
+   to Query Server allowing processing view and output generation in streaming
+   way.
+
+   CouchDB sends special array that carries view row data::
+
+     [
+       "list_row",
+       {
+         "id": "0cb42c267fe32d4b56b3500bc503e030",
+         "key": "0cb42c267fe32d4b56b3500bc503e030",
+         "value": "1-967a00dff5e02add41819138abb3284d"
+       }
+     ]
+
+   If Query Server has something to return on this, he returns back array with
+   ``"chunks"`` item in head and array of data at the tail. Suddenly, for our
+   case there he has nothing to return, so the response will be::
+
+     [
+       "chunks",
+       []
+     ]
+
+   When there is no more view rows to process, CouchDB sends special message,
+   that signs about that there is no more data to send from his side::
+
+     ["list_end"]
+
+
+#. Finalization
+
+   The last stage of the communication process is the returning *list tail*:
+   the last data chunk. After this, processing list function will be completed
+   and client will receive complete response.
+
+   For our example the last message will be the next::
+
+     [
+       "end",
+       [
+         "{\"total_rows\":2,\"offset\":0,\"rows\":[{\"id\":\"0cb42c267fe32d4b56b3500bc503e030\",\"key\":\"0cb42c267fe32d4b56b3500bc503e030\",\"value\":\"1-967a00dff5e02add41819138abb3284d\"},{\"id\":\"431926a69504bde41851eb3c18a27b1f\",\"key\":\"431926a69504bde41851eb3c18a27b1f\",\"value\":\"1-967a00dff5e02add41819138abb3284d\"}]}"
+       ]
+     ]
+
+There, we had made a big mistake: we had return result in single message from
+the Query Server. It's ok while there are few data in the database, but it's
+not acceptable for millions documents and millions view rows.
+
+Let's fix our list function and see the changes in communication::
+
+  function(head, req){
+    start({'headers': {'Content-Type': 'application/json'}});
+    send('{');
+    send('"total_rows":' + toJSON(head.total_rows) + ',');
+    send('"offset":' + toJSON(head.offset) + ',');
+    send('"rows":[');
+    if (row=getRow()){
+      send(toJSON(row));
+    }
+    while(row=getRow()){
+      send(',' + toJSON(row));
+    }
+    send(']');
+    return '}';
+  }
+
+"Wait, what?" - you'd like to ask. Yes, we'd build JSON response manually by
+string chunks, but let's take a look on logs::
+
+  [Wed, 24 Jul 2013 05:45:30 GMT] [debug] [<0.19191.1>] OS Process #Port<0.4444> Output :: ["start",["{","\"total_rows\":2,","\"offset\":0,","\"rows\":["],{"headers":{"Content-Type":"application/json"}}]
+  [Wed, 24 Jul 2013 05:45:30 GMT] [info] [<0.18963.1>] 127.0.0.1 - - GET /blog/_design/post/_list/index/all_docs 200
+  [Wed, 24 Jul 2013 05:45:30 GMT] [debug] [<0.19191.1>] OS Process #Port<0.4444> Input  :: ["list_row",{"id":"0cb42c267fe32d4b56b3500bc503e030","key":"0cb42c267fe32d4b56b3500bc503e030","value":"1-967a00dff5e02add41819138abb3284d"}]
+  [Wed, 24 Jul 2013 05:45:30 GMT] [debug] [<0.19191.1>] OS Process #Port<0.4444> Output :: ["chunks",["{\"id\":\"0cb42c267fe32d4b56b3500bc503e030\",\"key\":\"0cb42c267fe32d4b56b3500bc503e030\",\"value\":\"1-967a00dff5e02add41819138abb3284d\"}"]]
+  [Wed, 24 Jul 2013 05:45:30 GMT] [debug] [<0.19191.1>] OS Process #Port<0.4444> Input  :: ["list_row",{"id":"431926a69504bde41851eb3c18a27b1f","key":"431926a69504bde41851eb3c18a27b1f","value":"1-967a00dff5e02add41819138abb3284d"}]
+  [Wed, 24 Jul 2013 05:45:30 GMT] [debug] [<0.19191.1>] OS Process #Port<0.4444> Output :: ["chunks",[",{\"id\":\"431926a69504bde41851eb3c18a27b1f\",\"key\":\"431926a69504bde41851eb3c18a27b1f\",\"value\":\"1-967a00dff5e02add41819138abb3284d\"}"]]
+  [Wed, 24 Jul 2013 05:45:30 GMT] [debug] [<0.19191.1>] OS Process #Port<0.4444> Input  :: ["list_end"]
+  [Wed, 24 Jul 2013 05:45:30 GMT] [debug] [<0.19191.1>] OS Process #Port<0.4444> Output :: ["end",["]","}"]]
+
+Note, that now the Query Server sends response by lightweight chunks and if
+our communication process was extremely slow, the client will see how response
+data appears on his screen. Chunk by chunk, without waiting for the complete
+result, like he have for our previous list function.
+
+.. _qs/ddoc/updates:
+
+``updates``
+-----------
+
+:Command: ``ddoc``
+:SubCommand: ``updates``
+:Arguments:
+
+  - Document object or ``null`` if document `id` wasn't specified in request
+  - :ref:`request_object`
+
+:Returns: Array with there elements:
+
+  - ``"up"``
+  - Document object or ``null`` if nothing should be stored
+  - :ref:`response_object`
+
+Executes :ref:`update function <updatefun>`.
+
+CouchDB sends::
+
+    [
+        "ddoc",
+        "_design/id",
+        [
+            "updates",
+            "nothing"
+        ],
+        [
+            null,
+            {
+                "info": {
+                    "db_name": "test",
+                    "doc_count": 5,
+                    "doc_del_count": 0,
+                    "update_seq": 16,
+                    "purge_seq": 0,
+                    "compact_running": false,
+                    "disk_size": 8044648,
+                    "data_size": 7979601,
+                    "instance_start_time": "1374612186131612",
+                    "disk_format_version": 6,
+                    "committed_update_seq": 16
+                },
+                "id": null,
+                "uuid": "7b695cb34a03df0316c15ab529002e69",
+                "method": "POST",
+                "requested_path": [
+                    "test",
+                    "_design",
+                    "1139",
+                    "_update",
+                    "nothing"
+                ],
+                "path": [
+                    "test",
+                    "_design",
+                    "1139",
+                    "_update",
+                    "nothing"
+                ],
+                "raw_path": "/test/_design/1139/_update/nothing",
+                "query": {},
+                "headers": {
+                    "Accept": "*/*",
+                    "Accept-Encoding": "identity, gzip, deflate, compress",
+                    "Content-Length": "0",
+                    "Host": "localhost:5984"
+                },
+                "body": "",
+                "peer": "127.0.0.1",
+                "form": {},
+                "cookie": {},
+                "userCtx": {
+                    "db": "test",
+                    "name": null,
+                    "roles": [
+                        "_admin"
+                    ]
+                },
+                "secObj": {}
+            }
+        ]
+    ]
+
+The Query Server answers::
+
+  [
+    "up",
+    null,
+    {"body": "document id wasn't provided"}
+  ]
+
+or in case of successful update::
+
+  [
+    "up",
+    {
+      "_id": "7b695cb34a03df0316c15ab529002e69",
+      "hello": "world!"
+    },
+    {"body": "document was updated"}
+  ]
+
+
+.. _qs/ddoc/filters:
+
+``filters``
+-----------
+
+:Command: ``ddoc``
+:SubCommand: ``filters``
+:Arguments:
+
+  - Array of document objects
+  - :ref:`request_object`
+
+:Returns: Array of two elements:
+
+  - ``true``
+  - Array of booleans in the same order of input documents.
+
+Executes :ref:`filter function <filterfun>`.
+
+CouchDB sends::
+
+  [
+      "ddoc",
+      "_design/test",
+      [
+          "filters",
+          "random"
+      ],
+      [
+          [
+              {
+                  "_id": "431926a69504bde41851eb3c18a27b1f",
+                  "_rev": "1-967a00dff5e02add41819138abb3284d",
+                  "_revisions": {
+                      "start": 1,
+                      "ids": [
+                          "967a00dff5e02add41819138abb3284d"
+                      ]
+                  }
+              },
+              {
+                  "_id": "0cb42c267fe32d4b56b3500bc503e030",
+                  "_rev": "1-967a00dff5e02add41819138abb3284d",
+                  "_revisions": {
+                      "start": 1,
+                      "ids": [
+                          "967a00dff5e02add41819138abb3284d"
+                      ]
+                  }
+              }
+          ],
+          {
+              "info": {
+                  "db_name": "test",
+                  "doc_count": 5,
+                  "doc_del_count": 0,
+                  "update_seq": 19,
+                  "purge_seq": 0,
+                  "compact_running": false,
+                  "disk_size": 8056936,
+                  "data_size": 7979745,
+                  "instance_start_time": "1374612186131612",
+                  "disk_format_version": 6,
+                  "committed_update_seq": 19
+              },
+              "id": null,
+              "uuid": "7b695cb34a03df0316c15ab529023a81",
+              "method": "GET",
+              "requested_path": [
+                  "test",
+                  "_changes?filter=test",
+                  "random"
+              ],
+              "path": [
+                  "test",
+                  "_changes"
+              ],
+              "raw_path": "/test/_changes?filter=test/random",
+              "query": {
+                  "filter": "test/random"
+              },
+              "headers": {
+                  "Accept": "application/json",
+                  "Accept-Encoding": "identity, gzip, deflate, compress",
+                  "Content-Length": "0",
+                  "Content-Type": "application/json; charset=utf-8",
+                  "Host": "localhost:5984"
+              },
+              "body": "",
+              "peer": "127.0.0.1",
+              "form": {},
+              "cookie": {},
+              "userCtx": {
+                  "db": "test",
+                  "name": null,
+                  "roles": [
+                      "_admin"
+                  ]
+              },
+              "secObj": {}
+          }
+      ]
+  ]
+
+The Query Server answers::
+
+  [
+    true,
+    [
+      true,
+      false
+    ]
+  ]
+
+
+
+.. _qs/ddoc/views:
+
+``views``
+---------
+
+:Command: ``ddoc``
+:SubCommand: ``views``
+:Arguments: Array of document objects
+:Returns: Array of two elements:
+
+  - ``true``
+  - Array of booleans in the same order of input documents.
+
+.. versionadded:: 1.2
+
+Executes :ref:`view function <viewfilter>` in place of the filter.
+
+Acts in the same way as :ref:`qs/ddoc/filters` command.
+
+.. _qs/ddoc/validate_doc_update:
+
+``validate_doc_update``
+-----------------------
+
+:Command: ``ddoc``
+:SubCommand: ``validate_doc_update``
+:Arguments:
+
+  - Document object that will be stored
+  - Document object that will be replaced
+  - :ref:`userctx_object`
+  - :ref:`security_object`
+
+:Returns: ``1``
+
+Executes :ref:`validation function <vdufun>`.
+
+CouchDB send::
+
+  [
+    "ddoc",
+    "_design/id",
+    ["validate_doc_update"],
+    [
+      {
+        "_id": "docid",
+        "_rev": "2-e0165f450f6c89dc6b071c075dde3c4d",
+        "score": 10
+      },
+      {
+        "_id": "docid",
+        "_rev": "1-9f798c6ad72a406afdbf470b9eea8375",
+        "score": 4
+      },
+      {
+        "name": "Mike",
+        "roles": ["player"]
+      },
+      {
+        "admins": {},
+        "members": []
+      }
+    ]
+  ]
+
+The Query Server answers::
+
+  1
+
+.. note::
+
+   While the only valid response for this command is ``true`` to prevent
+   document save the Query Server need to raise an error: ``forbidden`` or
+   ``unauthorized`` - these errors will be turned into correct ``HTTP 403`` and
+   ``HTTP 401`` responses respectively.
+
+
+.. _qs/errors:
+
+Raising errors
+==============
+
+When something went wrong the Query Server is able to inform CouchDB about
+such situation by sending special message in response of received command.
+
+Error messages prevents further command execution and returns error description
+to the CouchDB. Since this point all errors are logically divided into two
+groups:
+
+- `Common errors`. These errors are only breaks current query server command and
+  returns the error info to CouchDB instance *without* terminating Query Server
+  process.
+- `Fatal errors`. The fatal errors signs about something really bad that hurts
+  overall Query Server process stability and productivity. For instance, if
+  you're using Python Query Server and some design function is unable to import
+  some third party module, it's better to count such error as fatal and
+  terminate whole process or you still have to do the same after import fixing,
+  but manually.
+
+.. _qs/error:
+
+``error``
+---------
+
+To raise an error, the Query Server have to answer::
+
+  ["error", "error_name", "reason why"]
+
+The ``"error_name"`` helps to classify problems by their type e.g. if it's
+``"value_error"`` so probably user have entered wrong data, ``"not_found"``
+notifies about missed resource and ``"type_error"`` definitely says about
+invalid and non expected input from user.
+
+The ``"reason why"`` is the error message that explains why it raised and, if
+possible, what need to do to fix it.
+
+For example, calling :ref:`updatefun` against non existed document could produce
+next error message::
+
+  ["error", "not_found", "Update function requires existed document"]
+
+
+.. _qs/error/forbidden:
+
+``forbidden``
+-------------
+
+The `forbidden` error are widely used by :ref:`vdufun` to stop further function
+processing and prevent on disk store of the new document version. Since this
+errors actually is not an error, but an assertion against user actions, CouchDB
+doesn't log it at `"error"` level, but returns `HTTP 403 Forbidden` response
+with error information object.
+
+To raise this error, the Query Server have to answer::
+
+  {"forbidden": "reason why"}
+
+
+.. _qs/error/unauthorized:
+
+``unauthorized``
+----------------
+
+The `unauthorized` error mostly acts like `forbidden` one, but with
+semantic as *please authorize first*. This small difference helps end user to
+understand what he can do to solve the problem. CouchDB doesn't log it at
+`"error"` level, but returns `HTTP 401 Unauthorized` response with error
+information object.
+
+To raise this error, the Query Server have to answer::
+
+  {"unauthorized": "reason why"}
+
+.. _qs/log:
+
+Logging
+=======
+
+At any time, the Query Server may send some information that will be saved in
+CouchDB's log file. This is done by sending a special object with just one
+field, log, on a separate line::
+
+  ["log", "some message"]
+
+CouchDB response nothing, but writes received message into log file::
+
+  [Sun, 13 Feb 2009 23:31:30 GMT] [info] [<0.72.0>] Query Server Log Message: some message
+
+These messages are only logged at :ref:`info level <config/log/level>`.


[06/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Set header for replicator options group.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/7315da07
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/7315da07
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/7315da07

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 7315da07e6ad46587780b0328cfb7639851eca4a
Parents: 1a06693
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 17 08:55:44 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/config/index.rst      | 3 +--
 share/doc/src/config/replicator.rst | 8 ++++----
 2 files changed, 5 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/7315da07/share/doc/src/config/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/index.rst b/share/doc/src/config/index.rst
index f678b21..5db70f8 100644
--- a/share/doc/src/config/index.rst
+++ b/share/doc/src/config/index.rst
@@ -25,10 +25,9 @@ Configuring CouchDB
    auth
    compaction
    logging
+   replicator
    query-servers
    externals
    services
    misc
    proxying
-
-   replicator

http://git-wip-us.apache.org/repos/asf/couchdb/blob/7315da07/share/doc/src/config/replicator.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/replicator.rst b/share/doc/src/config/replicator.rst
index 883b051..bac4d49 100644
--- a/share/doc/src/config/replicator.rst
+++ b/share/doc/src/config/replicator.rst
@@ -12,6 +12,10 @@
 
 .. highlight:: ini
 
+==========
+Replicator
+==========
+
 .. _config/replicator:
 
 ``[replicator]`` :: Replicator Database Configuration
@@ -19,10 +23,6 @@
 
 .. versionadded:: 1.2
 
-These options are under ``[replicator]`` section and applies to
-:ref:`replicator` feature.
-
-
 .. _config/replicator/db:
 
 ``db``


[04/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add sections anchors for /db/_local API.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/b226efc0
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/b226efc0
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/b226efc0

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: b226efc0fa16ce3e7f79dbbcbf82e1e3582a6522
Parents: 5be91ec
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 21:43:50 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/local.rst | 6 ++++++
 1 file changed, 6 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/b226efc0/share/doc/src/api/local.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/local.rst b/share/doc/src/api/local.rst
index e6a2ede..bc251ec 100644
--- a/share/doc/src/api/local.rst
+++ b/share/doc/src/api/local.rst
@@ -98,6 +98,8 @@ Gets the specified local document. The semantics are identical to
 accessing a standard document in the specified database, except that the
 document is not replicated. See :ref:`api/doc.get`.
 
+.. _api/local/doc.put:
+
 ``PUT /db/_local/local-doc``
 ============================
 
@@ -114,6 +116,8 @@ Stores the specified local document. The semantics are identical to
 storing a standard document in the specified database, except that the
 document is not replicated. See :ref:`api/doc.put`.
 
+.. _api/local/doc.delete:
+
 ``DELETE /db/_local/local-doc``
 ===============================
 
@@ -145,6 +149,8 @@ Deletes the specified local document. The semantics are identical to
 deleting a standard document in the specified database, except that the
 document is not replicated. See :ref:`api/doc.delete`.
 
+.. _api/local/doc.copy:
+
 ``COPY /db/_local/local-doc``
 =============================
 


[12/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Use singular name for article groups.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/391bea7a
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/391bea7a
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/391bea7a

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 391bea7a922d7277cac8c005bf1b76c69c56cb6e
Parents: c199cd9
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 22:52:41 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am               |  10 +-
 share/doc/src/index.rst                   |   2 +-
 share/doc/src/replication/conflicts.rst   | 786 +++++++++++++++++++++++++
 share/doc/src/replication/index.rst       |  37 ++
 share/doc/src/replication/intro.rst       |  95 +++
 share/doc/src/replication/protocol.rst    | 201 +++++++
 share/doc/src/replication/replicator.rst  | 383 ++++++++++++
 share/doc/src/replications/conflicts.rst  | 786 -------------------------
 share/doc/src/replications/index.rst      |  37 --
 share/doc/src/replications/intro.rst      |  95 ---
 share/doc/src/replications/protocol.rst   | 201 -------
 share/doc/src/replications/replicator.rst | 383 ------------
 12 files changed, 1508 insertions(+), 1508 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 2519f7e..a8c8fca 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -184,11 +184,11 @@ src_files = \
     ../src/config/services.rst \
     ../src/config/intro.rst \
     ../src/config/proxying.rst \
-    ../src/replications/conflicts.rst \
-    ../src/replications/index.rst \
-    ../src/replications/intro.rst \
-    ../src/replications/protocol.rst \
-    ../src/replications/replicator.rst \
+    ../src/replication/conflicts.rst \
+    ../src/replication/index.rst \
+    ../src/replication/intro.rst \
+    ../src/replication/protocol.rst \
+    ../src/replication/replicator.rst \
     ../src/changelog.rst \
     ../src/changes.rst \
     ../src/contributing.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/index.rst b/share/doc/src/index.rst
index 4a3a51b..1ff3d40 100644
--- a/share/doc/src/index.rst
+++ b/share/doc/src/index.rst
@@ -29,7 +29,7 @@ Contents
 
     intro
     config/index
-    replications/index
+    replication/index
     ddocs
     query-servers
     changes

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replication/conflicts.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication/conflicts.rst b/share/doc/src/replication/conflicts.rst
new file mode 100644
index 0000000..404d256
--- /dev/null
+++ b/share/doc/src/replication/conflicts.rst
@@ -0,0 +1,786 @@
+.. 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.
+
+
+.. _replication/conflicts:
+
+==============================
+Replication and conflict model
+==============================
+
+Let's take the following example to illustrate replication and conflict handling.
+
+- Alice has a document containing Bob's business card;
+- She synchronizes it between her desktop PC and her laptop;
+- On the desktop PC, she updates Bob's E-mail address;
+  Without syncing again, she updates Bob's mobile number on the laptop;
+- Then she replicates the two to each other again.
+
+So on the desktop the document has Bob's new E-mail address and his old mobile
+number, and on the laptop it has his old E-mail address and his new mobile
+number.
+
+The question is, what happens to these conflicting updated documents?
+
+CouchDB replication
+===================
+
+CouchDB works with JSON documents inside databases. Replication of databases
+takes place over HTTP, and can be either a "pull" or a "push", but is
+unidirectional. So the easiest way to perform a full sync is to do a "push"
+followed by a "pull" (or vice versa).
+
+So, Alice creates v1 and sync it. She updates to v2a on one side and v2b on the
+other, and then replicates. What happens?
+
+The answer is simple: both versions exist on both sides!
+
+.. code-block:: text
+
+     DESKTOP                          LAPTOP
+   +---------+
+   | /db/bob |                                     INITIAL
+   |   v1    |                                     CREATION
+   +---------+
+
+   +---------+                      +---------+
+   | /db/bob |  ----------------->  | /db/bob |     PUSH
+   |   v1    |                      |   v1    |
+   +---------+                      +---------+
+
+   +---------+                      +---------+  INDEPENDENT
+   | /db/bob |                      | /db/bob |     LOCAL
+   |   v2a   |                      |   v2b   |     EDITS
+   +---------+                      +---------+
+
+   +---------+                      +---------+
+   | /db/bob |  ----------------->  | /db/bob |     PUSH
+   |   v2a   |                      |   v2a   |
+   +---------+                      |   v2b   |
+                                    +---------+
+
+   +---------+                      +---------+
+   | /db/bob |  <-----------------  | /db/bob |     PULL
+   |   v2a   |                      |   v2a   |
+   |   v2b   |                      |   v2b   |
+   +---------+                      +---------+
+
+After all, this is not a filesystem, so there's no restriction that only one
+document can exist with the name /db/bob. These are just "conflicting" revisions
+under the same name.
+
+Because the changes are always replicated, the data is safe. Both machines have
+identical copies of both documents, so failure of a hard drive on either side
+won't lose any of the changes.
+
+Another thing to notice is that peers do not have to be configured or tracked.
+You can do regular replications to peers, or you can do one-off, ad-hoc pushes
+or pulls. After the replication has taken place, there is no record kept of
+which peer any particular document or revision came from.
+
+So the question now is: what happens when you try to read /db/bob? By default,
+CouchDB picks one arbitrary revision as the "winner", using a deterministic
+algorithm so that the same choice will be made on all peers. The same happens
+with views: the deterministically-chosen winner is the only revision fed into
+your map function.
+
+Let's say that the winner is v2a. On the desktop, if Alice reads the document
+she'll see v2a, which is what she saved there. But on the laptop, after
+replication, she'll also see only v2a. It could look as if the changes she made
+there have been lost - but of course they have not, they have just been hidden
+away as a conflicting revision. But eventually she'll need these changes merged
+into Bob's business card, otherwise they will effectively have been lost.
+
+Any sensible business-card application will, at minimum, have to present the
+conflicting versions to Alice and allow her to create a new version
+incorporating information from them all. Ideally it would merge the updates
+itself.
+
+Conflict avoidance
+==================
+
+When working on a single node, CouchDB will avoid creating conflicting revisions
+by returning a 409 HTTP error. This is because, when you PUT a new version of a
+document, you must give the ``_rev`` of the previous version. If that ``_rev``
+has already been superseded, the update is rejected with a ``HTTP 409 Conflict``.
+
+So imagine two users on the same node are fetching Bob's business card, updating
+it concurrently, and writing it back:
+
+.. code-block:: text
+
+  USER1    ----------->  GET /db/bob
+           <-----------  {"_rev":"1-aaa", ...}
+
+  USER2    ----------->  GET /db/bob
+           <-----------  {"_rev":"1-aaa", ...}
+
+  USER1    ----------->  PUT /db/bob?rev=1-aaa
+           <-----------  {"_rev":"2-bbb", ...}
+
+  USER2    ----------->  PUT /db/bob?rev=1-aaa
+           <-----------  409 Conflict  (not saved)
+
+User2's changes are rejected, so it's up to the app to fetch /db/bob again,
+and either:
+
+#. apply the same changes as were applied to the earlier revision, and submit
+   a new PUT
+#. redisplay the document so the user has to edit it again
+#. just overwrite it with the document being saved before (which is not
+   advisable, as user1's changes will be silently lost)
+
+So when working in this mode, your application still has to be able to handle
+these conflicts and have a suitable retry strategy, but these conflicts never
+end up inside the database itself.
+
+Conflicts in batches
+====================
+
+There are two different ways that conflicts can end up in the database:
+
+- Conflicting changes made on different databases, which are replicated to each
+  other, as shown earlier.
+- Changes are written to the database using ``_bulk_docs`` and all_or_nothing,
+  which bypasses the 409 mechanism.
+
+The :ref:`_bulk_docs API <api/db/bulk_docs>` lets you submit multiple updates
+(and/or deletes) in a single HTTP POST. Normally, these are treated as
+independent updates; some in the batch may fail because the `_rev` is stale
+(just like a 409 from a PUT) whilst others are written successfully.
+The response from ``_bulk_docs`` lists the success/fail separately for each
+document in the batch.
+
+However there is another mode of working, whereby you specify
+``{"all_or_nothing":true}`` as part of the request. This is CouchDB's nearest
+equivalent of a "transaction", but it's not the same as a database transaction
+which can fail and roll back. Rather, it means that all of the changes in the
+request will be forcibly applied to the database, even if that introduces
+conflicts. The only guarantee you are given is that they will either all be
+applied to the database, or none of them (e.g. if the power is pulled out before
+the update is finished writing to disk).
+
+So this gives you a way to introduce conflicts within a single database
+instance. If you choose to do this instead of PUT, it means you don't have to
+write any code for the possibility of getting a 409 response, because you will
+never get one. Rather, you have to deal with conflicts appearing later in the
+database, which is what you'd have to do in a multi-master application anyway.
+
+.. code-block:: http
+
+  POST /db/_bulk_docs
+
+.. code-block:: javascript
+
+  {
+    "all_or_nothing": true,
+    "docs": [
+      {"_id":"x", "_rev":"1-xxx", ...},
+      {"_id":"y", "_rev":"1-yyy", ...},
+      ...
+    ]
+  }
+
+Revision tree
+=============
+
+When you update a document in CouchDB, it keeps a list of the previous
+revisions. In the case where conflicting updates are introduced, this history
+branches into a tree, where the current conflicting revisions for this document
+form the tips (leaf nodes) of this tree:
+
+.. code-block:: text
+
+      ,--> r2a
+    r1 --> r2b
+      `--> r2c
+
+Each branch can then extend its history - for example if you read revision r2b
+and then PUT with ?rev=r2b then you will make a new revision along that
+particular branch.
+
+.. code-block:: text
+
+      ,--> r2a -> r3a -> r4a
+    r1 --> r2b -> r3b
+      `--> r2c -> r3c
+
+Here, (r4a, r3b, r3c) are the set of conflicting revisions. The way you resolve
+a conflict is to delete the leaf nodes along the other branches. So when you
+combine (r4a+r3b+r3c) into a single merged document, you would replace r4a and
+delete r3b and r3c.
+
+.. code-block:: text
+
+      ,--> r2a -> r3a -> r4a -> r5a
+    r1 --> r2b -> r3b -> (r4b deleted)
+      `--> r2c -> r3c -> (r4c deleted)
+
+Note that r4b and r4c still exist as leaf nodes in the history tree, but as
+deleted docs. You can retrieve them but they will be marked ``"_deleted":true``.
+
+When you compact a database, the bodies of all the non-leaf documents are
+discarded. However, the list of historical _revs is retained, for the benefit of
+later conflict resolution in case you meet any old replicas of the database at
+some time in future. There is "revision pruning" to stop this getting
+arbitrarily large.
+
+Working with conflicting documents
+==================================
+
+The basic :ref:`GET /db/bob <api/doc.get>` operation will not show you any
+information about conflicts. You see only the deterministically-chosen winner,
+and get no indication as to whether other conflicting revisions exist or not:
+
+.. code-block:: javascript
+
+  {
+    "_id":"test",
+    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+    "hello":"bar"
+  }
+
+If you do ``GET /db/bob?conflicts=true``, and the document is in a conflict
+state, then you will get the winner plus a _conflicts member containing an array
+of the revs of the other, conflicting revision(s). You can then fetch them
+individually using subsequent ``GET /db/bob?rev=xxxx`` operations:
+
+.. code-block:: javascript
+
+  {
+    "_id":"test",
+    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+    "hello":"bar",
+    "_conflicts":[
+      "2-65db2a11b5172bf928e3bcf59f728970",
+      "2-5bc3c6319edf62d4c624277fdd0ae191"
+    ]
+  }
+
+If you do ``GET /db/bob?open_revs=all`` then you will get all the leaf nodes of
+the revision tree. This will give you all the current conflicts, but will also
+give you leaf nodes which have been deleted (i.e. parts of the conflict history
+which have since been resolved). You can remove these by filtering out documents
+with ``"_deleted":true``:
+
+.. code-block:: javascript
+
+  [
+    {"ok":{"_id":"test","_rev":"2-5bc3c6319edf62d4c624277fdd0ae191","hello":"foo"}},
+    {"ok":{"_id":"test","_rev":"2-65db2a11b5172bf928e3bcf59f728970","hello":"baz"}},
+    {"ok":{"_id":"test","_rev":"2-b91bb807b4685080c6a651115ff558f5","hello":"bar"}}
+  ]
+
+The ``"ok"`` tag is an artifact of ``open_revs``, which also lets you list
+explicit revisions as a JSON array, e.g. ``open_revs=[rev1,rev2,rev3]``. In this
+form, it would be possible to request a revision which is now missing, because
+the database has been compacted.
+
+.. note::
+  The order of revisions returned by ``open_revs=all`` is **NOT** related to
+  the deterministic "winning" algorithm. In the above example, the winning
+  revision is 2-b91b... and happens to be returned last, but in other cases it
+  can be returned in a different position.
+
+Once you have retrieved all the conflicting revisions, your application can then
+choose to display them all to the user. Or it could attempt to merge them, write
+back the merged version, and delete the conflicting versions - that is, to
+resolve the conflict permanently.
+
+As described above, you need to update one revision and delete all the
+conflicting revisions explicitly. This can be done using a single `POST` to
+``_bulk_docs``, setting ``"_deleted":true`` on those revisions you wish to
+delete.
+
+Multiple document API
+=====================
+
+You can fetch multiple documents at once using ``include_docs=true`` on a view.
+However, a ``conflicts=true`` request is ignored; the "doc" part of the value
+never includes a ``_conflicts`` member. Hence you would need to do another query
+to determine for each document whether it is in a conflicting state:
+
+.. code-block:: bash
+
+  $ curl 'http://127.0.0.1:5984/conflict_test/_all_docs?include_docs=true&conflicts=true'
+
+.. code-block:: javascript
+
+  {
+    "total_rows":1,
+    "offset":0,
+    "rows":[
+      {
+        "id":"test",
+        "key":"test",
+        "value":{"rev":"2-b91bb807b4685080c6a651115ff558f5"},
+        "doc":{
+          "_id":"test",
+          "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+          "hello":"bar"
+        }
+      }
+    ]
+  }
+
+.. code-block:: bash
+
+  $ curl 'http://127.0.0.1:5984/conflict_test/test?conflicts=true'
+
+.. code-block:: javascript
+
+  {
+    "_id":"test",
+    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
+    "hello":"bar",
+    "_conflicts":[
+      "2-65db2a11b5172bf928e3bcf59f728970",
+      "2-5bc3c6319edf62d4c624277fdd0ae191"
+    ]
+  }
+
+View map functions
+==================
+
+Views only get the winning revision of a document. However they do also get a
+``_conflicts`` member if there are any conflicting revisions. This means you can
+write a view whose job is specifically to locate documents with conflicts.
+Here is a simple map function which achieves this:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc._conflicts) {
+      emit(null, [doc._rev].concat(doc._conflicts));
+    }
+  }
+
+which gives the following output:
+
+.. code-block:: javascript
+
+  {
+    "total_rows":1,
+    "offset":0,
+    "rows":[
+      {
+        "id":"test",
+        "key":null,
+        "value":[
+          "2-b91bb807b4685080c6a651115ff558f5",
+          "2-65db2a11b5172bf928e3bcf59f728970",
+          "2-5bc3c6319edf62d4c624277fdd0ae191"
+        ]
+      }
+    ]
+  }
+
+If you do this, you can have a separate "sweep" process which periodically scans
+your database, looks for documents which have conflicts, fetches the conflicting
+revisions, and resolves them.
+
+Whilst this keeps the main application simple, the problem with this approach is
+that there will be a window between a conflict being introduced and it being
+resolved. From a user's viewpoint, this may appear that the document they just
+saved successfully may suddenly lose their changes, only to be resurrected some
+time later. This may or may not be acceptable.
+
+Also, it's easy to forget to start the sweeper, or not to implement it properly,
+and this will introduce odd behaviour which will be hard to track down.
+
+CouchDB's "winning" revision algorithm may mean that information drops out of a
+view until a conflict has been resolved. Consider Bob's business card again;
+suppose Alice has a view which emits mobile numbers, so that her telephony
+application can display the caller's name based on caller ID. If there are
+conflicting documents with Bob's old and new mobile numbers, and they happen to
+be resolved in favour of Bob's old number, then the view won't be able to
+recognise his new one. In this particular case, the application might have
+preferred to put information from both the conflicting documents into the view,
+but this currently isn't possible.
+
+Suggested algorithm to fetch a document with conflict resolution:
+
+#. Get document via ``GET docid?conflicts=true`` request;
+#. For each member in the ``_conflicts`` array call ``GET docid?rev=xxx``.
+   If any errors occur at this stage, restart from step 1.
+   (There could be a race where someone else has already resolved this conflict
+   and deleted that rev)
+#. Perform application-specific merging
+#. Write ``_bulk_docs`` with an update to the first rev and deletes of the other
+   revs.
+
+This could either be done on every read (in which case you could replace all
+calls to GET in your application with calls to a library which does the above),
+or as part of your sweeper code.
+
+And here is an example of this in Ruby using the low-level `RestClient`_:
+
+.. _RestClient: https://rubygems.org/gems/rest-client
+
+.. code-block:: ruby
+
+  require 'rubygems'
+  require 'rest_client'
+  require 'json'
+  DB="http://127.0.0.1:5984/conflict_test"
+
+  # Write multiple documents as all_or_nothing, can introduce conflicts
+  def writem(docs)
+    JSON.parse(RestClient.post("#{DB}/_bulk_docs", {
+      "all_or_nothing" => true,
+      "docs" => docs,
+    }.to_json))
+  end
+
+  # Write one document, return the rev
+  def write1(doc, id=nil, rev=nil)
+    doc['_id'] = id if id
+    doc['_rev'] = rev if rev
+    writem([doc]).first['rev']
+  end
+
+  # Read a document, return *all* revs
+  def read1(id)
+    retries = 0
+    loop do
+      # FIXME: escape id
+      res = [JSON.parse(RestClient.get("#{DB}/#{id}?conflicts=true"))]
+      if revs = res.first.delete('_conflicts')
+        begin
+          revs.each do |rev|
+            res << JSON.parse(RestClient.get("#{DB}/#{id}?rev=#{rev}"))
+          end
+        rescue
+          retries += 1
+          raise if retries >= 5
+          next
+        end
+      end
+      return res
+    end
+  end
+
+  # Create DB
+  RestClient.delete DB rescue nil
+  RestClient.put DB, {}.to_json
+
+  # Write a document
+  rev1 = write1({"hello"=>"xxx"},"test")
+  p read1("test")
+
+  # Make three conflicting versions
+  write1({"hello"=>"foo"},"test",rev1)
+  write1({"hello"=>"bar"},"test",rev1)
+  write1({"hello"=>"baz"},"test",rev1)
+
+  res = read1("test")
+  p res
+
+  # Now let's replace these three with one
+  res.first['hello'] = "foo+bar+baz"
+  res.each_with_index do |r,i|
+    unless i == 0
+      r.replace({'_id'=>r['_id'], '_rev'=>r['_rev'], '_deleted'=>true})
+    end
+  end
+  writem(res)
+
+  p read1("test")
+
+An application written this way never has to deal with a ``PUT 409``, and is
+automatically multi-master capable.
+
+You can see that it's straightforward enough when you know what you're doing.
+It's just that CouchDB doesn't currently provide a convenient HTTP API for
+"fetch all conflicting revisions", nor "PUT to supersede these N revisions", so
+you need to wrap these yourself. I also don't know of any client-side libraries
+which provide support for this.
+
+Merging and revision history
+============================
+
+Actually performing the merge is an application-specific function. It depends
+on the structure of your data. Sometimes it will be easy: e.g. if a document
+contains a list which is only ever appended to, then you can perform a union of
+the two list versions.
+
+Some merge strategies look at the changes made to an object, compared to its
+previous version. This is how git's merge function works.
+
+For example, to merge Bob's business card versions v2a and v2b, you could look
+at the differences between v1 and v2b, and then apply these changes to v2a as
+well.
+
+With CouchDB, you can sometimes get hold of old revisions of a document.
+For example, if you fetch ``/db/bob?rev=v2b&revs_info=true`` you'll get a list
+of the previous revision ids which ended up with revision v2b. Doing the same
+for v2a you can find their common ancestor revision. However if the database
+has been compacted, the content of that document revision will have been lost.
+``revs_info`` will still show that v1 was an ancestor, but report it as
+"missing"::
+
+  BEFORE COMPACTION           AFTER COMPACTION
+
+       ,-> v2a                     v2a
+     v1
+       `-> v2b                     v2b
+
+So if you want to work with diffs, the recommended way is to store those diffs
+within the new revision itself. That is: when you replace v1 with v2a, include
+an extra field or attachment in v2a which says which fields were changed from
+v1 to v2a. This unfortunately does mean additional book-keeping for your
+application.
+
+Comparison with other replicating data stores
+=============================================
+
+The same issues arise with other replicating systems, so it can be instructive
+to look at these and see how they compare with CouchDB. Please feel free to add
+other examples.
+
+Unison
+------
+
+`Unison`_ is a bi-directional file synchronisation tool. In this case, the
+business card would be a file, say `bob.vcf`.
+
+.. _Unison: http://www.cis.upenn.edu/~bcpierce/unison/
+
+When you run unison, changes propagate both ways. If a file has changed on one
+side but not the other, the new replaces the old. Unison maintains a local state
+file so that it knows whether a file has changed since the last successful
+replication.
+
+In our example it has changed on both sides. Only one file called `bob.vcf`
+can exist within the filesystem. Unison solves the problem by simply ducking
+out: the user can choose to replace the remote version with the local version,
+or vice versa (both of which would lose data), but the default action is to
+leave both sides unchanged.
+
+From Alice's point of view, at least this is a simple solution. Whenever she's
+on the desktop she'll see the version she last edited on the desktop, and
+whenever she's on the laptop she'll see the version she last edited there.
+
+But because no replication has actually taken place, the data is not protected.
+If her laptop hard drive dies, she'll lose all her changes made on the laptop;
+ditto if her desktop hard drive dies.
+
+It's up to her to copy across one of the versions manually (under a different
+filename), merge the two, and then finally push the merged version to the other
+side.
+
+Note also that the original file (version v1) has been lost by this point.
+So it's not going to be known from inspection alone which of v2a and v2b has the
+most up-to-date E-mail address for Bob, and which has the most up-to-date mobile
+number. Alice has to remember which she entered last.
+
+
+Git
+----
+
+`Git`_ is a well-known distributed source control system. Like Unison, git deals
+with files. However, git considers the state of a whole set of files as a single
+object, the "tree". Whenever you save an update, you create a "commit" which
+points to both the updated tree and the previous commit(s), which in turn point
+to the previous tree(s). You therefore have a full history of all the states of
+the files. This forms a branch, and a pointer is kept to the tip of the branch,
+from which you can work backwards to any previous state. The "pointer" is
+actually an SHA1 hash of the tip commit.
+
+.. _Git: http://git-scm.com/
+
+If you are replicating with one or more peers, a separate branch is made for
+each of the peers. For example, you might have::
+
+    master               -- my local branch
+    remotes/foo/master   -- branch on peer 'foo'
+    remotes/bar/master   -- branch on peer 'bar'
+
+In the normal way of working, replication is a "pull", importing changes from
+a remote peer into the local repository. A "pull" does two things: first "fetch"
+the state of the peer into the remote tracking branch for that peer; and then
+attempt to "merge" those changes into the local branch.
+
+Now let's consider the business card. Alice has created a git repo containing
+``bob.vcf``, and cloned it across to the other machine. The branches look like
+this, where ``AAAAAAAA`` is the SHA1 of the commit::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: AAAAAAAA                        master: AAAAAAAA
+  remotes/laptop/master: AAAAAAAA         remotes/desktop/master: AAAAAAAA
+
+Now she makes a change on the desktop, and commits it into the desktop repo;
+then she makes a different change on the laptop, and commits it into the laptop
+repo::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: BBBBBBBB                        master: CCCCCCCC
+  remotes/laptop/master: AAAAAAAA         remotes/desktop/master: AAAAAAAA
+
+Now on the desktop she does ``git pull laptop``. Firstly, the remote objects
+are copied across into the local repo and the remote tracking branch is
+updated::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: BBBBBBBB                        master: CCCCCCCC
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: AAAAAAAA
+
+.. note::
+  repo still contains AAAAAAAA because commits BBBBBBBB and CCCCCCCC point to it
+
+Then git will attempt to merge the changes in. It can do this because it knows
+the parent commit to ``CCCCCCCC`` is ``AAAAAAAA``, so it takes a diff between
+``AAAAAAAA`` and ``CCCCCCCC`` and tries to apply it to ``BBBBBBBB``.
+
+If this is successful, then you'll get a new version with a merge commit::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: DDDDDDDD                        master: CCCCCCCC
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: AAAAAAAA
+
+Then Alice has to logon to the laptop and run ``git pull desktop``. A similar
+process occurs. The remote tracking branch is updated::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: DDDDDDDD                        master: CCCCCCCC
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: DDDDDDDD
+
+Then a merge takes place. This is a special-case: ``CCCCCCCC`` one of the parent
+commits of ``DDDDDDDD``, so the laptop can `fast forward` update from
+``CCCCCCCC`` to ``DDDDDDDD`` directly without having to do any complex merging.
+This leaves the final state as::
+
+  ---------- desktop ----------           ---------- laptop ----------
+  master: DDDDDDDD                        master: DDDDDDDD
+  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: DDDDDDDD
+
+Now this is all and good, but you may wonder how this is relevant when thinking
+about CouchDB.
+
+Firstly, note what happens in the case when the merge algorithm fails.
+The changes are still propagated from the remote repo into the local one, and
+are available in the remote tracking branch; so unlike Unison, you know the data
+is protected. It's just that the local working copy may fail to update, or may
+diverge from the remote version. It's up to you to create and commit the
+combined version yourself, but you are guaranteed to have all the history you
+might need to do this.
+
+Note that whilst it's possible to build new merge algorithms into Git,
+the standard ones are focused on line-based changes to source code. They don't
+work well for XML or JSON if it's presented without any line breaks.
+
+The other interesting consideration is multiple peers. In this case you have
+multiple remote tracking branches, some of which may match your local branch,
+some of which may be behind you, and some of which may be ahead of you
+(i.e. contain changes that you haven't yet merged)::
+
+  master: AAAAAAAA
+  remotes/foo/master: BBBBBBBB
+  remotes/bar/master: CCCCCCCC
+  remotes/baz/master: AAAAAAAA
+
+Note that each peer is explicitly tracked, and therefore has to be explicitly
+created. If a peer becomes stale or is no longer needed, it's up to you to
+remove it from your configuration and delete the remote tracking branch.
+This is different to CouchDB, which doesn't keep any peer state in the database.
+
+Another difference with git is that it maintains all history back to time
+zero - git compaction keeps diffs between all those versions in order to reduce
+size, but CouchDB discards them. If you are constantly updating a document,
+the size of a git repo would grow forever. It is possible (with some effort)
+to use "history rewriting" to make git forget commits earlier than a particular
+one.
+
+
+What is the CouchDB replication protocol? Is it like Git?
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+**Key points**
+
+**If you know Git, then you know how Couch replication works.** Replicating is
+*very* similar to pushing or pulling with distributed source managers like Git.
+
+**CouchDB replication does not have its own protocol.** A replicator simply
+connects to two DBs as a client, then reads from one and writes to the other.
+Push replication is reading the local data and updating the remote DB;
+pull replication is vice versa.
+
+* **Fun fact 1**: The replicator is actually an independent Erlang application,
+  in its own process. It connects to both couches, then reads records from one
+  and writes them to the other.
+* **Fun fact 2**: CouchDB has no way of knowing who is a normal client and who
+  is a replicator (let alone whether the replication is push or pull).
+  It all looks like client connections. Some of them read records. Some of them
+  write records.
+
+**Everything flows from the data model**
+
+The replication algorithm is trivial, uninteresting. A trained monkey could
+design it. It's simple because the cleverness is the data model, which has these
+useful characteristics:
+
+#. Every record in CouchDB is completely independent of all others. That sucks
+   if you want to do a JOIN or a transaction, but it's awesome if you want to
+   write a replicator. Just figure out how to replicate one record, and then
+   repeat that for each record.
+#. Like Git, records have a linked-list revision history. A record's revision ID
+   is the checksum of its own data. Subsequent revision IDs are checksums of:
+   the new data, plus the revision ID of the previous.
+
+#. In addition to application data (``{"name": "Jason", "awesome": true}``),
+   every record stores the evolutionary timeline of all previous revision IDs
+   leading up to itself.
+
+   - Exercise: Take a moment of quiet reflection. Consider any two different
+     records, A and B. If A's revision ID appears in B's timeline, then B
+     definitely evolved from A. Now consider Git's fast-forward merges.
+     Do you hear that? That is the sound of your mind being blown.
+
+#. Git isn't really a linear list. It has forks, when one parent has multiple
+   children. CouchDB has that too.
+
+   - Exercise: Compare two different records, A and B. A's revision ID does not
+     appear in B's timeline; however, one revision ID, C, is in both A's and B's
+     timeline. Thus A didn't evolve from B. B didn't evolve from A. But rather,
+     A and B have a common ancestor C. In Git, that is a "fork." In CouchDB,
+     it's a "conflict."
+
+   - In Git, if both children go on to develop their timelines independently,
+     that's cool. Forks totally support that.
+   - In CouchDB, if both children go on to develop their timelines
+     independently, that cool too. Conflicts totally support that.
+   - **Fun fact 3**: CouchDB "conflicts" do not correspond to Git "conflicts."
+     A Couch conflict is a divergent revision history, what Git calls a "fork."
+     For this reason the CouchDB community pronounces "conflict" with a silent
+     `n`: "co-flicked."
+
+#. Git also has merges, when one child has multiple parents. CouchDB *sort* of
+   has that too.
+
+   - **In the data model, there is no merge.** The client simply marks one
+     timeline as deleted and continues to work with the only extant timeline.
+   - **In the application, it feels like a merge.** Typically, the client merges
+     the *data* from each timeline in an application-specific way.
+     Then it writes the new data to the timeline. In Git, this is like copying
+     and pasting the changes from branch A into branch B, then commiting to
+     branch B and deleting branch A. The data was merged, but there was no
+     `git merge`.
+   - These behaviors are different because, in Git, the timeline itself is
+     important; but in CouchDB, the data is important and the timeline is
+     incidental—it's just there to support replication. That is one reason why
+     CouchDB's built-in revisioning is inappropriate for storing revision data
+     like a wiki page.
+
+**Final notes**
+
+At least one sentence in this writeup (possibly this one) is complete BS.
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replication/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication/index.rst b/share/doc/src/replication/index.rst
new file mode 100644
index 0000000..1dec453
--- /dev/null
+++ b/share/doc/src/replication/index.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.
+
+.. _replication:
+
+================
+Data Replication
+================
+
+The replication is an incremental one way process involving two databases
+(a source and a destination).
+
+The aim of the replication is that at the end of the process, all active
+documents on the source database are also in the destination database and all
+documents that were deleted in the source databases are also deleted (if exists)
+on the destination database.
+
+The replication process only copies the last revision of a document, so all
+previous revisions that were only on the source database are not copied to the
+destination database.
+
+.. toctree::
+   :maxdepth: 2
+
+   intro
+   replicator
+   conflicts
+   protocol

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replication/intro.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication/intro.rst b/share/doc/src/replication/intro.rst
new file mode 100644
index 0000000..f9c81e2
--- /dev/null
+++ b/share/doc/src/replication/intro.rst
@@ -0,0 +1,95 @@
+.. 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.
+
+.. _replication/intro:
+
+Introduction Into Replications
+==============================
+
+One of CouchDB's strengths is the ability to synchronize two copies of the same
+database. This enables users to distribute data across several nodes or
+datacenters, but also to move data more closely to clients.
+
+Replication involves a source and a destination database, which can be one the
+same or on different CouchDB instances. The aim of the replication is that at
+the end of the process, all active documents on the source database are also in
+the destination database and all documents that were deleted in the source
+databases are also deleted on the destination database (if they even existed).
+
+
+Triggering Replication
+----------------------
+
+Replication is controlled through documents in the :ref:`replicator`, where
+each document describes one replication process (see
+:ref:`replication-settings`).
+
+A replication is triggered by storing a replication document in the replicator
+database. Its status can be inspected through the active tasks API (see
+:ref:`api/misc/active_tasks` and :ref:`replication-status`). A replication can be
+stopped by deleting the document, or by updating it with its `cancel` property
+set to `true`.
+
+
+Replication Procedure
+---------------------
+
+During replication, CouchDB will compare the source and the destination
+database to determine which documents differ between the source and the
+destination database. It does so by following the :ref:`changes` on the source
+and comparing the documents to the destination. Changes are submitted to the
+destination in batches where they can introduce conflicts. Documents that
+already exist on the destination in the same revision are not transferred. As
+the deletion of documents is represented by a new revision, a document deleted
+on the source will also be deleted on the target.
+
+A replication task will finish once it reaches the end of the changes feed. If
+its `continuous` property is set to true, it will wait for new changes to
+appear until the task is cancelled. Replication tasks also create checkpoint
+documents on the destination to ensure that a restarted task can continue from
+where it stopped, for example after it has crashed.
+
+When a replication task is initiated on the sending node, it is called *push*
+replication, if it is initiated by the receiving node, it is called *pull*
+replication.
+
+
+Master - Master replication
+---------------------------
+
+One replication task will only transfer changes in one direction. To achieve
+master-master replication it is possible to set up two replication tasks in
+different directions. When a change is replication from database A to B by the
+first task, the second will discover that the new change on B already exists in
+A and will wait for further changes.
+
+
+Controlling which Documents to Replicate
+----------------------------------------
+
+There are two ways for controlling which documents are replicated, and which
+are skipped. *Local* documents are never replicated (see :ref:`api/local`).
+
+Additionally, :ref:`filterfun` can be used in a replication documents (see
+:ref:`replication-settings`). The replication task will then evaluate
+the filter function for each document in the changes feed. The document will
+only be replicated if the filter returns `true`.
+
+
+Migrating Data to Clients
+-------------------------
+
+Replication can be especially useful for bringing data closer to clients.
+`PouchDB <http://pouchdb.com/>`_ implements the replication algorithm of CouchDB
+in JavaScript, making it possible to make data from a CouchDB database
+available in an offline browser application, and synchronize changes back to
+CouchDB.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replication/protocol.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication/protocol.rst b/share/doc/src/replication/protocol.rst
new file mode 100644
index 0000000..bf478f7
--- /dev/null
+++ b/share/doc/src/replication/protocol.rst
@@ -0,0 +1,201 @@
+.. 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.
+
+.. _replication/protocol:
+
+============================
+CouchDB Replication Protocol
+============================
+
+The **CouchDB Replication protocol** is a protocol for synchronizing
+documents between 2 peers over HTTP/1.1.
+
+Language
+--------
+
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+document are to be interpreted as described in :rfc:`2119`.
+
+
+Goals
+-----
+
+The CouchDB Replication protocol is a synchronization protocol for
+synchronizing documents between 2 peers over HTTP/1.1.
+
+In theory the CouchDB protocol can be used between products that
+implement it. However the reference implementation, written in Erlang_, is
+provided by the couch_replicator_ module available in Apache CouchDB.
+
+
+The CouchDB_ replication protocol is using the `CouchDB REST API
+<http://wiki.apache.org/couchdb/Reference>`_ and so is based on HTTP and
+the Apache CouchDB MVC Data model. The primary goal of this
+specification is to describe the CouchDB replication algorithm.
+
+
+Definitions
+-----------
+
+ID:
+    An identifier (could be an UUID) as described in :rfc:`4122`
+
+Sequence:
+    An ID provided by the changes feed. It can be numeric but not
+    necessarily.
+
+Revision:
+    (to define)
+
+Document
+    A document is JSON entity with a unique ID and revision.
+
+Database
+    A collection of documents with a unique URI
+
+URI
+    An uri is defined by the :rfc:`2396` . It can be an URL as defined
+    in :rfc:`1738`.
+
+Source
+    Database from where the Documents are replicated
+
+Target
+    Database where the Document are replicated
+
+Checkpoint
+    Last source sequence ID
+
+
+Algorithm
+---------
+
+1. Get unique identifiers for the Source and Target based on their URI if
+   replication task ID is not available.
+
+2. Save this identifier in a special Document named `_local/<uniqueid>`
+   on the Target database. This document isn't replicated. It will
+   collect the last Source sequence ID, the Checkpoint, from the
+   previous replication process.
+
+3. Get the Source changes feed by passing it the Checkpoint using the
+   `since` parameter by calling the `/<source>/_changes` URL. The
+   changes feed only return a list of current revisions.
+
+
+.. note::
+
+    This step can be done continuously using the `feed=longpoll` or
+    `feed=continuous` parameters. Then the feed will continuously get
+    the changes.
+
+
+4. Collect a group of Document/Revisions ID pairs from the **changes
+   feed** and send them to the target databases on the
+   `/<target>/_revs_diffs` URL. The result will contain the list of
+   revisions **NOT** in the Target.
+
+5. GET each revisions from the source Database by calling the URL
+   `/<source>/<docid>?revs=true&open_revs`=<revision>` . This
+   will get the document with teh parent revisions. Also don't forget to
+   get attachments that aren't already stored at the target. As an
+   optimisation you can use the HTTP multipart api to get all.
+
+6. Collect a group of revisions fetched at previous step and store them
+   on the target database using the `Bulk Docs
+   <http://wiki.apache.org/couchdb/HTTP_Document_API#Bulk_Docs>`_ API
+   with the `new_edit: false` JSON property to preserve their revisions
+   ID.
+
+7. After the group of revision is stored on the Target, save
+   the new Checkpoint on the Source.
+
+
+.. note::
+
+    - Even if some revisions have been ignored the sequence should be
+      take in consideration for the Checkpoint.
+
+    - To compare non numeric sequence ordering, you will have to keep an
+      ordered list of the sequences IDS as they appear in the _changes
+      feed and compare their indices.
+
+Filter replication
+------------------
+
+The replication can be filtered by passing the `filter` parameter to the
+changes feeds with a function name. This will call a function on each
+changes. If this function return True, the document will be added to the
+feed.
+
+
+Optimisations
+-------------
+
+- The system should run each steps in parallel to reduce the latency.
+
+- The number of revisions passed to the step 3 and 6 should be large
+  enough to reduce the bandwidth and make sure to reduce the latency.
+
+
+API Reference
+-------------
+
+- :ref:`api/db.head` -- Check Database existence
+- :ref:`api/db/ensure_full_commit` -- Ensure that all changes are stored on disk
+- :ref:`api/local/doc.get` -- Read the last Checkpoint
+- :ref:`api/local/doc.put` -- Save a new Checkpoint
+
+Push Only
+~~~~~~~~~
+
+- :ref:`api/db.put` -- Create Target if it not exists and option was provided
+- :ref:`api/db/revs_diff.post` -- Locate Revisions that are not known to the
+  Target
+- :ref:`api/db/bulk_docs.post` -- Upload Revisions to the Target
+- :ref:`api/doc.put`?new_edits=false -- Upload a single Document with
+  attachments to the Target
+
+Pull Only
+~~~~~~~~~
+
+- :ref:`api/db/changes.get` -- Locate changes since on Source the last pull.
+  The request uses next query parameters:
+
+  - ``style=all_docs``
+  - ``feed=feed`` , where feed is :ref:`normal <changes/normal>` or
+    :ref:`longpoll <changes/longpoll>`
+  - ``limit=limit``
+  - ``heartbeat=heartbeat``
+
+- :ref:`api/doc.get` -- Retrieve a single Document from Source with attachments.
+  The request uses next query parameters:
+
+  - ``open_revs=revid`` - where ``revid`` is the actual Document Revision at the
+    moment of the pull request
+  - ``revs=true``
+  - ``atts_since=lastrev``
+
+Reference
+---------
+
+* `TouchDB Ios wiki <https://github.com/couchbaselabs/TouchDB-iOS/wiki/Replication-Algorithm>`_
+* `CouchDB documentation
+  <http://wiki.apache.org/couchdb/Replication>`_
+* CouchDB `change notifications`_
+
+.. _CouchDB: http://couchdb.apache.org
+.. _Erlang: http://erlang.org
+.. _couch_replicator: https://github.com/apache/couchdb/tree/master/src/couch_replicator
+.. _change notifications: http://guide.couchdb.org/draft/notifications.html
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replication/replicator.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replication/replicator.rst b/share/doc/src/replication/replicator.rst
new file mode 100644
index 0000000..1a40c65
--- /dev/null
+++ b/share/doc/src/replication/replicator.rst
@@ -0,0 +1,383 @@
+.. 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.
+
+.. _replicator:
+
+Replicator Database
+===================
+
+A database where you ``PUT``/``POST`` documents to trigger replications
+and you ``DELETE`` to cancel ongoing replications. These documents have
+exactly the same content as the JSON objects we used to ``POST`` to
+``_replicate`` (fields ``source``, ``target``, ``create_target``,
+``continuous``, ``doc_ids``, ``filter``, ``query_params``.
+
+Replication documents can have a user defined ``_id``. Design documents
+(and ``_local`` documents) added to the replicator database are ignored.
+
+The default name of this database is ``_replicator``. The name can be
+changed in the ``local.ini`` configuration, section ``[replicator]``,
+parameter ``db``.
+
+Basics
+------
+
+Let's say you PUT the following document into ``_replicator``:
+
+.. code-block:: javascript
+
+    {
+        "_id": "my_rep",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "create_target":  true
+    }
+
+In the couch log you'll see 2 entries like these:
+
+.. code-block:: text
+
+    [Thu, 17 Feb 2011 19:43:59 GMT] [info] [<0.291.0>] Document `my_rep` triggered replication `c0ebe9256695ff083347cbf95f93e280+create_target`
+    [Thu, 17 Feb 2011 19:44:37 GMT] [info] [<0.124.0>] Replication `c0ebe9256695ff083347cbf95f93e280+create_target` finished (triggered by document `my_rep`)
+
+As soon as the replication is triggered, the document will be updated by
+CouchDB with 3 new fields:
+
+.. code-block:: javascript
+
+    {
+        "_id": "my_rep",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "create_target":  true,
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297974122
+    }
+
+Special fields set by the replicator start with the prefix
+``_replication_``.
+
+-  ``_replication_id``
+
+   The ID internally assigned to the replication. This is also the ID
+   exposed by ``/_active_tasks``.
+
+-  ``_replication_state``
+
+   The current state of the replication.
+
+-  ``_replication_state_time``
+
+   A Unix timestamp (number of seconds since 1 Jan 1970) that tells us
+   when the current replication state (marked in ``_replication_state``)
+   was set.
+
+When the replication finishes, it will update the ``_replication_state``
+field (and ``_replication_state_time``) with the value ``completed``, so
+the document will look like:
+
+.. code-block:: javascript
+
+    {
+        "_id": "my_rep",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "create_target":  true,
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "completed",
+        "_replication_state_time":  1297974122
+    }
+
+When an error happens during replication, the ``_replication_state``
+field is set to ``error`` (and ``_replication_state_time`` gets updated of
+course).
+
+When you PUT/POST a document to the ``_replicator`` database, CouchDB
+will attempt to start the replication up to 10 times (configurable under
+``[replicator]``, parameter ``max_replication_retry_count``). If it
+fails on the first attempt, it waits 5 seconds before doing a second
+attempt. If the second attempt fails, it waits 10 seconds before doing a
+third attempt. If the third attempt fails, it waits 20 seconds before
+doing a fourth attempt (each attempt doubles the previous wait period).
+When an attempt fails, the Couch log will show you something like:
+
+.. code-block:: text
+
+    [error] [<0.149.0>] Error starting replication `67c1bb92010e7abe35d7d629635f18b6+create_target` (document `my_rep_2`): {db_not_found,<<"could not open http://myserver:5986/foo/">>
+
+.. note::
+   The ``_replication_state`` field is only set to ``error`` when all
+   the attempts were unsuccessful.
+
+There are only 3 possible values for the ``_replication_state`` field:
+``triggered``, ``completed`` and ``error``. Continuous replications
+never get their state set to ``completed``.
+
+Documents describing the same replication
+-----------------------------------------
+
+Lets suppose 2 documents are added to the ``_replicator`` database in
+the following order:
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_A",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar"
+    }
+
+and
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_B",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar"
+    }
+
+Both describe exactly the same replication (only their ``_ids`` differ).
+In this case document ``doc_A`` triggers the replication, getting
+updated by CouchDB with the fields ``_replication_state``,
+``_replication_state_time`` and ``_replication_id``, just like it was
+described before. Document ``doc_B`` however, is only updated with one
+field, the ``_replication_id`` so it will look like this:
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_B",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280"
+    }
+
+While document ``doc_A`` will look like this:
+
+.. code-block:: javascript
+
+    {
+        "_id": "doc_A",
+        "source":  "http://myserver.com:5984/foo",
+        "target":  "bar",
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297974122
+    }
+
+Note that both document get exactly the same value for the
+``_replication_id`` field. This way you can identify which documents
+refer to the same replication - you can for example define a view which
+maps replication IDs to document IDs.
+
+Canceling replications
+----------------------
+
+To cancel a replication simply ``DELETE`` the document which triggered
+the replication. The Couch log will show you an entry like the
+following:
+
+.. code-block:: text
+
+    [Thu, 17 Feb 2011 20:16:29 GMT] [info] [<0.125.0>] Stopped replication `c0ebe9256695ff083347cbf95f93e280+continuous+create_target` because replication document `doc_A` was deleted
+
+.. note::
+   You need to ``DELETE`` the document that triggered the replication.
+   ``DELETE``-ing another document that describes the same replication
+   but did not trigger it, will not cancel the replication.
+
+Server restart
+--------------
+
+When CouchDB is restarted, it checks its ``_replicator`` database and
+restarts any replication that is described by a document that either has
+its ``_replication_state`` field set to ``triggered`` or it doesn't have
+yet the ``_replication_state`` field set.
+
+.. note::
+   Continuous replications always have a ``_replication_state`` field
+   with the value ``triggered``, therefore they're always restarted
+   when CouchDB is restarted.
+
+Changing the Replicator Database
+--------------------------------
+
+Imagine your replicator database (default name is ``_replicator``) has the
+two following documents that represent pull replications from servers A
+and B:
+
+.. code-block:: javascript
+
+    {
+        "_id": "rep_from_A",
+        "source":  "http://aserver.com:5984/foo",
+        "target":  "foo_a",
+        "continuous":  true,
+        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297971311
+    }
+
+.. code-block:: javascript
+
+    {
+        "_id": "rep_from_B",
+        "source":  "http://bserver.com:5984/foo",
+        "target":  "foo_b",
+        "continuous":  true,
+        "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
+        "_replication_state":  "triggered",
+        "_replication_state_time":  1297974122
+    }
+
+Now without stopping and restarting CouchDB, you change the name of the
+replicator database to ``another_replicator_db``:
+
+.. code-block:: bash
+
+    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"another_replicator_db"'
+    "_replicator"
+
+As soon as this is done, both pull replications defined before, are
+stopped. This is explicitly mentioned in CouchDB's log:
+
+.. code-block:: text
+
+    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.104.0>] Stopping all ongoing replications because the replicator database was deleted or changed
+    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.127.0>] 127.0.0.1 - - PUT /_config/replicator/db 200
+
+Imagine now you add a replication document to the new replicator
+database named ``another_replicator_db``:
+
+.. code-block:: javascript
+
+    {
+        "_id": "rep_from_X",
+        "source":  "http://xserver.com:5984/foo",
+        "target":  "foo_x",
+        "continuous":  true
+    }
+
+From now own you have a single replication going on in your system: a
+pull replication pulling from server X. Now you change back the
+replicator database to the original one ``_replicator``:
+
+::
+
+    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"_replicator"'
+    "another_replicator_db"
+
+Immediately after this operation, the replication pulling from server X
+will be stopped and the replications defined in the ``_replicator``
+database (pulling from servers A and B) will be resumed.
+
+Changing again the replicator database to ``another_replicator_db`` will
+stop the pull replications pulling from servers A and B, and resume the
+pull replication pulling from server X.
+
+Replicating the replicator database
+-----------------------------------
+
+Imagine you have in server C a replicator database with the two
+following pull replication documents in it:
+
+.. code-block:: javascript
+
+    {
+         "_id": "rep_from_A",
+         "source":  "http://aserver.com:5984/foo",
+         "target":  "foo_a",
+         "continuous":  true,
+         "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
+         "_replication_state":  "triggered",
+         "_replication_state_time":  1297971311
+    }
+
+.. code-block:: javascript
+
+    {
+         "_id": "rep_from_B",
+         "source":  "http://bserver.com:5984/foo",
+         "target":  "foo_b",
+         "continuous":  true,
+         "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
+         "_replication_state":  "triggered",
+         "_replication_state_time":  1297974122
+    }
+
+Now you would like to have the same pull replications going on in server
+D, that is, you would like to have server D pull replicating from
+servers A and B. You have two options:
+
+-  Explicitly add two documents to server's D replicator database
+
+-  Replicate server's C replicator database into server's D replicator
+   database
+
+Both alternatives accomplish exactly the same goal.
+
+Delegations
+-----------
+
+Replication documents can have a custom ``user_ctx`` property. This
+property defines the user context under which a replication runs. For
+the old way of triggering replications (POSTing to ``/_replicate/``),
+this property was not needed (it didn't exist in fact) - this is because
+at the moment of triggering the replication it has information about the
+authenticated user. With the replicator database, since it's a regular
+database, the information about the authenticated user is only present
+at the moment the replication document is written to the database - the
+replicator database implementation is like a ``_changes`` feed consumer
+(with ``?include_docs=true``) that reacts to what was written to the
+replicator database - in fact this feature could be implemented with an
+external script/program. This implementation detail implies that for non
+admin users, a ``user_ctx`` property, containing the user's name and a
+subset of his/her roles, must be defined in the replication document.
+This is ensured by the document update validation function present in
+the default design document of the replicator database. This validation
+function also ensure that a non admin user can set a user name property
+in the ``user_ctx`` property that doesn't match his/her own name (same
+principle applies for the roles).
+
+For admins, the ``user_ctx`` property is optional, and if it's missing
+it defaults to a user context with name null and an empty list of roles
+- this mean design documents will not be written to local targets. If
+writing design documents to local targets is desired, the a user context
+with the roles ``_admin`` must be set explicitly.
+
+Also, for admins the ``user_ctx`` property can be used to trigger a
+replication on behalf of another user. This is the user context that
+will be passed to local target database document validation functions.
+
+.. note::
+   The ``user_ctx`` property only has effect for local endpoints.
+
+Example delegated replication document:
+
+.. code-block:: javascript
+
+    {
+         "_id": "my_rep",
+         "source":  "http://bserver.com:5984/foo",
+         "target":  "bar",
+         "continuous":  true,
+         "user_ctx": {
+              "name": "joe",
+              "roles": ["erlanger", "researcher"]
+         }
+    }
+
+As stated before, for admins the ``user_ctx`` property is optional, while
+for regular (non admin) users it's mandatory. When the roles property of
+``user_ctx`` is missing, it defaults to the empty list ``[ ]``.


[22/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add eventsource feed type to API. Set back references.

COUCHDB-1857


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/351e91af
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/351e91af
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/351e91af

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 351e91afd5fb994cb96d6cc794ab7170452a9797
Parents: d159201
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 03:18:36 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/database.rst | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/351e91af/share/doc/src/api/database.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database.rst b/share/doc/src/api/database.rst
index ae85948..188a9f7 100644
--- a/share/doc/src/api/database.rst
+++ b/share/doc/src/api/database.rst
@@ -283,15 +283,16 @@ If successful, the returned JSON will indicate success
 
   * **Argument**: feed
 
-    * **Description**:  Type of feed
+    * **Description**: Type of the :ref:`changes <changes>` feed
     * **Optional**: yes
     * **Type**: string
     * **Default**: normal
     * **Supported Values**:
 
-      * **continuous**: Continuous (non-polling) mode
-      * **longpoll**: Long polling mode
-      * **normal**: Normal mode
+      * **continuous**: :ref:`Continuous <changes/continuous>` mode
+      * **eventsource**: :ref:`Event source <changes/eventsource>` mode
+      * **longpoll**: :ref:`Long polling <changes/longpoll>` mode
+      * **normal**: :ref:`Normal <changes/normal>` mode
 
   * **Argument**: filter
 


[21/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Add references to changes feed sections.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/d1592019
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/d1592019
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/d1592019

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: d1592019f9d8cacc0ce3f64bb669f8222e775b9b
Parents: 9af2b44
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 03:16:22 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/changes.rst | 11 +++++++++++
 1 file changed, 11 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/d1592019/share/doc/src/changes.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/changes.rst b/share/doc/src/changes.rst
index cfec5cd..9ec747e 100644
--- a/share/doc/src/changes.rst
+++ b/share/doc/src/changes.rst
@@ -16,6 +16,8 @@
 Changes Feed
 ============
 
+.. _changes/normal:
+
 Polling
 =======
 
@@ -135,6 +137,9 @@ including the given sequence number::
     ],
     "last_seq":5} 
 
+
+.. _changes/longpoll:
+
 Long Polling
 ============
 
@@ -149,6 +154,9 @@ A timeout limits the maximum length of time the connection is open. If there
 are no changes before the timeout expires the response's results will be an
 empty list.  
 
+
+.. _changes/continuous:
+
 Continuous
 ==========
 
@@ -182,6 +190,9 @@ represents a long pause before the change with seq 6 occurred.  
 
 .. _section in the book: http://books.couchdb.org/relax/reference/change-notifications
 
+
+.. _changes/eventsource:
+
 Event Source
 ============
 


[45/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Import views article from Guide to CouchDB as introduction to views.

http://guide.couchdb.org/draft/views.html

COUCHDB-1539


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/1931add7
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/1931add7
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/1931add7

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 1931add7b3dfb783092cd99a04548b41f3492fb2
Parents: 0ece2b6
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 14:17:26 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 14:17:26 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am            |  12 +-
 share/doc/images/views-intro-01.png    | Bin 0 -> 1026767 bytes
 share/doc/images/views-intro-02.png    | Bin 0 -> 9758 bytes
 share/doc/images/views-intro-03.png    | Bin 0 -> 12650 bytes
 share/doc/images/views-intro-04.png    | Bin 0 -> 14537 bytes
 share/doc/src/couchapp/index.rst       |   1 +
 share/doc/src/couchapp/views/index.rst |  26 ++
 share/doc/src/couchapp/views/intro.rst | 675 ++++++++++++++++++++++++++++
 8 files changed, 713 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 6583682..7cb1625 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -45,6 +45,10 @@ html_files = \
     html/_images/futon-editeddoc.png \
     html/_images/futon-overview.png \
     html/_images/futon-replform.png \
+    html/_images/views-intro-01.png \
+    html/_images/views-intro-02.png \
+    html/_images/views-intro-03.png \
+    html/_images/views-intro-04.png \
     html/_sources/api/basics.txt \
     html/_sources/api/index.txt \
     html/_sources/api/local.txt \
@@ -85,6 +89,8 @@ html_files = \
     html/_sources/config/proxying.txt \
     html/_sources/couchapp/ddocs.txt \
     html/_sources/couchapp/index.txt \
+    html/_sources/couchapp/views/index.txt \
+    html/_sources/couchapp/views/intro.txt \
     html/_sources/fauxton/addons.txt \
     html/_sources/fauxton/index.txt \
     html/_sources/fauxton/install.txt \
@@ -170,7 +176,9 @@ html_files = \
     html/config/intro.html \
     html/config/proxying.html \
     html/couchapp/ddocs.html \
-    html/couchapp/intdex.html \
+    html/couchapp/index.html \
+    html/couchapp/views/index.html \
+    html/couchapp/views/intro.html \
     html/fauxton/addons.html \
     html/fauxton/index.html \
     html/fauxton/install.html \
@@ -255,6 +263,8 @@ src_files = \
     ../src/config/proxying.rst \
     ../src/couchapp/ddocs.rst \
     ../src/couchapp/index.rst \
+    ../src/couchapp/views/index.rst \
+    ../src/couchapp/views/intro.rst \
     ../src/fauxton/addons.rst \
     ../src/fauxton/index.rst \
     ../src/fauxton/install.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/images/views-intro-01.png
----------------------------------------------------------------------
diff --git a/share/doc/images/views-intro-01.png b/share/doc/images/views-intro-01.png
new file mode 100644
index 0000000..b102d5e
Binary files /dev/null and b/share/doc/images/views-intro-01.png differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/images/views-intro-02.png
----------------------------------------------------------------------
diff --git a/share/doc/images/views-intro-02.png b/share/doc/images/views-intro-02.png
new file mode 100644
index 0000000..4e9f3dc
Binary files /dev/null and b/share/doc/images/views-intro-02.png differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/images/views-intro-03.png
----------------------------------------------------------------------
diff --git a/share/doc/images/views-intro-03.png b/share/doc/images/views-intro-03.png
new file mode 100644
index 0000000..83929ee
Binary files /dev/null and b/share/doc/images/views-intro-03.png differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/images/views-intro-04.png
----------------------------------------------------------------------
diff --git a/share/doc/images/views-intro-04.png b/share/doc/images/views-intro-04.png
new file mode 100644
index 0000000..51e3de8
Binary files /dev/null and b/share/doc/images/views-intro-04.png differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/src/couchapp/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/index.rst b/share/doc/src/couchapp/index.rst
index 8df4d91..d01b91e 100644
--- a/share/doc/src/couchapp/index.rst
+++ b/share/doc/src/couchapp/index.rst
@@ -25,4 +25,5 @@ your app is as simple as replicating it to the production server).
    :maxdepth: 2
 
    ddocs
+   views/index
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/src/couchapp/views/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/index.rst b/share/doc/src/couchapp/views/index.rst
new file mode 100644
index 0000000..0979a49
--- /dev/null
+++ b/share/doc/src/couchapp/views/index.rst
@@ -0,0 +1,26 @@
+.. 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.
+
+
+.. _views:
+
+==============
+Guide to Views
+==============
+
+Views are the primary tool used for querying and reporting on CouchDB documents.
+There you'll learn how they works and how to use them to build effective
+applications with CouchDB
+
+.. toctree::
+
+  intro

http://git-wip-us.apache.org/repos/asf/couchdb/blob/1931add7/share/doc/src/couchapp/views/intro.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/intro.rst b/share/doc/src/couchapp/views/intro.rst
new file mode 100644
index 0000000..5e1dab4
--- /dev/null
+++ b/share/doc/src/couchapp/views/intro.rst
@@ -0,0 +1,675 @@
+.. 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.
+
+
+.. _views/intro:
+
+===========================
+Introduction Into The Views
+===========================
+
+Views are useful for many purposes:
+
+- Filtering the documents in your database to find those relevant to a
+  particular process.
+- Extracting data from your documents and presenting it in a specific order.
+- Building efficient indexes to find documents by any value or structure that
+  resides in them.
+- Use these indexes to represent relationships among documents.
+- Finally, with views you can make all sorts of calculations on the data in your
+  documents. For example, if documents represent your company’s financial
+  transactions, a view can answer the question of what the spending was in the
+  last week, month, or year.
+
+What Is a View?
+===============
+
+Let’s go through the different use cases. First is extracting data that you
+might need for a special purpose in a specific order. For a front page, we want
+a list of blog post titles sorted by date. We’ll work with a set of example
+documents as we walk through how views work:
+
+.. code-block:: javascript
+
+  {
+    "_id":"biking",
+    "_rev":"AE19EBC7654",
+
+    "title":"Biking",
+    "body":"My biggest hobby is mountainbiking. The other day...",
+    "date":"2009/01/30 18:04:11"
+  }
+
+.. code-block:: javascript
+
+  {
+    "_id":"bought-a-cat",
+    "_rev":"4A3BBEE711",
+
+    "title":"Bought a Cat",
+    "body":"I went to the the pet store earlier and brought home a little kitty...",
+    "date":"2009/02/17 21:13:39"
+  }
+
+.. code-block:: javascript
+
+  {
+    "_id":"hello-world",
+    "_rev":"43FBA4E7AB",
+
+    "title":"Hello World",
+    "body":"Well hello and welcome to my new blog...",
+    "date":"2009/01/15 15:52:20"
+  }
+
+Three will do for the example. Note that the documents are sorted by "_id",
+which is how they are stored in the database. Now we define a view.
+Bear with us without an explanation while we show you some code:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc.date && doc.title) {
+      emit(doc.date, doc.title);
+    }
+  }
+
+This is a `map function`, and it is written in JavaScript. If you are not
+familiar with JavaScript but have used C or any other C-like language such as
+Java, PHP, or C#, this should look familiar. It is a simple function definition.
+
+You provide CouchDB with view functions as strings stored inside the ``views``
+field of a design document. You don’t run it yourself. Instead, when you
+`query your view`, CouchDB takes the source code and runs it for you on every
+document in the database your view was defined in. You `query your view` to
+retrieve the `view result`.
+
+All map functions have a single parameter doc. This is a single document in
+the database. Our map function checks whether our document has a ``date`` and
+a ``title`` attribute — luckily, all of our documents have them — and then calls
+the built-in :js:func:`emit` function with these two attributes as arguments.
+
+The :js:func:`emit` function always takes two arguments: the first is ``key``,
+and the second is ``value``. The ``emit(key, value)`` function creates an entry
+in our `view result`. One more thing: the ``emit()`` function can be called
+multiple times in the map function to create multiple entries in the view
+results from a single document, but we are not doing that yet.
+
+CouchDB takes whatever you pass into the emit() function and puts it into a list
+(see Table 1, “View results” below). Each row in that list includes the `key`
+and `value`. More importantly, the list is sorted by key (by ``doc.date``
+in our case).  The most important feature of a view result is that it is sorted
+by `key`. We will come back to that over and over again to do neat things. Stay
+tuned.
+
+Table 1. View results:
+
++-----------------------+------------------+
+|         Key           |      Value       |
++=======================+==================+
+| "2009/01/15 15:52:20" | "Hello World"    |
++-----------------------+------------------+
+| "2009/01/30 18:04:11" | "Biking"         |
++-----------------------+------------------+
+| "2009/02/17 21:13:39" | "Bought a Cat"   |
++-----------------------+------------------+
+
+
+When you query your view, CouchDB takes the source code and runs it for you on
+every document in the database. If you have a lot of documents, that takes
+quite a bit of time and you might wonder if it is not horribly inefficient
+to do this. Yes, it would be, but CouchDB is designed to avoid any extra costs:
+it only runs through all documents once, when you first query your view.
+If a document is changed, the map function is only run once, to recompute
+the keys and values for that single document.
+
+The view result is stored in a B-tree, just like the structure that is
+responsible for holding your documents. View B-trees are stored in their
+own file, so that for high-performance CouchDB usage, you can keep views on
+their own disk. The B-tree provides very fast lookups of rows by key, as well
+as efficient streaming of rows in a key range. In our example, a single view
+can answer all questions that involve time: “Give me all the blog posts from
+last week” or “last month” or “this year.” Pretty neat.
+
+When we query our view, we get back a list of all documents sorted by date.
+Each row also includes the post title so we can construct links to posts.
+Table 1 is just a graphical representation of the view result.
+The actual result is JSON-encoded and contains a little more metadata:
+
+.. code-block:: javascript
+
+  {
+    "total_rows": 3,
+    "offset": 0,
+    "rows": [
+      {
+        "key": "2009/01/15 15:52:20",
+        "id": "hello-world",
+        "value": "Hello World"
+      },
+
+      {
+        "key": "2009/01/30 18:04:11",
+        "id": "biking",
+        "value": "Biking"
+      },
+
+      {
+        "key": "2009/02/17 21:13:39",
+        "id": "bought-a-cat",
+        "value": "Bought a Cat"
+      }
+
+    ]
+  }
+
+Now, the actual result is not as nicely formatted and doesn’t include any
+superfluous whitespace or newlines, but this is better for you (and us!)
+to read and understand. Where does that "id" member in the result rows come
+from? That wasn’t there before. That’s because we omitted it earlier to avoid
+confusion. CouchDB automatically includes the document ID of the document that
+created the entry in the view result. We’ll use this as well when constructing
+links to the blog post pages.
+
+Efficient Lookups
+=================
+
+Let’s move on to the second use case for views: “building efficient indexes to
+find documents by any value or structure that resides in them.” We already
+explained the efficient indexing, but we skipped a few details. This is a good
+time to finish this discussion as we are looking at map functions that are a
+little more complex.
+
+First, back to the B-trees! We explained that the B-tree that backs the
+key-sorted view result is built only once, when you first query a view,
+and all subsequent queries will just read the B-tree instead of executing
+the map function for all documents again. What happens, though, when you change
+a document, add a new one, or delete one? Easy: CouchDB is smart enough
+to find the rows in the view result that were created by a specific document.
+It marks them invalid so that they no longer show up in view results.
+If the document was deleted, we’re good — the resulting B-tree reflects the
+state of the database. If a document got updated, the new document is run
+through the map function and the resulting new lines are inserted into
+the B-tree at the correct spots. New documents are handled in the same way.
+The B-tree is a very efficient data structure for our needs, and the crash-only
+design of CouchDB databases is carried over to the view indexes as well.
+
+To add one more point to the efficiency discussion: usually multiple documents
+are updated between view queries. The mechanism explained in the previous
+paragraph gets applied to all changes in the database since the last time
+the view was queried in a batch operation, which makes things even faster and
+is generally a better use of your resources.
+
+Find One
+--------
+
+On to more complex map functions. We said “find documents by any value or
+structure that resides in them.” We already explained how to extract a value
+by which to sort a list of views (our date field). The same mechanism is used
+for fast lookups. The URI to query to get a view’s result is
+``/database/_design/designdocname/_view/viewname``. This gives you a list of all
+rows in the view. We have only three documents, so things are small, but with
+thousands of documents, this can get long. You can add view parameters to the
+URI to constrain the result set. Say we know the date of a blog post.
+To find a single document, we would use
+``/blog/_design/docs/_view/by_date?key="2009/01/30 18:04:11"``
+to get the “Biking” blog post. Remember that you can place whatever you like
+in the key parameter to the emit() function. Whatever you put in there, we can
+now use to look up exactly — and fast.
+
+Note that in the case where multiple rows have the same key (perhaps we design
+a view where the key is the name of the post’s author), key queries can return
+more than one row.
+
+Find Many
+---------
+
+We talked about “getting all posts for last month.” If it’s February now,
+this is as easy as ``/blog/_design/docs/_view/by_date?startkey="2010/01/01 00:00:00"&endkey="2010/02/00 00:00:00"``.
+The ``startkey`` and ``endkey`` parameters specify an inclusive range on which
+we can search.
+
+To make things a little nicer and to prepare for a future example, we are going
+to change the format of our date field. Instead of a string, we are going to use
+an array, where individual members are part of a timestamp in decreasing
+significance. This sounds fancy, but it is rather easy. Instead of::
+
+  {
+    "date": "2009/01/31 00:00:00"
+  }
+
+we use::
+
+  {
+    "date": [2009, 1, 31, 0, 0, 0]
+  }
+
+Our map function does not have to change for this, but our view result looks
+a little different:
+
+Table 2. New view results:
+
++---------------------------+------------------+
+|            Key            |      Value       |
++===========================+==================+
+| [2009, 1, 15, 15, 52, 20] | "Hello World"    |
++---------------------------+------------------+
+| [2009, 2, 17, 21, 13, 39] | "Biking"         |
++---------------------------+------------------+
+| [2009, 1, 30, 18, 4, 11]  | "Bought a Cat"   |
++---------------------------+------------------+
+
+
+And our queries change to ``/blog/_design/docs/_view/by_date?startkey=[2010, 1, 1, 0, 0, 0]&endkey=[2010, 2, 1, 0, 0, 0]``.
+For all you care, this is just a change in syntax, not meaning. But it shows
+you the power of views. Not only can you construct an index with scalar values
+like strings and integers, you can also use JSON structures as keys for your
+views. Say we tag our documents with a list of tags and want to see all tags,
+but we don’t care for documents that have not been tagged.
+
+.. code-block:: javascript
+
+  {
+    ...
+    tags: ["cool", "freak", "plankton"],
+    ...
+  }
+
+.. code-block:: javascript
+
+  {
+    ...
+    tags: [],
+    ...
+  }
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc.tags.length > 0) {
+      for(var idx in doc.tags) {
+        emit(doc.tags[idx], null);
+      }
+    }
+  }
+
+
+This shows a few new things. You can have conditions on structure
+(``if(doc.tags.length > 0)``) instead of just values. This is also an example of
+how a map function calls :js:func:`emit` multiple times per document.
+And finally, you can pass null instead of a value to the value parameter.
+The same is true for the key parameter. We’ll see in a bit how that is useful.
+
+Reversed Results
+----------------
+
+To retrieve view results in reverse order, use the ``descending=true`` query
+parameter. If you are using a ``startkey`` parameter, you will find that CouchDB
+returns different rows or no rows at all. What’s up with that?
+
+It’s pretty easy to understand when you see how view query options work under
+the hood. A view is stored in a tree structure for fast lookups. Whenever you
+query a view, this is how CouchDB operates:
+
+#. Starts reading at the top, or at the position that ``startkey`` specifies,
+   if present.
+#. Returns one row at a time until the end or until it hits ``endkey``,
+   if present.
+
+If you specify ``descending=true``, the reading direction is reversed,
+not the sort  order of the rows in the view. In addition, the same two-step
+procedure is followed.
+
+Say you have a view result that looks like this:
+
++-----+-------+
+| Key | Value |
++=====+=======+
+|  0  | "foo" |
++-----+-------+
+|  1  | "bar" |
++-----+-------+
+|  2  | "baz" |
++-----+-------+
+
+Here are potential query options: ``?startkey=1&descending=true``. What will
+CouchDB do? See #1 above: it jumps to ``startkey``, which is the row with the
+key ``1``, and starts reading backward until it hits the end of the view.
+So the particular result would be:
+
++-----+-------+
+| Key | Value |
++=====+=======+
+|  1  | "bar" |
++-----+-------+
+|  0  | "foo" |
++-----+-------+
+
+This is very likely not what you want. To get the rows with the indexes ``1``
+and ``2`` in reverse order, you need to switch the ``startkey`` to ``endkey``:
+``endkey=1&descending=true``:
+
++-----+-------+
+| Key | Value |
++=====+=======+
+|  2  | "baz" |
++-----+-------+
+|  1  | "bar" |
++-----+-------+
+
+Now that looks a lot better. CouchDB started reading at the bottom of the view
+and went backward until it hit ``endkey``.
+
+The View to Get Comments for Posts
+==================================
+
+We use an array key here to support the ``group_level`` reduce query parameter.
+CouchDB’s views are stored in the B-tree file structure. Because of the way
+B-trees are structured, we can cache the intermediate reduce results in the
+non-leaf nodes of the tree, so reduce queries can be computed along arbitrary
+key ranges in logarithmic time. See Figure 1, “Comments map function”.
+
+In the blog app, we use ``group_leve``l reduce queries to compute the count of
+comments both on a per-post and total basis, achieved by querying the same view
+index with different methods. With some array keys, and assuming each key has
+the value ``1``:
+
+.. code-block:: javascript
+
+  ["a","b","c"]
+  ["a","b","e"]
+  ["a","c","m"]
+  ["b","a","c"]
+  ["b","a","g"]
+
+the reduce view:
+
+.. code-block:: javascript
+
+  function(keys, values, rereduce) {
+    return sum(values)
+  }
+
+returns the total number of rows between the start and end key.
+So with ``startkey=["a","b"]&endkey=["b"]`` (which includes the first three of
+the above keys) the result would equal ``3``. The effect is to count rows.
+If you’d like to count rows without depending on the row value, you can switch
+on the ``rereduce`` parameter:
+
+.. code-block:: javascript
+
+  function(keys, values, rereduce) {
+    if (rereduce) {
+      return sum(values);
+    } else {
+      return values.length;
+    }
+  }
+
+.. note::
+
+   JavaScript function about could be effectively replaced by builtin ``_count``
+   one.
+
+.. figure:: ../../../images/views-intro-01.png
+   :align: center
+   :scale: 50 %
+   :alt:  Comments map function
+
+   Figure 1. Comments map function
+
+
+This is the reduce view used by the example app to count comments, while
+utilizing the map to output the comments, which are more useful than just
+``1`` over and over. It pays to spend some time playing around with map and
+reduce functions. Futon is OK for this, but it doesn’t give full access to all
+the query parameters. Writing your own test code for views in your language
+of choice is a great way to explore the nuances and capabilities of CouchDB’s
+incremental MapReduce system.
+
+Anyway, with a ``group_level`` query, you’re basically running a series of
+reduce range queries: one for each group that shows up at the level you query.
+Let’s reprint the key list from earlier, grouped at level ``1``:
+
+.. code-block:: javascript
+
+  ["a"]   3
+  ["b"]   2
+
+And at ``group_level=2``:
+
+.. code-block:: javascript
+
+  ["a","b"]   2
+  ["a","c"]   1
+  ["b","a"]   2
+
+Using the parameter ``group=true`` makes it behave as though it were
+``group_level=exact``, so in the case of our current example, it would give the
+number ``1`` for each key, as there are no exactly duplicated keys.
+
+Reduce/Rereduce
+===============
+
+We briefly talked about the ``rereduce`` parameter to your reduce function.
+We’ll explain what’s up with it in this section. By now, you should have learned
+that your view result is stored in B-tree index structure for efficiency.
+The existence and use of the ``rereduce`` parameter is tightly coupled to how
+the B-tree index works.
+
+Consider the map result are:
+
+.. code-block:: javascript
+
+  "afrikan", 1
+  "afrikan", 1
+  "chinese", 1
+  "chinese", 1
+  "chinese", 1
+  "chinese", 1
+  "french", 1
+  "italian", 1
+  "italian", 1
+  "spanish", 1
+  "vietnamese", 1
+  "vietnamese", 1
+
+Example 1. Example view result (mmm, food)
+
+When we want to find out how many dishes there are per origin, we can reuse
+the simple reduce function shown earlier:
+
+.. code-block:: javascript
+
+  function(keys, values, rereduce) {
+    return sum(values);
+  }
+
+Figure 2, “The B-tree index” shows a simplified version of what the B-tree index
+looks like. We abbreviated the key strings.
+
+.. figure:: ../../../images/views-intro-02.png
+   :align: center
+   :alt: The B-tree index
+
+   Figure 2. The B-tree index
+
+The view result is what computer science grads call a “pre-order” walk through
+the tree. We look at each element in each node starting from the left. Whenever
+we see that there is a subnode to descend into, we descend and start reading
+the elements in that subnode. When we have walked through the entire tree,
+we’re done.
+
+You can see that CouchDB stores both keys and values inside each leaf node.
+In our case, it is simply always ``1``, but you might have a value where you
+count other results and then all rows have a different value. What’s important
+is that CouchDB runs all elements that are within a node into the reduce
+function (setting the ``rereduce`` parameter to false) and stores the result
+inside the parent node along with the edge to the subnode. In our case, each
+edge has a 3 representing the reduce value for the node it points to.
+
+.. note::
+
+   In reality, nodes have more than 1,600 elements in them. CouchDB computes
+   the result for all the elements in multiple iterations over the elements in
+   a single node, not all at once (which would be disastrous for memory
+   consumption).
+
+Now let’s see what happens when we run a query. We want to know how many
+"chinese" entries we have. The query option is simple: ``?key="chinese"``.
+See Figure 3, “The B-tree index reduce result”.
+
+.. figure:: ../../../images/views-intro-03.png
+   :align: center
+   :alt: The B-tree index reduce result
+
+   Figure 3. The B-tree index reduce result
+
+CouchDB detects that all values in the subnode include the "chinese" key.
+It concludes that it can take just the 3 values associated with that node to
+compute the final result. It then finds the node left to it and sees that it’s
+a node with keys outside the requested range (``key=`` requests a range where
+the beginning and the end are the same value). It concludes that it has to use
+the "chinese" element’s value and the other node’s value and run them through
+the reduce function with the ``rereduce`` parameter set to true.
+
+The reduce function effectively calculates 3 + 1 on query time and returns the
+desired result. The next example shows some pseudocode that shows the last
+invocation of the reduce function with actual values:
+
+.. code-block:: javascript
+
+  function(null, [3, 1], true) {
+    return sum([3, 1]);
+  }
+
+
+Now, we said your reduce function must actually reduce your values. If you see
+the B-tree, it should become obvious what happens when you don’t reduce your
+values. Consider the following map result and reduce function. This time we
+want to get a list of all the unique labels in our view:
+
+.. code-block:: javascript
+
+  "abc", "afrikan"
+  "cef", "afrikan"
+  "fhi", "chinese"
+  "hkl", "chinese"
+  "ino", "chinese"
+  "lqr", "chinese"
+  "mtu", "french"
+  "owx", "italian"
+  "qza", "italian"
+  "tdx", "spanish"
+  "xfg", "vietnamese"
+  "zul", "vietnamese"
+
+We don’t care for the key here and only list all the labels we have. Our reduce
+function removes duplicates:
+
+.. code-block:: javascript
+
+  function(keys, values, rereduce) {
+    var unique_labels = {};
+    values.forEach(function(label) {
+      if(!unique_labels[label]) {
+        unique_labels[label] = true;
+      }
+    });
+
+    return unique_labels;
+  }
+
+
+This translates to Figure 4, “An overflowing reduce index”.
+
+We hope you get the picture. The way the B-tree storage works means that if you
+don’t actually reduce your data in the reduce function, you end up having
+CouchDB copy huge amounts of data around that grow linearly, if not faster
+with the number of rows in your view.
+
+CouchDB will be able to compute the final result, but only for views with a few
+rows. Anything larger will experience a ridiculously slow view build time.
+To help with that, CouchDB since version 0.10.0 will throw an error if your
+reduce function does not reduce its input values.
+
+.. figure:: ../../../images/views-intro-04.png
+   :align: center
+   :alt: An overflowing reduce index
+
+   Figure 4. An overflowing reduce index
+
+
+Lessons Learned
+===============
+
+- If you don’t use the key field in the map function, you are probably doing it
+  wrong.
+- If you are trying to make a list of values unique in the reduce functions,
+  you are probably doing it wrong.
+- If you don’t reduce your values to a single scalar value or a small
+  fixed-sized object or array with a fixed number of scalar values of small
+  sizes, you are probably doing it wrong.
+
+Wrapping Up
+===========
+
+Map functions are side effect–free functions that take a document as argument
+and `emit` key/value pairs. CouchDB stores the emitted rows by constructing a
+sorted B-tree index, so row lookups by key, as well as streaming operations
+across a range of rows, can be accomplished in a small memory and processing
+footprint, while writes avoid seeks. Generating a view takes ``O(N)``, where
+``N`` is the total number of rows in the view. However, querying a view is very
+quick, as the B-tree remains shallow even when it contains many, many keys.
+
+Reduce functions operate on the sorted rows emitted by map view functions.
+CouchDB’s reduce functionality takes advantage of one of the fundamental
+properties of B-tree indexes: for every leaf node (a sorted row), there is a
+chain of internal nodes reaching back to the root. Each leaf node in the B-tree
+carries a few rows (on the order of tens, depending on row size), and each
+internal node may link to a few leaf nodes or other internal nodes.
+
+The reduce function is run on every node in the tree in order to calculate
+the final reduce value. The end result is a reduce function that can be
+incrementally updated upon changes to the map function, while recalculating
+the reduction values for a minimum number of nodes. The initial reduction is
+calculated once per each node (inner and leaf) in the tree.
+
+When run on leaf nodes (which contain actual map rows), the reduce function’s
+third parameter, ``rereduce``, is false. The arguments in this case are the keys
+and values as output by the map function. The function has a single returned
+reduction value, which is stored on the inner node that a working set of leaf
+nodes have in common, and is used as a cache in future reduce calculations.
+
+When the reduce function is run on inner nodes, the ``rereduce`` flag is
+``true``. This allows the function to account for the fact that it will be
+receiving its own prior output. When ``rereduce`` is true, the values passed to
+the function are intermediate reduction values as cached from previous
+calculations. When the tree is more than two levels deep, the `rereduce` phase
+is repeated, consuming chunks of the previous level’s output until the final
+reduce value is calculated at the root node.
+
+A common mistake new CouchDB users make is attempting to construct complex
+aggregate values with a reduce function. Full reductions should result in a
+scalar value, like 5, and not, for instance, a JSON hash with a set of unique
+keys and the count of each. The problem with this approach is that you’ll end
+up with a very large final value. The number of unique keys can be nearly as
+large as the number of total keys, even for a large set. It is fine to combine
+a few scalar calculations into one reduce function; for instance, to find the
+total, average, and standard deviation of a set of numbers in a single function.
+
+If you’re interested in pushing the edge of CouchDB’s incremental reduce
+functionality, have a look at `Google’s paper on Sawzall`_, which gives examples
+of some of the more exotic reductions that can be accomplished in a system with
+similar constraints.
+
+.. _Google’s paper on Sawzall: http://research.google.com/archive/sawzall.html


[46/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Import view collation article from wiki.

http://wiki.apache.org/couchdb/View_collation

COUCHDB-1820


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/a2f550b1
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/a2f550b1
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/a2f550b1

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: a2f550b184071566316858e5ac8c550a65390bcf
Parents: 1931add
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 15:04:31 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 15:04:31 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am                |   3 +
 share/doc/src/couchapp/views/collation.rst | 254 ++++++++++++++++++++++++
 share/doc/src/couchapp/views/index.rst     |   1 +
 3 files changed, 258 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/a2f550b1/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 7cb1625..ab73390 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -89,6 +89,7 @@ html_files = \
     html/_sources/config/proxying.txt \
     html/_sources/couchapp/ddocs.txt \
     html/_sources/couchapp/index.txt \
+    html/_sources/couchapp/views/collation.txt \
     html/_sources/couchapp/views/index.txt \
     html/_sources/couchapp/views/intro.txt \
     html/_sources/fauxton/addons.txt \
@@ -177,6 +178,7 @@ html_files = \
     html/config/proxying.html \
     html/couchapp/ddocs.html \
     html/couchapp/index.html \
+    html/couchapp/views/collation.html \
     html/couchapp/views/index.html \
     html/couchapp/views/intro.html \
     html/fauxton/addons.html \
@@ -263,6 +265,7 @@ src_files = \
     ../src/config/proxying.rst \
     ../src/couchapp/ddocs.rst \
     ../src/couchapp/index.rst \
+    ../src/couchapp/views/collation.rst \
     ../src/couchapp/views/index.rst \
     ../src/couchapp/views/intro.rst \
     ../src/fauxton/addons.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/a2f550b1/share/doc/src/couchapp/views/collation.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/collation.rst b/share/doc/src/couchapp/views/collation.rst
new file mode 100644
index 0000000..4b9f1b0
--- /dev/null
+++ b/share/doc/src/couchapp/views/collation.rst
@@ -0,0 +1,254 @@
+.. 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.
+
+
+===============
+Views Collation
+===============
+
+Basics
+======
+
+View functions specify a key and a value to be returned for each row. CouchDB
+collates the view rows by this key. In the following example, the ``LastName``
+property serves as the key, thus the result will be sorted by ``LastName``:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc.Type == "customer") {
+      emit(doc.LastName, {FirstName: doc.FirstName, Address: doc.Address});
+    }
+  }
+
+CouchDB allows arbitrary JSON structures to be used as keys. You can use complex
+keys for fine-grained control over sorting and grouping.
+
+Examples
+========
+
+The following clever trick would return both customer and order documents.
+The key is composed of a customer ``_id`` and a sorting token. Because the key
+for order documents begins with the ``_id`` of a customer document, all the
+orders will be sorted by customer. Because the sorting token for customers is
+lower than the token for orders, the customer document will come before the
+associated orders. The values 0 and 1 for the sorting token are arbitrary.
+
+.. code-block:: javascript
+
+  function(doc) {
+    if (doc.Type == "customer") {
+      emit([doc._id, 0], doc);
+    } else if (doc.Type == "order") {
+      emit([doc.customer_id, 1], doc);
+    }
+  }
+
+
+Sorting by Dates
+================
+
+It maybe be convenient to store date attributes in a human readable format
+(i.e. as a `string`), but still sort by date. This can be done by converting
+the date to a `number` in the :js:func:`emit` function. For example, given
+a document with a created_at attribute of ``'Wed Jul 23 16:29:21 +0100 2013'``,
+the following emit function would sort by date:
+
+.. code-block:: javascript
+
+  emit(Date.parse(doc.created_at).getTime(), doc);
+
+Alternatively, if you use a date format which sorts lexicographically,
+such as ``"2013/06/09 13:52:11 +0000"`` you can just
+
+.. code-block:: javascript
+
+  emit(doc.created_at, doc);
+
+and avoid the conversion. As a bonus, this date format is compatible with the
+JavaScript date parser, so you can use ``new Date(doc.created_at)`` in your
+client side JavaScript to make date sorting easy in the browser.
+
+String Ranges
+=============
+
+If you need start and end keys that encompass every string with a given prefix,
+it is better to use a high value unicode character, than to use a ``'ZZZZ'``
+suffix.
+
+That is, rather than::
+
+  startkey="abc"&endkey="abcZZZZZZZZZ"
+
+You should use::
+
+  startkey="abc"&endkey="abc\ufff0"
+
+Collation Specification
+=======================
+
+This section is based on the view_collation function in `view_collation.js`_:
+
+.. _view_collation.js: https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=blob;f=share/www/script/test/view_collation.js;hb=HEAD
+
+.. code-block:: javascript
+
+  // special values sort before all other types
+  null
+  false
+  true
+
+  // then numbers
+  1
+  2
+  3.0
+  4
+
+  // then text, case sensitive
+  "a"
+  "A"
+  "aa"
+  "b"
+  "B"
+  "ba"
+  "bb"
+
+  // then arrays. compared element by element until different.
+  // Longer arrays sort after their prefixes
+  ["a"]
+  ["b"]
+  ["b","c"]
+  ["b","c", "a"]
+  ["b","d"]
+  ["b","d", "e"]
+
+  // then object, compares each key value in the list until different.
+  // larger objects sort after their subset objects.
+  {a:1}
+  {a:2}
+  {b:1}
+  {b:2}
+  {b:2, a:1} // Member order does matter for collation.
+             // CouchDB preserves member order
+             // but doesn't require that clients will.
+             // this test might fail if used with a js engine
+             // that doesn't preserve order
+  {b:2, c:2}
+
+Comparison of strings is done using `ICU`_ which implements the
+`Unicode Collation Algorithm`_, giving a dictionary sorting of keys.
+This can give surprising results if you were expecting ASCII ordering.
+Note that:
+
+- All symbols sort before numbers and letters (even the "high" symbols like
+  tilde, ``0x7e``)
+
+- Differing sequences of letters are compared without regard to case, so
+  ``a < aa`` but also ``A < aa`` and ``a < AA``
+
+- Identical sequences of letters are compared with regard to case, with
+  lowercase before uppercase, so ``a < A``
+
+.. _ICU: http://site.icu-project.org/
+.. _Unicode Collation Algorithm: http://www.unicode.org/unicode/reports/tr10/
+
+You can demonstrate the collation sequence for 7-bit ASCII characters like this:
+
+.. code-block:: ruby
+
+  require 'rubygems'
+  require 'restclient'
+  require 'json'
+
+  DB="http://127.0.0.1:5984/collator"
+
+  RestClient.delete DB rescue nil
+  RestClient.put "#{DB}",""
+
+  (32..126).each do |c|
+    RestClient.put "#{DB}/#{c.to_s(16)}", {"x"=>c.chr}.to_json
+  end
+
+  RestClient.put "#{DB}/_design/test", <<EOS
+  {
+    "views":{
+      "one":{
+        "map":"function (doc) { emit(doc.x,null); }"
+      }
+    }
+  }
+  EOS
+
+  puts RestClient.get("#{DB}/_design/test/_view/one")
+
+This shows the collation sequence to be::
+
+  ` ^ _ - , ; : ! ? . ' " ( ) [ ] { } @ * / \ & # % + < = > | ~ $ 0 1 2 3 4 5 6 7 8 9
+  a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z
+
+Key ranges
+----------
+
+Take special care when querying key ranges. For example: the query::
+
+  startkey="Abc"&endkey="AbcZZZZ"
+
+will match "ABC" and "abc1", but not "abc". This is because UCA sorts as::
+
+  abc < Abc < ABC < abc1 < AbcZZZZZ
+
+For most applications, to avoid problems you should lowercase the `startkey`::
+
+  startkey="abc"&endkey="abcZZZZZZZZ"
+
+will match all keys starting with ``[aA][bB][cC]``
+
+Complex keys
+------------
+
+The query ``startkey=["foo"]&endkey=["foo",{}]`` will match most array keys
+with "foo" in the first element, such as ``["foo","bar"]`` and
+``["foo",["bar","baz"]]``. However it will not match ``["foo",{"an":"object"}]``
+
+_all_docs
+=========
+
+The :ref:`_all_docs <api/db/all_docs>`  view is a special case because it uses
+ASCII collation for doc ids, not UCA::
+
+  startkey="_design/"&endkey="_design/ZZZZZZZZ"
+
+will not find ``_design/abc`` because `'Z'` comes before `'a'` in the ASCII
+sequence. A better solution is::
+
+  startkey="_design/"&endkey="_design0"
+
+Raw collation
+=============
+
+To squeeze a little more performance out of views, you can specify
+``"options":{"collation":"raw"}``  within the view definition for native Erlang
+collation, especially if you don't require UCA. This gives a different collation
+sequence:
+
+.. code-block:: javascript
+
+  1
+  false
+  null
+  true
+  {"a":"a"},
+  ["a"]
+  "a"
+
+Beware that ``{}`` is no longer a suitable "high" key sentinel value. Use a
+string like ``"\ufff0"`` instead.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/a2f550b1/share/doc/src/couchapp/views/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/index.rst b/share/doc/src/couchapp/views/index.rst
index 0979a49..9239a69 100644
--- a/share/doc/src/couchapp/views/index.rst
+++ b/share/doc/src/couchapp/views/index.rst
@@ -24,3 +24,4 @@ applications with CouchDB
 .. toctree::
 
   intro
+  collation


[35/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Move JSON Number handling section to API basics.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/aa86c0bb
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/aa86c0bb
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/aa86c0bb

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: aa86c0bba9f20cc95ab97453f1e095dcd4858fd6
Parents: 8f4db91
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 04:42:33 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:56:32 2013 +0400

----------------------------------------------------------------------
 share/doc/src/api/basics.rst     | 187 ++++++++++++++++++++++++++++++++++
 share/doc/src/json-structure.rst | 187 ----------------------------------
 2 files changed, 187 insertions(+), 187 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/aa86c0bb/share/doc/src/api/basics.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/basics.rst b/share/doc/src/api/basics.rst
index 83b1445..a1b1b82 100644
--- a/share/doc/src/api/basics.rst
+++ b/share/doc/src/api/basics.rst
@@ -301,6 +301,193 @@ languages, including Perl, Python, Ruby, Erlang and others.
    valid, invalid structures will cause CouchDB to return an HTTP status code
    of 500 (server error).
 
+Number Handling
+---------------
+
+Any numbers defined in JSON that contain a decimal point or exponent
+will be passed through the Erlang VM's idea of the "double" data type.
+Any numbers that are used in views will pass through the views idea of
+a number (the common JavaScript case means even integers pass through
+a double due to JavaScript's definition of a number).
+
+Consider this document that we write to CouchDB:
+
+.. code-block:: javascript
+
+    {
+      "_id":"30b3b38cdbd9e3a587de9b8122000cff",
+      "number": 1.1
+    }
+
+Now let’s read that document back from CouchDB:
+
+.. code-block:: javascript
+
+    {
+      "_id":"30b3b38cdbd9e3a587de9b8122000cff",
+      "_rev":"1-f065cee7c3fd93aa50f6c97acde93030",
+      "number":1.1000000000000000888
+    }
+
+
+What happens is CouchDB is changing the textual representation of the
+result of decoding what it was given into some numerical format. In most
+cases this is an `IEEE 754`_ double precision floating point number which
+is exactly what almost all other languages use as well.
+
+.. _IEEE 754: https://en.wikipedia.org/wiki/IEEE_754-2008
+
+What CouchDB does a bit differently than other languages is that it
+does not attempt to pretty print the resulting output to use the
+shortest number of characters. For instance, this is why we have this
+relationship:
+
+.. code-block:: erlang
+
+    ejson:encode(ejson:decode(<<"1.1">>)).
+    <<"1.1000000000000000888">>
+
+What can be confusing here is that internally those two formats
+decode into the same IEEE-754 representation. And more importantly, it
+will decode into a fairly close representation when passed through all
+major parsers that I know about.
+
+While we've only been discussing cases where the textual
+representation changes, another important case is when an input value
+is contains more precision than can actually represented in a double.
+(You could argue that this case is actually "losing" data if you don't
+accept that numbers are stored in doubles).
+
+Here's a log for a couple of the more common JSON libraries I happen
+to have on my machine:
+
+Spidermonkey::
+
+    $ js -h 2>&1 | head -n 1
+    JavaScript-C 1.8.5 2011-03-31
+    $ js
+    js> JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
+    "1.0123456789012346"
+    js> var f = JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
+    js> JSON.stringify(JSON.parse(f))
+    "1.0123456789012346"
+
+Node::
+
+    $ node -v
+    v0.6.15
+    $ node
+    JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
+    '1.0123456789012346'
+    var f = JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
+    undefined
+    JSON.stringify(JSON.parse(f))
+    '1.0123456789012346'
+
+Python::
+
+    $ python
+    Python 2.7.2 (default, Jun 20 2012, 16:23:33)
+    [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
+    Type "help", "copyright", "credits" or "license" for more information.
+    import json
+    json.dumps(json.loads("1.01234567890123456789012345678901234567890"))
+    '1.0123456789012346'
+    f = json.dumps(json.loads("1.01234567890123456789012345678901234567890"))
+    json.dumps(json.loads(f))
+    '1.0123456789012346'
+
+Ruby::
+
+    $ irb --version
+    irb 0.9.5(05/04/13)
+    require 'JSON'
+    => true
+    JSON.dump(JSON.load("[1.01234567890123456789012345678901234567890]"))
+    => "[1.01234567890123]"
+    f = JSON.dump(JSON.load("[1.01234567890123456789012345678901234567890]"))
+    => "[1.01234567890123]"
+    JSON.dump(JSON.load(f))
+    => "[1.01234567890123]"
+
+
+.. note:: A small aside on Ruby, it requires a top level object or array, so I just
+         wrapped the value. Should be obvious it doesn't affect the result of
+         parsing the number though.
+
+
+Ejson (CouchDB's current parser) at CouchDB sha 168a663b::
+
+    $ ./utils/run -i
+    Erlang R14B04 (erts-5.8.5) [source] [64-bit] [smp:2:2] [rq:2]
+    [async-threads:4] [hipe] [kernel-poll:true]
+
+    Eshell V5.8.5  (abort with ^G)
+    1> ejson:encode(ejson:decode(<<"1.01234567890123456789012345678901234567890">>)).
+    <<"1.0123456789012346135">>
+    2> F = ejson:encode(ejson:decode(<<"1.01234567890123456789012345678901234567890">>)).
+    <<"1.0123456789012346135">>
+    3> ejson:encode(ejson:decode(F)).
+    <<"1.0123456789012346135">>
+
+
+As you can see they all pretty much behave the same except for Ruby
+actually does appear to be losing some precision over the other
+libraries.
+
+The astute observer will notice that ejson (the CouchDB JSON library)
+reported an extra three digits. While its tempting to think that this
+is due to some internal difference, its just a more specific case of
+the 1.1 input as described above.
+
+The important point to realize here is that a double can only hold a
+finite number of values. What we're doing here is generating a string
+that when passed through the "standard" floating point parsing
+algorithms (ie, strtod) will result in the same bit pattern in memory
+as we started with. Or, slightly different, the bytes in a JSON
+serialized number are chosen such that they refer to a single specific
+value that a double can represent.
+
+The important point to understand is that we're mapping from one
+infinite set onto a finite set. An easy way to see this is by
+reflecting on this::
+
+    1.0 == 1.00 == 1.000 = 1.(infinite zeroes)
+
+Obviously a computer can't hold infinite bytes so we have to
+decimate our infinitely sized set to a finite set that can be
+represented concisely.
+
+The game that other JSON libraries are playing is merely:
+
+"How few characters do I have to use to select this specific value for a double"
+
+And that game has lots and lots of subtle details that are difficult
+to duplicate in C without a significant amount of effort (it took
+Python over a year to get it sorted with their fancy build systems
+that automatically run on a number of different architectures).
+
+Hopefully we've shown that CouchDB is not doing anything "funky" by
+changing input. Its behaving the same as any other common JSON library
+does, its just not pretty printing its output.
+
+On the other hand, if you actually are in a position where an IEEE-754
+double is not a satisfactory datatype for your numbers, then the
+answer as has been stated is to not pass your numbers through this
+representation. In JSON this is accomplished by encoding them as a
+string or by using integer types (although integer types can still
+bite you if you use a platform that has a different integer
+representation than normal, ie, JavaScript).
+
+Also, if anyone is really interested in changing this behavior, I'm
+all ears for contributions to `jiffy`_ (which is theoretically going to
+replace ejson when I get around to updating the build system). The
+places I've looked for inspiration are TCL and Python. If you know a
+decent implementation of this float printing algorithm give me a
+holler.
+
+.. _jiffy: https://github.com/davisp/jiffy
+
 .. _errors:
 
 HTTP Status Codes

http://git-wip-us.apache.org/repos/asf/couchdb/blob/aa86c0bb/share/doc/src/json-structure.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/json-structure.rst b/share/doc/src/json-structure.rst
index c4089b9..c124e44 100644
--- a/share/doc/src/json-structure.rst
+++ b/share/doc/src/json-structure.rst
@@ -634,190 +634,3 @@ View Head Information
         "total_rows": 42,
         "offset": 3
     }
-
-Number Handling
-===============
-
-Any numbers defined in JSON that contain a decimal point or exponent
-will be passed through the Erlang VM's idea of the "double" data type.
-Any numbers that are used in views will pass through the views idea of
-a number (the common JavaScript case means even integers pass through
-a double due to JavaScript's definition of a number).
-
-Consider this document that we write to CouchDB:
-
-.. code-block:: javascript
-
-    {
-      "_id":"30b3b38cdbd9e3a587de9b8122000cff",
-      "number": 1.1
-    }
-
-Now let’s read that document back from CouchDB:
-
-.. code-block:: javascript
-
-    {
-      "_id":"30b3b38cdbd9e3a587de9b8122000cff",
-      "_rev":"1-f065cee7c3fd93aa50f6c97acde93030",
-      "number":1.1000000000000000888
-    }
-
-
-What happens is CouchDB is changing the textual representation of the
-result of decoding what it was given into some numerical format. In most
-cases this is an `IEEE 754`_ double precision floating point number which
-is exactly what almost all other languages use as well.
-
-.. _IEEE 754: https://en.wikipedia.org/wiki/IEEE_754-2008
-
-What CouchDB does a bit differently than other languages is that it
-does not attempt to pretty print the resulting output to use the
-shortest number of characters. For instance, this is why we have this
-relationship:
-
-.. code-block:: erlang
-
-    ejson:encode(ejson:decode(<<"1.1">>)).
-    <<"1.1000000000000000888">>
-
-What can be confusing here is that internally those two formats
-decode into the same IEEE-754 representation. And more importantly, it
-will decode into a fairly close representation when passed through all
-major parsers that I know about.
-
-While we've only been discussing cases where the textual
-representation changes, another important case is when an input value
-is contains more precision than can actually represented in a double.
-(You could argue that this case is actually "losing" data if you don't
-accept that numbers are stored in doubles).
-
-Here's a log for a couple of the more common JSON libraries I happen
-to have on my machine:
-
-Spidermonkey::
-
-    $ js -h 2>&1 | head -n 1
-    JavaScript-C 1.8.5 2011-03-31
-    $ js
-    js> JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
-    "1.0123456789012346"
-    js> var f = JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
-    js> JSON.stringify(JSON.parse(f))
-    "1.0123456789012346"
-
-Node::
-
-    $ node -v
-    v0.6.15
-    $ node
-    JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
-    '1.0123456789012346'
-    var f = JSON.stringify(JSON.parse("1.01234567890123456789012345678901234567890"))
-    undefined
-    JSON.stringify(JSON.parse(f))
-    '1.0123456789012346'
-
-Python::
-
-    $ python
-    Python 2.7.2 (default, Jun 20 2012, 16:23:33)
-    [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
-    Type "help", "copyright", "credits" or "license" for more information.
-    import json
-    json.dumps(json.loads("1.01234567890123456789012345678901234567890"))
-    '1.0123456789012346'
-    f = json.dumps(json.loads("1.01234567890123456789012345678901234567890"))
-    json.dumps(json.loads(f))
-    '1.0123456789012346'
-
-Ruby::
-
-    $ irb --version
-    irb 0.9.5(05/04/13)
-    require 'JSON'
-    => true
-    JSON.dump(JSON.load("[1.01234567890123456789012345678901234567890]"))
-    => "[1.01234567890123]"
-    f = JSON.dump(JSON.load("[1.01234567890123456789012345678901234567890]"))
-    => "[1.01234567890123]"
-    JSON.dump(JSON.load(f))
-    => "[1.01234567890123]"
-
-
-.. note:: A small aside on Ruby, it requires a top level object or array, so I just
-         wrapped the value. Should be obvious it doesn't affect the result of
-         parsing the number though.
-
-
-Ejson (CouchDB's current parser) at CouchDB sha 168a663b::
-
-    $ ./utils/run -i
-    Erlang R14B04 (erts-5.8.5) [source] [64-bit] [smp:2:2] [rq:2]
-    [async-threads:4] [hipe] [kernel-poll:true]
-
-    Eshell V5.8.5  (abort with ^G)
-    1> ejson:encode(ejson:decode(<<"1.01234567890123456789012345678901234567890">>)).
-    <<"1.0123456789012346135">>
-    2> F = ejson:encode(ejson:decode(<<"1.01234567890123456789012345678901234567890">>)).
-    <<"1.0123456789012346135">>
-    3> ejson:encode(ejson:decode(F)).
-    <<"1.0123456789012346135">>
-
-
-As you can see they all pretty much behave the same except for Ruby
-actually does appear to be losing some precision over the other
-libraries.
-
-The astute observer will notice that ejson (the CouchDB JSON library)
-reported an extra three digits. While its tempting to think that this
-is due to some internal difference, its just a more specific case of
-the 1.1 input as described above.
-
-The important point to realize here is that a double can only hold a
-finite number of values. What we're doing here is generating a string
-that when passed through the "standard" floating point parsing
-algorithms (ie, strtod) will result in the same bit pattern in memory
-as we started with. Or, slightly different, the bytes in a JSON
-serialized number are chosen such that they refer to a single specific
-value that a double can represent.
-
-The important point to understand is that we're mapping from one
-infinite set onto a finite set. An easy way to see this is by
-reflecting on this::
-
-    1.0 == 1.00 == 1.000 = 1.(infinite zeroes)
-
-Obviously a computer can't hold infinite bytes so we have to
-decimate our infinitely sized set to a finite set that can be
-represented concisely.
-
-The game that other JSON libraries are playing is merely:
-
-"How few characters do I have to use to select this specific value for a double"
-
-And that game has lots and lots of subtle details that are difficult
-to duplicate in C without a significant amount of effort (it took
-Python over a year to get it sorted with their fancy build systems
-that automatically run on a number of different architectures).
-
-Hopefully we've shown that CouchDB is not doing anything "funky" by
-changing input. Its behaving the same as any other common JSON library
-does, its just not pretty printing its output.
-
-On the other hand, if you actually are in a position where an IEEE-754
-double is not a satisfactory datatype for your numbers, then the
-answer as has been stated is to not pass your numbers through this
-representation. In JSON this is accomplished by encoding them as a
-string or by using integer types (although integer types can still
-bite you if you use a platform that has a different integer
-representation than normal, ie, JavaScript).
-
-Also, if anyone is really interested in changing this behavior, I'm
-all ears for contributions to `jiffy`_ (which is theoretically going to
-replace ejson when I get around to updating the build system). The
-places I've looked for inspiration are TCL and Python. If you know a
-decent implementation of this float printing algorithm give me a
-holler.
-
-.. _jiffy: https://github.com/davisp/jiffy


[48/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Import "View Cookbook for SQL Jockeys" article from Guide.

http://guide.couchdb.org/draft/cookbook.html


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/b5487403
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/b5487403
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/b5487403

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: b54874039ff07dad5e872f095d317c124b82c96a
Parents: bf60cd5
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 16:02:57 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 16:02:57 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am            |   3 +
 share/doc/src/couchapp/views/index.rst |   1 +
 share/doc/src/couchapp/views/nosql.rst | 530 ++++++++++++++++++++++++++++
 3 files changed, 534 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/b5487403/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index 7c4eb56..ffe64aa 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -93,6 +93,7 @@ html_files = \
     html/_sources/couchapp/views/index.txt \
     html/_sources/couchapp/views/intro.txt \
     html/_sources/couchapp/views/joins.txt \
+    html/_sources/couchapp/views/nosql.txt \
     html/_sources/fauxton/addons.txt \
     html/_sources/fauxton/index.txt \
     html/_sources/fauxton/install.txt \
@@ -183,6 +184,7 @@ html_files = \
     html/couchapp/views/index.html \
     html/couchapp/views/intro.html \
     html/couchapp/views/joins.html \
+    html/couchapp/views/nosql.html \
     html/fauxton/addons.html \
     html/fauxton/index.html \
     html/fauxton/install.html \
@@ -271,6 +273,7 @@ src_files = \
     ../src/couchapp/views/index.rst \
     ../src/couchapp/views/intro.rst \
     ../src/couchapp/views/joins.rst \
+    ../src/couchapp/views/nosql.rst \
     ../src/fauxton/addons.rst \
     ../src/fauxton/index.rst \
     ../src/fauxton/install.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/b5487403/share/doc/src/couchapp/views/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/index.rst b/share/doc/src/couchapp/views/index.rst
index 1a77caf..4b007f5 100644
--- a/share/doc/src/couchapp/views/index.rst
+++ b/share/doc/src/couchapp/views/index.rst
@@ -26,3 +26,4 @@ applications with CouchDB
   intro
   collation
   joins
+  nosql

http://git-wip-us.apache.org/repos/asf/couchdb/blob/b5487403/share/doc/src/couchapp/views/nosql.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/couchapp/views/nosql.rst b/share/doc/src/couchapp/views/nosql.rst
new file mode 100644
index 0000000..49d0bc4
--- /dev/null
+++ b/share/doc/src/couchapp/views/nosql.rst
@@ -0,0 +1,530 @@
+.. 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.
+
+
+.. _views/nosql:
+
+=============================
+View Cookbook for SQL Jockeys
+=============================
+
+This is a collection of some common SQL queries and how to get the same result
+in CouchDB. The key to remember here is that CouchDB does not work like an SQL
+database at all and that best practices from the SQL world do not translate well
+or at all to CouchDB. This chapter’s “cookbook” assumes that you are familiar
+with the CouchDB basics such as creating and updating databases and documents.
+
+Using Views
+===========
+
+How you would do this in SQL::
+
+  CREATE TABLE
+
+or::
+
+  ALTER TABLE
+
+How you can do this in CouchDB?
+
+Using views is a two-step process. First you define a view; then you query it.
+This is analogous to defining a table structure (with indexes) using
+``CREATE TABLE`` or ``ALTER TABLE`` and querying it using an SQL query.
+
+Defining a View
+---------------
+
+Defining a view is done by creating a special document in a CouchDB database.
+The only real specialness is the ``_id`` of the document, which starts with
+``_design/`` — for example, _design/application. Other than that, it is just a
+regular CouchDB document. To make sure CouchDB understands that you are defining
+a view, you need to prepare the contents of that design document in a special
+format. Here is an example:
+
+.. code-block:: javascript
+
+  {
+    "_id": "_design/application",
+    "_rev": "1-C1687D17",
+    "views": {
+      "viewname": {
+        "map": "function(doc) { ... }",
+        "reduce": "function(keys, values) { ... }"
+      }
+    }
+  }
+
+We are defining a view `viewname`. The definition of the view consists of two
+functions: the map function and the reduce function. Specifying a reduce
+function is optional. We’ll look at the nature of the functions later. Note that
+`viewname` can be whatever you like: ``users``, ``by-name``, or ``by-date`` are
+just some examples.
+
+A single design document can also include multiple view definitions, each
+identified by a unique name:
+
+.. code-block:: javascript
+
+  {
+    "_id": "_design/application",
+    "_rev": "1-C1687D17",
+    "views": {
+      "viewname": {
+        "map": "function(doc) { ... }",
+        "reduce": "function(keys, values) { ... }"
+      },
+      "anotherview": {
+        "map": "function(doc) { ... }",
+        "reduce": "function(keys, values) { ... }"
+      }
+    }
+  }
+
+Querying a View
+---------------
+
+The name of the design document and the name of the view are significant for
+querying the view. To query the view `viewname`, you perform an HTTP ``GET``
+request to the following URI::
+
+  /database/_design/application/_view/viewname
+
+database is the name of the database you created your design document in. Next
+up is the design document name, and then the view name prefixed with ``_view/``.
+To query `anotherview`, replace `viewname` in that URI with `anotherview`.
+If you want to query a view in a different design document, adjust the design
+document name.
+
+MapReduce Functions
+-------------------
+
+MapReduce is a concept that solves problems by applying a two-step process,
+aptly named the map phase and the reduce phase. The map phase looks at all
+documents in CouchDB separately one after the other and creates a `map result`.
+The map result is an ordered list of key/value pairs. Both key and value can
+be specified by the user writing the map function. A map function may call the
+built-in ``emit(key, value)`` function 0 to N times per document, creating a row
+in the map result per invocation.
+
+CouchDB is smart enough to run a map function only once for every document, even
+on subsequent queries on a view. Only changes to documents or new documents need
+to be processed anew.
+
+Map functions
+-------------
+
+Map functions run in isolation for every document. They can’t modify the
+document, and they can’t talk to the outside world—they can’t have side effects.
+This is required so that CouchDB can guarantee correct results without having
+to recalculate a complete result when only one document gets changed.
+
+The map result looks like this:
+
+.. code-block:: javascript
+
+  {"total_rows":3,"offset":0,"rows":[
+  {"id":"fc2636bf50556346f1ce46b4bc01fe30","key":"Lena","value":5},
+  {"id":"1fb2449f9b9d4e466dbfa47ebe675063","key":"Lisa","value":4},
+  {"id":"8ede09f6f6aeb35d948485624b28f149","key":"Sarah","value":6}
+  ]}
+
+It is a list of rows sorted by the value of key. The id is added automatically
+and refers back to the document that created this row. The value is the data
+you’re looking for. For example purposes, it’s the girl’s age.
+
+The map function that produces this result is:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc.name && doc.age) {
+      emit(doc.name, doc.age);
+    }
+  }
+
+It includes the if statement as a sanity check to ensure that we’re operating
+on the right fields and calls the emit function with the name and age as the key
+and value.
+
+Look Up by Key
+==============
+
+How you would do this in SQL::
+
+  SELECT field FROM table WHERE value="searchterm"
+
+How you can do this in CouchDB?
+
+Use case: get a result (which can be a record or set of records) associated
+with a key ("searchterm").
+
+To look something up quickly, regardless of the storage mechanism, an index is
+needed. An index is a data structure optimized for quick search and retrieval.
+CouchDB’s map result is stored in such an index, which happens to be a B+ tree.
+
+To look up a value by "searchterm", we need to put all values into the key of a
+view. All we need is a simple map function:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc.value) {
+      emit(doc.value, null);
+    }
+  }
+
+This creates a list of documents that have a value field sorted by the data in
+the value field. To find all the records that match "searchterm", we query the
+view and specify the search term as a query parameter::
+
+  /database/_design/application/_view/viewname?key="searchterm"
+
+Consider the documents from the previous section, and say we’re indexing on the
+age field of the documents to find all the five-year-olds:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc.age && doc.name) {
+      emit(doc.age, doc.name);
+    }
+  }
+
+Query::
+
+  /ladies/_design/ladies/_view/age?key=5
+
+Result:
+
+.. code-block:: javascript
+
+  {"total_rows":3,"offset":1,"rows":[
+  {"id":"fc2636bf50556346f1ce46b4bc01fe30","key":5,"value":"Lena"}
+  ]}
+
+Easy.
+
+Note that you have to emit a value. The view result includes the associated
+document ID in every row. We can use it to look up more data from the document
+itself. We can also use the ``?include_docs=true`` parameter to have CouchDB
+fetch the documents individually for us.
+
+Look Up by Prefix
+=================
+
+How you would do this in SQL::
+
+  SELECT field FROM table WHERE value LIKE "searchterm%"
+
+How you can do this in CouchDB?
+
+Use case: find all documents that have a field value that starts with
+`searchterm`. For example, say you stored a MIME type (like `text/html` or
+`image/jpg`) for each document and now you want to find all documents that are
+images according to the MIME type.
+
+The solution is very similar to the previous example: all we need is a map
+function that is a little more clever than the first one. But first, an example
+document:
+
+.. code-block:: javascript
+
+  {
+    "_id": "Hugh Laurie",
+    "_rev": "1-9fded7deef52ac373119d05435581edf",
+    "mime-type": "image/jpg",
+    "description": "some dude"
+  }
+
+The clue lies in extracting the prefix that we want to search for from our
+document and putting it into our view index. We use a regular expression to
+match our prefix:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc["mime-type"]) {
+      // from the start (^) match everything that is not a slash ([^\/]+) until
+      // we find a slash (\/). Slashes needs to be escaped with a backslash (\/)
+      var prefix = doc["mime-type"].match(/^[^\/]+\//);
+      if(prefix) {
+        emit(prefix, null);
+      }
+    }
+  }
+
+We can now query this view with our desired MIME type prefix and not only find
+all images, but also text, video, and all other formats::
+
+  /files/_design/finder/_view/by-mime-type?key="image/"
+
+Aggregate Functions
+===================
+
+How you would do this in SQL::
+
+  SELECT COUNT(field) FROM table
+
+How you can do this in CouchDB?
+
+Use case: calculate a derived value from your data.
+
+We haven’t explained reduce functions yet. Reduce functions are similar to
+aggregate functions in SQL. They compute a value over multiple documents.
+
+To explain the mechanics of reduce functions, we’ll create one that doesn’t make
+a whole lot of sense. But this example is easy to understand. We’ll explore more
+useful reductions later.
+
+Reduce functions operate on the output of the map function (also called the map
+re⁠sult or intermediate result). The reduce function’s job, unsurprisingly, is to
+reduce the list that the map function produces.
+
+Here’s what our summing reduce function looks like:
+
+.. code-block:: javascript
+
+  function(keys, values) {
+    var sum = 0;
+    for(var idx in values) {
+      sum = sum + values[idx];
+    }
+    return sum;
+  }
+
+Here’s an alternate, more idiomatic JavaScript version:
+
+.. code-block:: javascript
+
+  function(keys, values) {
+    var sum = 0;
+    values.forEach(function(element) {
+      sum = sum + element;
+    });
+    return sum;
+  }
+
+.. note::
+
+  Don't miss effective builtin :ref:`reduce functions <reducefun>` like ``_sum``
+  and ``_count``
+
+This reduce function takes two arguments: a list of keys and a list of values.
+For our summing purposes we can ignore the keys-list and consider only the value
+list. We’re looping over the list and add each item to a running total that
+we’re returning at the end of the function.
+
+You’ll see one difference between the map and the reduce function. The map
+function uses ``emit()`` to create its result, whereas the reduce function
+returns a value.
+
+For example, from a list of integer values that specify the age, calculate the
+sum of all years of life for the news headline,
+`“786 life years present at event.”` A little contrived, but very simple and
+thus good for demonstration purposes. Consider the documents and the map view we
+used earlier in this chapter.
+
+The reduce function to calculate the total age of all girls is:
+
+.. code-block:: javascript
+
+  function(keys, values) {
+    return sum(values);
+  }
+
+Note that, instead of the two earlier versions, we use CouchDB’s predefined
+:js:func:`sum` function. It does the same thing as the other two, but it is such
+a common piece of code that CouchDB has it included.
+
+The result for our reduce view now looks like this:
+
+.. code-block:: javascript
+
+  {"rows":[
+    {"key":null,"value":15}
+  ]}
+
+The total sum of all age fields in all our documents is 15. Just what we wanted.
+The key member of the result object is null, as we can’t know anymore which
+documents took part in the creation of the reduced result. We’ll cover more
+advanced reduce cases later on.
+
+As a rule of thumb, the reduce function should reduce to a single scalar value.
+That is, an integer; a string; or a small, fixed-size list or object that
+includes an aggregated value (or values) from the values argument.
+It should never just return values or similar. CouchDB will give you a warning
+if you try to use reduce “the wrong way”:
+
+.. code-block:: javascript
+
+  {
+    "error":"reduce_overflow_error",
+    "message":"Reduce output must shrink more rapidly: Current output: ..."
+  }
+
+Get Unique Values
+=================
+
+How you would do this in SQL::
+
+  SELECT DISTINCT field FROM table
+
+How you can do this in CouchDB?
+
+Getting unique values is not as easy as adding a keyword. But a reduce view and
+a special query parameter give us the same result. Let’s say you want a list of
+tags that your users have tagged themselves with and no duplicates.
+
+First, let’s look at the source documents. We punt on ``_id`` and ``_rev``
+attributes here:
+
+.. code-block:: javascript
+
+  {
+    "name":"Chris",
+    "tags":["mustache", "music", "couchdb"]
+  }
+
+.. code-block:: javascript
+
+  {
+    "name":"Noah",
+    "tags":["hypertext", "philosophy", "couchdb"]
+  }
+
+.. code-block:: javascript
+
+  {
+    "name":"Jan",
+    "tags":["drums", "bike", "couchdb"]
+  }
+
+Next, we need a list of all tags. A map function will do the trick:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc.name && doc.tags) {
+      doc.tags.forEach(function(tag) {
+        emit(tag, null);
+      });
+    }
+  }
+
+The result will look like this:
+
+.. code-block:: javascript
+
+  {"total_rows":9,"offset":0,"rows":[
+  {"id":"3525ab874bc4965fa3cda7c549e92d30","key":"bike","value":null},
+  {"id":"3525ab874bc4965fa3cda7c549e92d30","key":"couchdb","value":null},
+  {"id":"53f82b1f0ff49a08ac79a9dff41d7860","key":"couchdb","value":null},
+  {"id":"da5ea89448a4506925823f4d985aabbd","key":"couchdb","value":null},
+  {"id":"3525ab874bc4965fa3cda7c549e92d30","key":"drums","value":null},
+  {"id":"53f82b1f0ff49a08ac79a9dff41d7860","key":"hypertext","value":null},
+  {"id":"da5ea89448a4506925823f4d985aabbd","key":"music","value":null},
+  {"id":"da5ea89448a4506925823f4d985aabbd","key":"mustache","value":null},
+  {"id":"53f82b1f0ff49a08ac79a9dff41d7860","key":"philosophy","value":null}
+  ]}
+
+As promised, these are all the tags, including duplicates. Since each document
+gets run through the map function in isolation, it cannot know if the same key
+has been emitted already. At this stage, we need to live with that. To achieve
+uniqueness, we need a reduce:
+
+.. code-block:: javascript
+
+  function(keys, values) {
+    return true;
+  }
+
+This reduce doesn’t do anything, but it allows us to specify a special query
+parameter when querying the view::
+
+  /dudes/_design/dude-data/_view/tags?group=true
+
+CouchDB replies:
+
+.. code-block:: javascript
+
+  {"rows":[
+  {"key":"bike","value":true},
+  {"key":"couchdb","value":true},
+  {"key":"drums","value":true},
+  {"key":"hypertext","value":true},
+  {"key":"music","value":true},
+  {"key":"mustache","value":true},
+  {"key":"philosophy","value":true}
+  ]}
+
+In this case, we can ignore the value part because it is always true, but the
+result includes a list of all our tags and no duplicates!
+
+With a small change we can put the reduce to good use, too. Let’s see how many
+of the non-unique tags are there for each tag. To calculate the tag frequency,
+we just use the summing up we already learned about. In the map function,
+we emit a 1 instead of null:
+
+.. code-block:: javascript
+
+  function(doc) {
+    if(doc.name && doc.tags) {
+      doc.tags.forEach(function(tag) {
+        emit(tag, 1);
+      });
+    }
+  }
+
+In the reduce function, we return the sum of all values:
+
+.. code-block:: javascript
+
+  function(keys, values) {
+    return sum(values);
+  }
+
+Now, if we query the view with the ``?group=true`` parameter, we get back the
+count for each tag:
+
+.. code-block:: javascript
+
+  {"rows":[
+  {"key":"bike","value":1},
+  {"key":"couchdb","value":3},
+  {"key":"drums","value":1},
+  {"key":"hypertext","value":1},
+  {"key":"music","value":1},
+  {"key":"mustache","value":1},
+  {"key":"philosophy","value":1}
+  ]}
+
+Enforcing Uniqueness
+====================
+
+How you would do this in SQL::
+
+  UNIQUE KEY(column)
+
+How you can do this in CouchDB?
+
+Use case: your applications require that a certain value exists only once in a
+database.
+
+This is an easy one: within a CouchDB database, each document must have a
+unique ``_id`` field. If you require unique values in a database, just assign
+them to a document’s ``_id`` field and CouchDB will enforce uniqueness for you.
+
+There’s one caveat, though: in the distributed case, when you are running more
+than one CouchDB node that accepts write requests, uniqueness can be guaranteed
+only per node or outside of CouchDB. CouchDB will allow two identical IDs to be
+written to two different nodes. On replication, CouchDB will detect a conflict
+and flag the document accordingly.


[11/50] [abbrv] Use singular name for article groups.

Posted by kx...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replications/conflicts.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/conflicts.rst b/share/doc/src/replications/conflicts.rst
deleted file mode 100644
index 404d256..0000000
--- a/share/doc/src/replications/conflicts.rst
+++ /dev/null
@@ -1,786 +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.
-
-
-.. _replication/conflicts:
-
-==============================
-Replication and conflict model
-==============================
-
-Let's take the following example to illustrate replication and conflict handling.
-
-- Alice has a document containing Bob's business card;
-- She synchronizes it between her desktop PC and her laptop;
-- On the desktop PC, she updates Bob's E-mail address;
-  Without syncing again, she updates Bob's mobile number on the laptop;
-- Then she replicates the two to each other again.
-
-So on the desktop the document has Bob's new E-mail address and his old mobile
-number, and on the laptop it has his old E-mail address and his new mobile
-number.
-
-The question is, what happens to these conflicting updated documents?
-
-CouchDB replication
-===================
-
-CouchDB works with JSON documents inside databases. Replication of databases
-takes place over HTTP, and can be either a "pull" or a "push", but is
-unidirectional. So the easiest way to perform a full sync is to do a "push"
-followed by a "pull" (or vice versa).
-
-So, Alice creates v1 and sync it. She updates to v2a on one side and v2b on the
-other, and then replicates. What happens?
-
-The answer is simple: both versions exist on both sides!
-
-.. code-block:: text
-
-     DESKTOP                          LAPTOP
-   +---------+
-   | /db/bob |                                     INITIAL
-   |   v1    |                                     CREATION
-   +---------+
-
-   +---------+                      +---------+
-   | /db/bob |  ----------------->  | /db/bob |     PUSH
-   |   v1    |                      |   v1    |
-   +---------+                      +---------+
-
-   +---------+                      +---------+  INDEPENDENT
-   | /db/bob |                      | /db/bob |     LOCAL
-   |   v2a   |                      |   v2b   |     EDITS
-   +---------+                      +---------+
-
-   +---------+                      +---------+
-   | /db/bob |  ----------------->  | /db/bob |     PUSH
-   |   v2a   |                      |   v2a   |
-   +---------+                      |   v2b   |
-                                    +---------+
-
-   +---------+                      +---------+
-   | /db/bob |  <-----------------  | /db/bob |     PULL
-   |   v2a   |                      |   v2a   |
-   |   v2b   |                      |   v2b   |
-   +---------+                      +---------+
-
-After all, this is not a filesystem, so there's no restriction that only one
-document can exist with the name /db/bob. These are just "conflicting" revisions
-under the same name.
-
-Because the changes are always replicated, the data is safe. Both machines have
-identical copies of both documents, so failure of a hard drive on either side
-won't lose any of the changes.
-
-Another thing to notice is that peers do not have to be configured or tracked.
-You can do regular replications to peers, or you can do one-off, ad-hoc pushes
-or pulls. After the replication has taken place, there is no record kept of
-which peer any particular document or revision came from.
-
-So the question now is: what happens when you try to read /db/bob? By default,
-CouchDB picks one arbitrary revision as the "winner", using a deterministic
-algorithm so that the same choice will be made on all peers. The same happens
-with views: the deterministically-chosen winner is the only revision fed into
-your map function.
-
-Let's say that the winner is v2a. On the desktop, if Alice reads the document
-she'll see v2a, which is what she saved there. But on the laptop, after
-replication, she'll also see only v2a. It could look as if the changes she made
-there have been lost - but of course they have not, they have just been hidden
-away as a conflicting revision. But eventually she'll need these changes merged
-into Bob's business card, otherwise they will effectively have been lost.
-
-Any sensible business-card application will, at minimum, have to present the
-conflicting versions to Alice and allow her to create a new version
-incorporating information from them all. Ideally it would merge the updates
-itself.
-
-Conflict avoidance
-==================
-
-When working on a single node, CouchDB will avoid creating conflicting revisions
-by returning a 409 HTTP error. This is because, when you PUT a new version of a
-document, you must give the ``_rev`` of the previous version. If that ``_rev``
-has already been superseded, the update is rejected with a ``HTTP 409 Conflict``.
-
-So imagine two users on the same node are fetching Bob's business card, updating
-it concurrently, and writing it back:
-
-.. code-block:: text
-
-  USER1    ----------->  GET /db/bob
-           <-----------  {"_rev":"1-aaa", ...}
-
-  USER2    ----------->  GET /db/bob
-           <-----------  {"_rev":"1-aaa", ...}
-
-  USER1    ----------->  PUT /db/bob?rev=1-aaa
-           <-----------  {"_rev":"2-bbb", ...}
-
-  USER2    ----------->  PUT /db/bob?rev=1-aaa
-           <-----------  409 Conflict  (not saved)
-
-User2's changes are rejected, so it's up to the app to fetch /db/bob again,
-and either:
-
-#. apply the same changes as were applied to the earlier revision, and submit
-   a new PUT
-#. redisplay the document so the user has to edit it again
-#. just overwrite it with the document being saved before (which is not
-   advisable, as user1's changes will be silently lost)
-
-So when working in this mode, your application still has to be able to handle
-these conflicts and have a suitable retry strategy, but these conflicts never
-end up inside the database itself.
-
-Conflicts in batches
-====================
-
-There are two different ways that conflicts can end up in the database:
-
-- Conflicting changes made on different databases, which are replicated to each
-  other, as shown earlier.
-- Changes are written to the database using ``_bulk_docs`` and all_or_nothing,
-  which bypasses the 409 mechanism.
-
-The :ref:`_bulk_docs API <api/db/bulk_docs>` lets you submit multiple updates
-(and/or deletes) in a single HTTP POST. Normally, these are treated as
-independent updates; some in the batch may fail because the `_rev` is stale
-(just like a 409 from a PUT) whilst others are written successfully.
-The response from ``_bulk_docs`` lists the success/fail separately for each
-document in the batch.
-
-However there is another mode of working, whereby you specify
-``{"all_or_nothing":true}`` as part of the request. This is CouchDB's nearest
-equivalent of a "transaction", but it's not the same as a database transaction
-which can fail and roll back. Rather, it means that all of the changes in the
-request will be forcibly applied to the database, even if that introduces
-conflicts. The only guarantee you are given is that they will either all be
-applied to the database, or none of them (e.g. if the power is pulled out before
-the update is finished writing to disk).
-
-So this gives you a way to introduce conflicts within a single database
-instance. If you choose to do this instead of PUT, it means you don't have to
-write any code for the possibility of getting a 409 response, because you will
-never get one. Rather, you have to deal with conflicts appearing later in the
-database, which is what you'd have to do in a multi-master application anyway.
-
-.. code-block:: http
-
-  POST /db/_bulk_docs
-
-.. code-block:: javascript
-
-  {
-    "all_or_nothing": true,
-    "docs": [
-      {"_id":"x", "_rev":"1-xxx", ...},
-      {"_id":"y", "_rev":"1-yyy", ...},
-      ...
-    ]
-  }
-
-Revision tree
-=============
-
-When you update a document in CouchDB, it keeps a list of the previous
-revisions. In the case where conflicting updates are introduced, this history
-branches into a tree, where the current conflicting revisions for this document
-form the tips (leaf nodes) of this tree:
-
-.. code-block:: text
-
-      ,--> r2a
-    r1 --> r2b
-      `--> r2c
-
-Each branch can then extend its history - for example if you read revision r2b
-and then PUT with ?rev=r2b then you will make a new revision along that
-particular branch.
-
-.. code-block:: text
-
-      ,--> r2a -> r3a -> r4a
-    r1 --> r2b -> r3b
-      `--> r2c -> r3c
-
-Here, (r4a, r3b, r3c) are the set of conflicting revisions. The way you resolve
-a conflict is to delete the leaf nodes along the other branches. So when you
-combine (r4a+r3b+r3c) into a single merged document, you would replace r4a and
-delete r3b and r3c.
-
-.. code-block:: text
-
-      ,--> r2a -> r3a -> r4a -> r5a
-    r1 --> r2b -> r3b -> (r4b deleted)
-      `--> r2c -> r3c -> (r4c deleted)
-
-Note that r4b and r4c still exist as leaf nodes in the history tree, but as
-deleted docs. You can retrieve them but they will be marked ``"_deleted":true``.
-
-When you compact a database, the bodies of all the non-leaf documents are
-discarded. However, the list of historical _revs is retained, for the benefit of
-later conflict resolution in case you meet any old replicas of the database at
-some time in future. There is "revision pruning" to stop this getting
-arbitrarily large.
-
-Working with conflicting documents
-==================================
-
-The basic :ref:`GET /db/bob <api/doc.get>` operation will not show you any
-information about conflicts. You see only the deterministically-chosen winner,
-and get no indication as to whether other conflicting revisions exist or not:
-
-.. code-block:: javascript
-
-  {
-    "_id":"test",
-    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
-    "hello":"bar"
-  }
-
-If you do ``GET /db/bob?conflicts=true``, and the document is in a conflict
-state, then you will get the winner plus a _conflicts member containing an array
-of the revs of the other, conflicting revision(s). You can then fetch them
-individually using subsequent ``GET /db/bob?rev=xxxx`` operations:
-
-.. code-block:: javascript
-
-  {
-    "_id":"test",
-    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
-    "hello":"bar",
-    "_conflicts":[
-      "2-65db2a11b5172bf928e3bcf59f728970",
-      "2-5bc3c6319edf62d4c624277fdd0ae191"
-    ]
-  }
-
-If you do ``GET /db/bob?open_revs=all`` then you will get all the leaf nodes of
-the revision tree. This will give you all the current conflicts, but will also
-give you leaf nodes which have been deleted (i.e. parts of the conflict history
-which have since been resolved). You can remove these by filtering out documents
-with ``"_deleted":true``:
-
-.. code-block:: javascript
-
-  [
-    {"ok":{"_id":"test","_rev":"2-5bc3c6319edf62d4c624277fdd0ae191","hello":"foo"}},
-    {"ok":{"_id":"test","_rev":"2-65db2a11b5172bf928e3bcf59f728970","hello":"baz"}},
-    {"ok":{"_id":"test","_rev":"2-b91bb807b4685080c6a651115ff558f5","hello":"bar"}}
-  ]
-
-The ``"ok"`` tag is an artifact of ``open_revs``, which also lets you list
-explicit revisions as a JSON array, e.g. ``open_revs=[rev1,rev2,rev3]``. In this
-form, it would be possible to request a revision which is now missing, because
-the database has been compacted.
-
-.. note::
-  The order of revisions returned by ``open_revs=all`` is **NOT** related to
-  the deterministic "winning" algorithm. In the above example, the winning
-  revision is 2-b91b... and happens to be returned last, but in other cases it
-  can be returned in a different position.
-
-Once you have retrieved all the conflicting revisions, your application can then
-choose to display them all to the user. Or it could attempt to merge them, write
-back the merged version, and delete the conflicting versions - that is, to
-resolve the conflict permanently.
-
-As described above, you need to update one revision and delete all the
-conflicting revisions explicitly. This can be done using a single `POST` to
-``_bulk_docs``, setting ``"_deleted":true`` on those revisions you wish to
-delete.
-
-Multiple document API
-=====================
-
-You can fetch multiple documents at once using ``include_docs=true`` on a view.
-However, a ``conflicts=true`` request is ignored; the "doc" part of the value
-never includes a ``_conflicts`` member. Hence you would need to do another query
-to determine for each document whether it is in a conflicting state:
-
-.. code-block:: bash
-
-  $ curl 'http://127.0.0.1:5984/conflict_test/_all_docs?include_docs=true&conflicts=true'
-
-.. code-block:: javascript
-
-  {
-    "total_rows":1,
-    "offset":0,
-    "rows":[
-      {
-        "id":"test",
-        "key":"test",
-        "value":{"rev":"2-b91bb807b4685080c6a651115ff558f5"},
-        "doc":{
-          "_id":"test",
-          "_rev":"2-b91bb807b4685080c6a651115ff558f5",
-          "hello":"bar"
-        }
-      }
-    ]
-  }
-
-.. code-block:: bash
-
-  $ curl 'http://127.0.0.1:5984/conflict_test/test?conflicts=true'
-
-.. code-block:: javascript
-
-  {
-    "_id":"test",
-    "_rev":"2-b91bb807b4685080c6a651115ff558f5",
-    "hello":"bar",
-    "_conflicts":[
-      "2-65db2a11b5172bf928e3bcf59f728970",
-      "2-5bc3c6319edf62d4c624277fdd0ae191"
-    ]
-  }
-
-View map functions
-==================
-
-Views only get the winning revision of a document. However they do also get a
-``_conflicts`` member if there are any conflicting revisions. This means you can
-write a view whose job is specifically to locate documents with conflicts.
-Here is a simple map function which achieves this:
-
-.. code-block:: javascript
-
-  function(doc) {
-    if (doc._conflicts) {
-      emit(null, [doc._rev].concat(doc._conflicts));
-    }
-  }
-
-which gives the following output:
-
-.. code-block:: javascript
-
-  {
-    "total_rows":1,
-    "offset":0,
-    "rows":[
-      {
-        "id":"test",
-        "key":null,
-        "value":[
-          "2-b91bb807b4685080c6a651115ff558f5",
-          "2-65db2a11b5172bf928e3bcf59f728970",
-          "2-5bc3c6319edf62d4c624277fdd0ae191"
-        ]
-      }
-    ]
-  }
-
-If you do this, you can have a separate "sweep" process which periodically scans
-your database, looks for documents which have conflicts, fetches the conflicting
-revisions, and resolves them.
-
-Whilst this keeps the main application simple, the problem with this approach is
-that there will be a window between a conflict being introduced and it being
-resolved. From a user's viewpoint, this may appear that the document they just
-saved successfully may suddenly lose their changes, only to be resurrected some
-time later. This may or may not be acceptable.
-
-Also, it's easy to forget to start the sweeper, or not to implement it properly,
-and this will introduce odd behaviour which will be hard to track down.
-
-CouchDB's "winning" revision algorithm may mean that information drops out of a
-view until a conflict has been resolved. Consider Bob's business card again;
-suppose Alice has a view which emits mobile numbers, so that her telephony
-application can display the caller's name based on caller ID. If there are
-conflicting documents with Bob's old and new mobile numbers, and they happen to
-be resolved in favour of Bob's old number, then the view won't be able to
-recognise his new one. In this particular case, the application might have
-preferred to put information from both the conflicting documents into the view,
-but this currently isn't possible.
-
-Suggested algorithm to fetch a document with conflict resolution:
-
-#. Get document via ``GET docid?conflicts=true`` request;
-#. For each member in the ``_conflicts`` array call ``GET docid?rev=xxx``.
-   If any errors occur at this stage, restart from step 1.
-   (There could be a race where someone else has already resolved this conflict
-   and deleted that rev)
-#. Perform application-specific merging
-#. Write ``_bulk_docs`` with an update to the first rev and deletes of the other
-   revs.
-
-This could either be done on every read (in which case you could replace all
-calls to GET in your application with calls to a library which does the above),
-or as part of your sweeper code.
-
-And here is an example of this in Ruby using the low-level `RestClient`_:
-
-.. _RestClient: https://rubygems.org/gems/rest-client
-
-.. code-block:: ruby
-
-  require 'rubygems'
-  require 'rest_client'
-  require 'json'
-  DB="http://127.0.0.1:5984/conflict_test"
-
-  # Write multiple documents as all_or_nothing, can introduce conflicts
-  def writem(docs)
-    JSON.parse(RestClient.post("#{DB}/_bulk_docs", {
-      "all_or_nothing" => true,
-      "docs" => docs,
-    }.to_json))
-  end
-
-  # Write one document, return the rev
-  def write1(doc, id=nil, rev=nil)
-    doc['_id'] = id if id
-    doc['_rev'] = rev if rev
-    writem([doc]).first['rev']
-  end
-
-  # Read a document, return *all* revs
-  def read1(id)
-    retries = 0
-    loop do
-      # FIXME: escape id
-      res = [JSON.parse(RestClient.get("#{DB}/#{id}?conflicts=true"))]
-      if revs = res.first.delete('_conflicts')
-        begin
-          revs.each do |rev|
-            res << JSON.parse(RestClient.get("#{DB}/#{id}?rev=#{rev}"))
-          end
-        rescue
-          retries += 1
-          raise if retries >= 5
-          next
-        end
-      end
-      return res
-    end
-  end
-
-  # Create DB
-  RestClient.delete DB rescue nil
-  RestClient.put DB, {}.to_json
-
-  # Write a document
-  rev1 = write1({"hello"=>"xxx"},"test")
-  p read1("test")
-
-  # Make three conflicting versions
-  write1({"hello"=>"foo"},"test",rev1)
-  write1({"hello"=>"bar"},"test",rev1)
-  write1({"hello"=>"baz"},"test",rev1)
-
-  res = read1("test")
-  p res
-
-  # Now let's replace these three with one
-  res.first['hello'] = "foo+bar+baz"
-  res.each_with_index do |r,i|
-    unless i == 0
-      r.replace({'_id'=>r['_id'], '_rev'=>r['_rev'], '_deleted'=>true})
-    end
-  end
-  writem(res)
-
-  p read1("test")
-
-An application written this way never has to deal with a ``PUT 409``, and is
-automatically multi-master capable.
-
-You can see that it's straightforward enough when you know what you're doing.
-It's just that CouchDB doesn't currently provide a convenient HTTP API for
-"fetch all conflicting revisions", nor "PUT to supersede these N revisions", so
-you need to wrap these yourself. I also don't know of any client-side libraries
-which provide support for this.
-
-Merging and revision history
-============================
-
-Actually performing the merge is an application-specific function. It depends
-on the structure of your data. Sometimes it will be easy: e.g. if a document
-contains a list which is only ever appended to, then you can perform a union of
-the two list versions.
-
-Some merge strategies look at the changes made to an object, compared to its
-previous version. This is how git's merge function works.
-
-For example, to merge Bob's business card versions v2a and v2b, you could look
-at the differences between v1 and v2b, and then apply these changes to v2a as
-well.
-
-With CouchDB, you can sometimes get hold of old revisions of a document.
-For example, if you fetch ``/db/bob?rev=v2b&revs_info=true`` you'll get a list
-of the previous revision ids which ended up with revision v2b. Doing the same
-for v2a you can find their common ancestor revision. However if the database
-has been compacted, the content of that document revision will have been lost.
-``revs_info`` will still show that v1 was an ancestor, but report it as
-"missing"::
-
-  BEFORE COMPACTION           AFTER COMPACTION
-
-       ,-> v2a                     v2a
-     v1
-       `-> v2b                     v2b
-
-So if you want to work with diffs, the recommended way is to store those diffs
-within the new revision itself. That is: when you replace v1 with v2a, include
-an extra field or attachment in v2a which says which fields were changed from
-v1 to v2a. This unfortunately does mean additional book-keeping for your
-application.
-
-Comparison with other replicating data stores
-=============================================
-
-The same issues arise with other replicating systems, so it can be instructive
-to look at these and see how they compare with CouchDB. Please feel free to add
-other examples.
-
-Unison
-------
-
-`Unison`_ is a bi-directional file synchronisation tool. In this case, the
-business card would be a file, say `bob.vcf`.
-
-.. _Unison: http://www.cis.upenn.edu/~bcpierce/unison/
-
-When you run unison, changes propagate both ways. If a file has changed on one
-side but not the other, the new replaces the old. Unison maintains a local state
-file so that it knows whether a file has changed since the last successful
-replication.
-
-In our example it has changed on both sides. Only one file called `bob.vcf`
-can exist within the filesystem. Unison solves the problem by simply ducking
-out: the user can choose to replace the remote version with the local version,
-or vice versa (both of which would lose data), but the default action is to
-leave both sides unchanged.
-
-From Alice's point of view, at least this is a simple solution. Whenever she's
-on the desktop she'll see the version she last edited on the desktop, and
-whenever she's on the laptop she'll see the version she last edited there.
-
-But because no replication has actually taken place, the data is not protected.
-If her laptop hard drive dies, she'll lose all her changes made on the laptop;
-ditto if her desktop hard drive dies.
-
-It's up to her to copy across one of the versions manually (under a different
-filename), merge the two, and then finally push the merged version to the other
-side.
-
-Note also that the original file (version v1) has been lost by this point.
-So it's not going to be known from inspection alone which of v2a and v2b has the
-most up-to-date E-mail address for Bob, and which has the most up-to-date mobile
-number. Alice has to remember which she entered last.
-
-
-Git
-----
-
-`Git`_ is a well-known distributed source control system. Like Unison, git deals
-with files. However, git considers the state of a whole set of files as a single
-object, the "tree". Whenever you save an update, you create a "commit" which
-points to both the updated tree and the previous commit(s), which in turn point
-to the previous tree(s). You therefore have a full history of all the states of
-the files. This forms a branch, and a pointer is kept to the tip of the branch,
-from which you can work backwards to any previous state. The "pointer" is
-actually an SHA1 hash of the tip commit.
-
-.. _Git: http://git-scm.com/
-
-If you are replicating with one or more peers, a separate branch is made for
-each of the peers. For example, you might have::
-
-    master               -- my local branch
-    remotes/foo/master   -- branch on peer 'foo'
-    remotes/bar/master   -- branch on peer 'bar'
-
-In the normal way of working, replication is a "pull", importing changes from
-a remote peer into the local repository. A "pull" does two things: first "fetch"
-the state of the peer into the remote tracking branch for that peer; and then
-attempt to "merge" those changes into the local branch.
-
-Now let's consider the business card. Alice has created a git repo containing
-``bob.vcf``, and cloned it across to the other machine. The branches look like
-this, where ``AAAAAAAA`` is the SHA1 of the commit::
-
-  ---------- desktop ----------           ---------- laptop ----------
-  master: AAAAAAAA                        master: AAAAAAAA
-  remotes/laptop/master: AAAAAAAA         remotes/desktop/master: AAAAAAAA
-
-Now she makes a change on the desktop, and commits it into the desktop repo;
-then she makes a different change on the laptop, and commits it into the laptop
-repo::
-
-  ---------- desktop ----------           ---------- laptop ----------
-  master: BBBBBBBB                        master: CCCCCCCC
-  remotes/laptop/master: AAAAAAAA         remotes/desktop/master: AAAAAAAA
-
-Now on the desktop she does ``git pull laptop``. Firstly, the remote objects
-are copied across into the local repo and the remote tracking branch is
-updated::
-
-  ---------- desktop ----------           ---------- laptop ----------
-  master: BBBBBBBB                        master: CCCCCCCC
-  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: AAAAAAAA
-
-.. note::
-  repo still contains AAAAAAAA because commits BBBBBBBB and CCCCCCCC point to it
-
-Then git will attempt to merge the changes in. It can do this because it knows
-the parent commit to ``CCCCCCCC`` is ``AAAAAAAA``, so it takes a diff between
-``AAAAAAAA`` and ``CCCCCCCC`` and tries to apply it to ``BBBBBBBB``.
-
-If this is successful, then you'll get a new version with a merge commit::
-
-  ---------- desktop ----------           ---------- laptop ----------
-  master: DDDDDDDD                        master: CCCCCCCC
-  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: AAAAAAAA
-
-Then Alice has to logon to the laptop and run ``git pull desktop``. A similar
-process occurs. The remote tracking branch is updated::
-
-  ---------- desktop ----------           ---------- laptop ----------
-  master: DDDDDDDD                        master: CCCCCCCC
-  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: DDDDDDDD
-
-Then a merge takes place. This is a special-case: ``CCCCCCCC`` one of the parent
-commits of ``DDDDDDDD``, so the laptop can `fast forward` update from
-``CCCCCCCC`` to ``DDDDDDDD`` directly without having to do any complex merging.
-This leaves the final state as::
-
-  ---------- desktop ----------           ---------- laptop ----------
-  master: DDDDDDDD                        master: DDDDDDDD
-  remotes/laptop/master: CCCCCCCC         remotes/desktop/master: DDDDDDDD
-
-Now this is all and good, but you may wonder how this is relevant when thinking
-about CouchDB.
-
-Firstly, note what happens in the case when the merge algorithm fails.
-The changes are still propagated from the remote repo into the local one, and
-are available in the remote tracking branch; so unlike Unison, you know the data
-is protected. It's just that the local working copy may fail to update, or may
-diverge from the remote version. It's up to you to create and commit the
-combined version yourself, but you are guaranteed to have all the history you
-might need to do this.
-
-Note that whilst it's possible to build new merge algorithms into Git,
-the standard ones are focused on line-based changes to source code. They don't
-work well for XML or JSON if it's presented without any line breaks.
-
-The other interesting consideration is multiple peers. In this case you have
-multiple remote tracking branches, some of which may match your local branch,
-some of which may be behind you, and some of which may be ahead of you
-(i.e. contain changes that you haven't yet merged)::
-
-  master: AAAAAAAA
-  remotes/foo/master: BBBBBBBB
-  remotes/bar/master: CCCCCCCC
-  remotes/baz/master: AAAAAAAA
-
-Note that each peer is explicitly tracked, and therefore has to be explicitly
-created. If a peer becomes stale or is no longer needed, it's up to you to
-remove it from your configuration and delete the remote tracking branch.
-This is different to CouchDB, which doesn't keep any peer state in the database.
-
-Another difference with git is that it maintains all history back to time
-zero - git compaction keeps diffs between all those versions in order to reduce
-size, but CouchDB discards them. If you are constantly updating a document,
-the size of a git repo would grow forever. It is possible (with some effort)
-to use "history rewriting" to make git forget commits earlier than a particular
-one.
-
-
-What is the CouchDB replication protocol? Is it like Git?
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-**Key points**
-
-**If you know Git, then you know how Couch replication works.** Replicating is
-*very* similar to pushing or pulling with distributed source managers like Git.
-
-**CouchDB replication does not have its own protocol.** A replicator simply
-connects to two DBs as a client, then reads from one and writes to the other.
-Push replication is reading the local data and updating the remote DB;
-pull replication is vice versa.
-
-* **Fun fact 1**: The replicator is actually an independent Erlang application,
-  in its own process. It connects to both couches, then reads records from one
-  and writes them to the other.
-* **Fun fact 2**: CouchDB has no way of knowing who is a normal client and who
-  is a replicator (let alone whether the replication is push or pull).
-  It all looks like client connections. Some of them read records. Some of them
-  write records.
-
-**Everything flows from the data model**
-
-The replication algorithm is trivial, uninteresting. A trained monkey could
-design it. It's simple because the cleverness is the data model, which has these
-useful characteristics:
-
-#. Every record in CouchDB is completely independent of all others. That sucks
-   if you want to do a JOIN or a transaction, but it's awesome if you want to
-   write a replicator. Just figure out how to replicate one record, and then
-   repeat that for each record.
-#. Like Git, records have a linked-list revision history. A record's revision ID
-   is the checksum of its own data. Subsequent revision IDs are checksums of:
-   the new data, plus the revision ID of the previous.
-
-#. In addition to application data (``{"name": "Jason", "awesome": true}``),
-   every record stores the evolutionary timeline of all previous revision IDs
-   leading up to itself.
-
-   - Exercise: Take a moment of quiet reflection. Consider any two different
-     records, A and B. If A's revision ID appears in B's timeline, then B
-     definitely evolved from A. Now consider Git's fast-forward merges.
-     Do you hear that? That is the sound of your mind being blown.
-
-#. Git isn't really a linear list. It has forks, when one parent has multiple
-   children. CouchDB has that too.
-
-   - Exercise: Compare two different records, A and B. A's revision ID does not
-     appear in B's timeline; however, one revision ID, C, is in both A's and B's
-     timeline. Thus A didn't evolve from B. B didn't evolve from A. But rather,
-     A and B have a common ancestor C. In Git, that is a "fork." In CouchDB,
-     it's a "conflict."
-
-   - In Git, if both children go on to develop their timelines independently,
-     that's cool. Forks totally support that.
-   - In CouchDB, if both children go on to develop their timelines
-     independently, that cool too. Conflicts totally support that.
-   - **Fun fact 3**: CouchDB "conflicts" do not correspond to Git "conflicts."
-     A Couch conflict is a divergent revision history, what Git calls a "fork."
-     For this reason the CouchDB community pronounces "conflict" with a silent
-     `n`: "co-flicked."
-
-#. Git also has merges, when one child has multiple parents. CouchDB *sort* of
-   has that too.
-
-   - **In the data model, there is no merge.** The client simply marks one
-     timeline as deleted and continues to work with the only extant timeline.
-   - **In the application, it feels like a merge.** Typically, the client merges
-     the *data* from each timeline in an application-specific way.
-     Then it writes the new data to the timeline. In Git, this is like copying
-     and pasting the changes from branch A into branch B, then commiting to
-     branch B and deleting branch A. The data was merged, but there was no
-     `git merge`.
-   - These behaviors are different because, in Git, the timeline itself is
-     important; but in CouchDB, the data is important and the timeline is
-     incidental—it's just there to support replication. That is one reason why
-     CouchDB's built-in revisioning is inappropriate for storing revision data
-     like a wiki page.
-
-**Final notes**
-
-At least one sentence in this writeup (possibly this one) is complete BS.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replications/index.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/index.rst b/share/doc/src/replications/index.rst
deleted file mode 100644
index 1dec453..0000000
--- a/share/doc/src/replications/index.rst
+++ /dev/null
@@ -1,37 +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.
-
-.. _replication:
-
-================
-Data Replication
-================
-
-The replication is an incremental one way process involving two databases
-(a source and a destination).
-
-The aim of the replication is that at the end of the process, all active
-documents on the source database are also in the destination database and all
-documents that were deleted in the source databases are also deleted (if exists)
-on the destination database.
-
-The replication process only copies the last revision of a document, so all
-previous revisions that were only on the source database are not copied to the
-destination database.
-
-.. toctree::
-   :maxdepth: 2
-
-   intro
-   replicator
-   conflicts
-   protocol

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replications/intro.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/intro.rst b/share/doc/src/replications/intro.rst
deleted file mode 100644
index f9c81e2..0000000
--- a/share/doc/src/replications/intro.rst
+++ /dev/null
@@ -1,95 +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.
-
-.. _replication/intro:
-
-Introduction Into Replications
-==============================
-
-One of CouchDB's strengths is the ability to synchronize two copies of the same
-database. This enables users to distribute data across several nodes or
-datacenters, but also to move data more closely to clients.
-
-Replication involves a source and a destination database, which can be one the
-same or on different CouchDB instances. The aim of the replication is that at
-the end of the process, all active documents on the source database are also in
-the destination database and all documents that were deleted in the source
-databases are also deleted on the destination database (if they even existed).
-
-
-Triggering Replication
-----------------------
-
-Replication is controlled through documents in the :ref:`replicator`, where
-each document describes one replication process (see
-:ref:`replication-settings`).
-
-A replication is triggered by storing a replication document in the replicator
-database. Its status can be inspected through the active tasks API (see
-:ref:`api/misc/active_tasks` and :ref:`replication-status`). A replication can be
-stopped by deleting the document, or by updating it with its `cancel` property
-set to `true`.
-
-
-Replication Procedure
----------------------
-
-During replication, CouchDB will compare the source and the destination
-database to determine which documents differ between the source and the
-destination database. It does so by following the :ref:`changes` on the source
-and comparing the documents to the destination. Changes are submitted to the
-destination in batches where they can introduce conflicts. Documents that
-already exist on the destination in the same revision are not transferred. As
-the deletion of documents is represented by a new revision, a document deleted
-on the source will also be deleted on the target.
-
-A replication task will finish once it reaches the end of the changes feed. If
-its `continuous` property is set to true, it will wait for new changes to
-appear until the task is cancelled. Replication tasks also create checkpoint
-documents on the destination to ensure that a restarted task can continue from
-where it stopped, for example after it has crashed.
-
-When a replication task is initiated on the sending node, it is called *push*
-replication, if it is initiated by the receiving node, it is called *pull*
-replication.
-
-
-Master - Master replication
----------------------------
-
-One replication task will only transfer changes in one direction. To achieve
-master-master replication it is possible to set up two replication tasks in
-different directions. When a change is replication from database A to B by the
-first task, the second will discover that the new change on B already exists in
-A and will wait for further changes.
-
-
-Controlling which Documents to Replicate
-----------------------------------------
-
-There are two ways for controlling which documents are replicated, and which
-are skipped. *Local* documents are never replicated (see :ref:`api/local`).
-
-Additionally, :ref:`filterfun` can be used in a replication documents (see
-:ref:`replication-settings`). The replication task will then evaluate
-the filter function for each document in the changes feed. The document will
-only be replicated if the filter returns `true`.
-
-
-Migrating Data to Clients
--------------------------
-
-Replication can be especially useful for bringing data closer to clients.
-`PouchDB <http://pouchdb.com/>`_ implements the replication algorithm of CouchDB
-in JavaScript, making it possible to make data from a CouchDB database
-available in an offline browser application, and synchronize changes back to
-CouchDB.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replications/protocol.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/protocol.rst b/share/doc/src/replications/protocol.rst
deleted file mode 100644
index bf478f7..0000000
--- a/share/doc/src/replications/protocol.rst
+++ /dev/null
@@ -1,201 +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.
-
-.. _replication/protocol:
-
-============================
-CouchDB Replication Protocol
-============================
-
-The **CouchDB Replication protocol** is a protocol for synchronizing
-documents between 2 peers over HTTP/1.1.
-
-Language
---------
-
-The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
-"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
-document are to be interpreted as described in :rfc:`2119`.
-
-
-Goals
------
-
-The CouchDB Replication protocol is a synchronization protocol for
-synchronizing documents between 2 peers over HTTP/1.1.
-
-In theory the CouchDB protocol can be used between products that
-implement it. However the reference implementation, written in Erlang_, is
-provided by the couch_replicator_ module available in Apache CouchDB.
-
-
-The CouchDB_ replication protocol is using the `CouchDB REST API
-<http://wiki.apache.org/couchdb/Reference>`_ and so is based on HTTP and
-the Apache CouchDB MVC Data model. The primary goal of this
-specification is to describe the CouchDB replication algorithm.
-
-
-Definitions
------------
-
-ID:
-    An identifier (could be an UUID) as described in :rfc:`4122`
-
-Sequence:
-    An ID provided by the changes feed. It can be numeric but not
-    necessarily.
-
-Revision:
-    (to define)
-
-Document
-    A document is JSON entity with a unique ID and revision.
-
-Database
-    A collection of documents with a unique URI
-
-URI
-    An uri is defined by the :rfc:`2396` . It can be an URL as defined
-    in :rfc:`1738`.
-
-Source
-    Database from where the Documents are replicated
-
-Target
-    Database where the Document are replicated
-
-Checkpoint
-    Last source sequence ID
-
-
-Algorithm
----------
-
-1. Get unique identifiers for the Source and Target based on their URI if
-   replication task ID is not available.
-
-2. Save this identifier in a special Document named `_local/<uniqueid>`
-   on the Target database. This document isn't replicated. It will
-   collect the last Source sequence ID, the Checkpoint, from the
-   previous replication process.
-
-3. Get the Source changes feed by passing it the Checkpoint using the
-   `since` parameter by calling the `/<source>/_changes` URL. The
-   changes feed only return a list of current revisions.
-
-
-.. note::
-
-    This step can be done continuously using the `feed=longpoll` or
-    `feed=continuous` parameters. Then the feed will continuously get
-    the changes.
-
-
-4. Collect a group of Document/Revisions ID pairs from the **changes
-   feed** and send them to the target databases on the
-   `/<target>/_revs_diffs` URL. The result will contain the list of
-   revisions **NOT** in the Target.
-
-5. GET each revisions from the source Database by calling the URL
-   `/<source>/<docid>?revs=true&open_revs`=<revision>` . This
-   will get the document with teh parent revisions. Also don't forget to
-   get attachments that aren't already stored at the target. As an
-   optimisation you can use the HTTP multipart api to get all.
-
-6. Collect a group of revisions fetched at previous step and store them
-   on the target database using the `Bulk Docs
-   <http://wiki.apache.org/couchdb/HTTP_Document_API#Bulk_Docs>`_ API
-   with the `new_edit: false` JSON property to preserve their revisions
-   ID.
-
-7. After the group of revision is stored on the Target, save
-   the new Checkpoint on the Source.
-
-
-.. note::
-
-    - Even if some revisions have been ignored the sequence should be
-      take in consideration for the Checkpoint.
-
-    - To compare non numeric sequence ordering, you will have to keep an
-      ordered list of the sequences IDS as they appear in the _changes
-      feed and compare their indices.
-
-Filter replication
-------------------
-
-The replication can be filtered by passing the `filter` parameter to the
-changes feeds with a function name. This will call a function on each
-changes. If this function return True, the document will be added to the
-feed.
-
-
-Optimisations
--------------
-
-- The system should run each steps in parallel to reduce the latency.
-
-- The number of revisions passed to the step 3 and 6 should be large
-  enough to reduce the bandwidth and make sure to reduce the latency.
-
-
-API Reference
--------------
-
-- :ref:`api/db.head` -- Check Database existence
-- :ref:`api/db/ensure_full_commit` -- Ensure that all changes are stored on disk
-- :ref:`api/local/doc.get` -- Read the last Checkpoint
-- :ref:`api/local/doc.put` -- Save a new Checkpoint
-
-Push Only
-~~~~~~~~~
-
-- :ref:`api/db.put` -- Create Target if it not exists and option was provided
-- :ref:`api/db/revs_diff.post` -- Locate Revisions that are not known to the
-  Target
-- :ref:`api/db/bulk_docs.post` -- Upload Revisions to the Target
-- :ref:`api/doc.put`?new_edits=false -- Upload a single Document with
-  attachments to the Target
-
-Pull Only
-~~~~~~~~~
-
-- :ref:`api/db/changes.get` -- Locate changes since on Source the last pull.
-  The request uses next query parameters:
-
-  - ``style=all_docs``
-  - ``feed=feed`` , where feed is :ref:`normal <changes/normal>` or
-    :ref:`longpoll <changes/longpoll>`
-  - ``limit=limit``
-  - ``heartbeat=heartbeat``
-
-- :ref:`api/doc.get` -- Retrieve a single Document from Source with attachments.
-  The request uses next query parameters:
-
-  - ``open_revs=revid`` - where ``revid`` is the actual Document Revision at the
-    moment of the pull request
-  - ``revs=true``
-  - ``atts_since=lastrev``
-
-Reference
----------
-
-* `TouchDB Ios wiki <https://github.com/couchbaselabs/TouchDB-iOS/wiki/Replication-Algorithm>`_
-* `CouchDB documentation
-  <http://wiki.apache.org/couchdb/Replication>`_
-* CouchDB `change notifications`_
-
-.. _CouchDB: http://couchdb.apache.org
-.. _Erlang: http://erlang.org
-.. _couch_replicator: https://github.com/apache/couchdb/tree/master/src/couch_replicator
-.. _change notifications: http://guide.couchdb.org/draft/notifications.html
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/391bea7a/share/doc/src/replications/replicator.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/replications/replicator.rst b/share/doc/src/replications/replicator.rst
deleted file mode 100644
index 1a40c65..0000000
--- a/share/doc/src/replications/replicator.rst
+++ /dev/null
@@ -1,383 +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.
-
-.. _replicator:
-
-Replicator Database
-===================
-
-A database where you ``PUT``/``POST`` documents to trigger replications
-and you ``DELETE`` to cancel ongoing replications. These documents have
-exactly the same content as the JSON objects we used to ``POST`` to
-``_replicate`` (fields ``source``, ``target``, ``create_target``,
-``continuous``, ``doc_ids``, ``filter``, ``query_params``.
-
-Replication documents can have a user defined ``_id``. Design documents
-(and ``_local`` documents) added to the replicator database are ignored.
-
-The default name of this database is ``_replicator``. The name can be
-changed in the ``local.ini`` configuration, section ``[replicator]``,
-parameter ``db``.
-
-Basics
-------
-
-Let's say you PUT the following document into ``_replicator``:
-
-.. code-block:: javascript
-
-    {
-        "_id": "my_rep",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "create_target":  true
-    }
-
-In the couch log you'll see 2 entries like these:
-
-.. code-block:: text
-
-    [Thu, 17 Feb 2011 19:43:59 GMT] [info] [<0.291.0>] Document `my_rep` triggered replication `c0ebe9256695ff083347cbf95f93e280+create_target`
-    [Thu, 17 Feb 2011 19:44:37 GMT] [info] [<0.124.0>] Replication `c0ebe9256695ff083347cbf95f93e280+create_target` finished (triggered by document `my_rep`)
-
-As soon as the replication is triggered, the document will be updated by
-CouchDB with 3 new fields:
-
-.. code-block:: javascript
-
-    {
-        "_id": "my_rep",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "create_target":  true,
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297974122
-    }
-
-Special fields set by the replicator start with the prefix
-``_replication_``.
-
--  ``_replication_id``
-
-   The ID internally assigned to the replication. This is also the ID
-   exposed by ``/_active_tasks``.
-
--  ``_replication_state``
-
-   The current state of the replication.
-
--  ``_replication_state_time``
-
-   A Unix timestamp (number of seconds since 1 Jan 1970) that tells us
-   when the current replication state (marked in ``_replication_state``)
-   was set.
-
-When the replication finishes, it will update the ``_replication_state``
-field (and ``_replication_state_time``) with the value ``completed``, so
-the document will look like:
-
-.. code-block:: javascript
-
-    {
-        "_id": "my_rep",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "create_target":  true,
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "completed",
-        "_replication_state_time":  1297974122
-    }
-
-When an error happens during replication, the ``_replication_state``
-field is set to ``error`` (and ``_replication_state_time`` gets updated of
-course).
-
-When you PUT/POST a document to the ``_replicator`` database, CouchDB
-will attempt to start the replication up to 10 times (configurable under
-``[replicator]``, parameter ``max_replication_retry_count``). If it
-fails on the first attempt, it waits 5 seconds before doing a second
-attempt. If the second attempt fails, it waits 10 seconds before doing a
-third attempt. If the third attempt fails, it waits 20 seconds before
-doing a fourth attempt (each attempt doubles the previous wait period).
-When an attempt fails, the Couch log will show you something like:
-
-.. code-block:: text
-
-    [error] [<0.149.0>] Error starting replication `67c1bb92010e7abe35d7d629635f18b6+create_target` (document `my_rep_2`): {db_not_found,<<"could not open http://myserver:5986/foo/">>
-
-.. note::
-   The ``_replication_state`` field is only set to ``error`` when all
-   the attempts were unsuccessful.
-
-There are only 3 possible values for the ``_replication_state`` field:
-``triggered``, ``completed`` and ``error``. Continuous replications
-never get their state set to ``completed``.
-
-Documents describing the same replication
------------------------------------------
-
-Lets suppose 2 documents are added to the ``_replicator`` database in
-the following order:
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_A",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar"
-    }
-
-and
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_B",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar"
-    }
-
-Both describe exactly the same replication (only their ``_ids`` differ).
-In this case document ``doc_A`` triggers the replication, getting
-updated by CouchDB with the fields ``_replication_state``,
-``_replication_state_time`` and ``_replication_id``, just like it was
-described before. Document ``doc_B`` however, is only updated with one
-field, the ``_replication_id`` so it will look like this:
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_B",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280"
-    }
-
-While document ``doc_A`` will look like this:
-
-.. code-block:: javascript
-
-    {
-        "_id": "doc_A",
-        "source":  "http://myserver.com:5984/foo",
-        "target":  "bar",
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297974122
-    }
-
-Note that both document get exactly the same value for the
-``_replication_id`` field. This way you can identify which documents
-refer to the same replication - you can for example define a view which
-maps replication IDs to document IDs.
-
-Canceling replications
-----------------------
-
-To cancel a replication simply ``DELETE`` the document which triggered
-the replication. The Couch log will show you an entry like the
-following:
-
-.. code-block:: text
-
-    [Thu, 17 Feb 2011 20:16:29 GMT] [info] [<0.125.0>] Stopped replication `c0ebe9256695ff083347cbf95f93e280+continuous+create_target` because replication document `doc_A` was deleted
-
-.. note::
-   You need to ``DELETE`` the document that triggered the replication.
-   ``DELETE``-ing another document that describes the same replication
-   but did not trigger it, will not cancel the replication.
-
-Server restart
---------------
-
-When CouchDB is restarted, it checks its ``_replicator`` database and
-restarts any replication that is described by a document that either has
-its ``_replication_state`` field set to ``triggered`` or it doesn't have
-yet the ``_replication_state`` field set.
-
-.. note::
-   Continuous replications always have a ``_replication_state`` field
-   with the value ``triggered``, therefore they're always restarted
-   when CouchDB is restarted.
-
-Changing the Replicator Database
---------------------------------
-
-Imagine your replicator database (default name is ``_replicator``) has the
-two following documents that represent pull replications from servers A
-and B:
-
-.. code-block:: javascript
-
-    {
-        "_id": "rep_from_A",
-        "source":  "http://aserver.com:5984/foo",
-        "target":  "foo_a",
-        "continuous":  true,
-        "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297971311
-    }
-
-.. code-block:: javascript
-
-    {
-        "_id": "rep_from_B",
-        "source":  "http://bserver.com:5984/foo",
-        "target":  "foo_b",
-        "continuous":  true,
-        "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
-        "_replication_state":  "triggered",
-        "_replication_state_time":  1297974122
-    }
-
-Now without stopping and restarting CouchDB, you change the name of the
-replicator database to ``another_replicator_db``:
-
-.. code-block:: bash
-
-    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"another_replicator_db"'
-    "_replicator"
-
-As soon as this is done, both pull replications defined before, are
-stopped. This is explicitly mentioned in CouchDB's log:
-
-.. code-block:: text
-
-    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.104.0>] Stopping all ongoing replications because the replicator database was deleted or changed
-    [Fri, 11 Mar 2011 07:44:20 GMT] [info] [<0.127.0>] 127.0.0.1 - - PUT /_config/replicator/db 200
-
-Imagine now you add a replication document to the new replicator
-database named ``another_replicator_db``:
-
-.. code-block:: javascript
-
-    {
-        "_id": "rep_from_X",
-        "source":  "http://xserver.com:5984/foo",
-        "target":  "foo_x",
-        "continuous":  true
-    }
-
-From now own you have a single replication going on in your system: a
-pull replication pulling from server X. Now you change back the
-replicator database to the original one ``_replicator``:
-
-::
-
-    $ curl -X PUT http://localhost:5984/_config/replicator/db -d '"_replicator"'
-    "another_replicator_db"
-
-Immediately after this operation, the replication pulling from server X
-will be stopped and the replications defined in the ``_replicator``
-database (pulling from servers A and B) will be resumed.
-
-Changing again the replicator database to ``another_replicator_db`` will
-stop the pull replications pulling from servers A and B, and resume the
-pull replication pulling from server X.
-
-Replicating the replicator database
------------------------------------
-
-Imagine you have in server C a replicator database with the two
-following pull replication documents in it:
-
-.. code-block:: javascript
-
-    {
-         "_id": "rep_from_A",
-         "source":  "http://aserver.com:5984/foo",
-         "target":  "foo_a",
-         "continuous":  true,
-         "_replication_id":  "c0ebe9256695ff083347cbf95f93e280",
-         "_replication_state":  "triggered",
-         "_replication_state_time":  1297971311
-    }
-
-.. code-block:: javascript
-
-    {
-         "_id": "rep_from_B",
-         "source":  "http://bserver.com:5984/foo",
-         "target":  "foo_b",
-         "continuous":  true,
-         "_replication_id":  "231bb3cf9d48314eaa8d48a9170570d1",
-         "_replication_state":  "triggered",
-         "_replication_state_time":  1297974122
-    }
-
-Now you would like to have the same pull replications going on in server
-D, that is, you would like to have server D pull replicating from
-servers A and B. You have two options:
-
--  Explicitly add two documents to server's D replicator database
-
--  Replicate server's C replicator database into server's D replicator
-   database
-
-Both alternatives accomplish exactly the same goal.
-
-Delegations
------------
-
-Replication documents can have a custom ``user_ctx`` property. This
-property defines the user context under which a replication runs. For
-the old way of triggering replications (POSTing to ``/_replicate/``),
-this property was not needed (it didn't exist in fact) - this is because
-at the moment of triggering the replication it has information about the
-authenticated user. With the replicator database, since it's a regular
-database, the information about the authenticated user is only present
-at the moment the replication document is written to the database - the
-replicator database implementation is like a ``_changes`` feed consumer
-(with ``?include_docs=true``) that reacts to what was written to the
-replicator database - in fact this feature could be implemented with an
-external script/program. This implementation detail implies that for non
-admin users, a ``user_ctx`` property, containing the user's name and a
-subset of his/her roles, must be defined in the replication document.
-This is ensured by the document update validation function present in
-the default design document of the replicator database. This validation
-function also ensure that a non admin user can set a user name property
-in the ``user_ctx`` property that doesn't match his/her own name (same
-principle applies for the roles).
-
-For admins, the ``user_ctx`` property is optional, and if it's missing
-it defaults to a user context with name null and an empty list of roles
-- this mean design documents will not be written to local targets. If
-writing design documents to local targets is desired, the a user context
-with the roles ``_admin`` must be set explicitly.
-
-Also, for admins the ``user_ctx`` property can be used to trigger a
-replication on behalf of another user. This is the user context that
-will be passed to local target database document validation functions.
-
-.. note::
-   The ``user_ctx`` property only has effect for local endpoints.
-
-Example delegated replication document:
-
-.. code-block:: javascript
-
-    {
-         "_id": "my_rep",
-         "source":  "http://bserver.com:5984/foo",
-         "target":  "bar",
-         "continuous":  true,
-         "user_ctx": {
-              "name": "joe",
-              "roles": ["erlanger", "researcher"]
-         }
-    }
-
-As stated before, for admins the ``user_ctx`` property is optional, while
-for regular (non admin) users it's mandatory. When the roles property of
-``user_ctx`` is missing, it defaults to the empty list ``[ ]``.


[41/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Fix references.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/ccdaffa4
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/ccdaffa4
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/ccdaffa4

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: ccdaffa45662d30df5f5ec242d029d8c398b0245
Parents: 11bf3d2
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 11:05:50 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 11:05:50 2013 +0400

----------------------------------------------------------------------
 share/doc/src/config/externals.rst | 2 +-
 share/doc/src/config/services.rst  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/ccdaffa4/share/doc/src/config/externals.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/externals.rst b/share/doc/src/config/externals.rst
index 2b857cd..adbaea7 100644
--- a/share/doc/src/config/externals.rst
+++ b/share/doc/src/config/externals.rst
@@ -26,7 +26,7 @@ maintains a given OS level process alive. If the process dies for any reason,
 CouchDB will restart it. If the process restarts too often, then CouchDB will
 mark it has halted and not attempt to restart it. The default max restart rate
 is ``3`` times in the last ``5`` seconds. These parameters are
-:ref:`adjustable <config/os_daemons_settings>`.
+:ref:`adjustable <config/os_daemon_settings>`.
 
 Commands that are started in this manner will have access to a simple
 API over stdio to request configuration parameters or to add log

http://git-wip-us.apache.org/repos/asf/couchdb/blob/ccdaffa4/share/doc/src/config/services.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/services.rst b/share/doc/src/config/services.rst
index 03dd694..23d4841 100644
--- a/share/doc/src/config/services.rst
+++ b/share/doc/src/config/services.rst
@@ -40,7 +40,7 @@ closing of the `_users` database for each request requiring authentication::
 ``compaction_daemon``
 ---------------------
 
-:ref:`Automatic compaction <compact/auto>` daemon::
+:ref:`Automatic compaction <config/compactions>` daemon::
 
   [daemons]
   compaction_daemon={couch_compaction_daemon, start_link, []}


[14/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Don't confuse with example.com as consumer.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/6e1ceed8
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/6e1ceed8
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/6e1ceed8

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: 6e1ceed8a3619a313a0177b89ef72ed59b587fe4
Parents: ca28e12
Author: Alexander Shorin <kx...@apache.org>
Authored: Tue Jul 23 10:14:35 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:48:37 2013 +0400

----------------------------------------------------------------------
 share/doc/src/config/auth.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/6e1ceed8/share/doc/src/config/auth.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/config/auth.rst b/share/doc/src/config/auth.rst
index 9f98bb1..7cf2af9 100644
--- a/share/doc/src/config/auth.rst
+++ b/share/doc/src/config/auth.rst
@@ -275,7 +275,7 @@ setup three special sections in :ref:`configuration <config>` file:
 ::
 
   [oauth_consumer_secrets]
-  example.com = sekr1t
+  consumer1 = sekr1t
 
 2. Token secrets:
 


[30/50] [abbrv] git commit: updated refs/heads/1781-reorganize-and-improve-docs to fa11c25

Posted by kx...@apache.org.
Split API articles into small files focused on specific problem.

Small files more conveniently to edit than the large ones.


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/d67c2733
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/d67c2733
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/d67c2733

Branch: refs/heads/1781-reorganize-and-improve-docs
Commit: d67c27332e60fd0b4eb58d22568469afa34bed42
Parents: 57e35fe
Author: Alexander Shorin <kx...@apache.org>
Authored: Wed Jul 24 04:22:06 2013 +0400
Committer: Alexander Shorin <kx...@apache.org>
Committed: Wed Jul 24 10:54:24 2013 +0400

----------------------------------------------------------------------
 share/doc/build/Makefile.am                |   91 +-
 share/doc/src/api/authn.rst                |  460 -------
 share/doc/src/api/configuration.rst        |  307 -----
 share/doc/src/api/database.rst             | 1500 -----------------------
 share/doc/src/api/database/all-docs.rst    |  244 ++++
 share/doc/src/api/database/bulk-docs.rst   |  390 ++++++
 share/doc/src/api/database/changes.rst     |  144 +++
 share/doc/src/api/database/common.rst      |  195 +++
 share/doc/src/api/database/compact.rst     |  168 +++
 share/doc/src/api/database/index.rst       |  113 ++
 share/doc/src/api/database/misc.rst        |  179 +++
 share/doc/src/api/database/security.rst    |   99 ++
 share/doc/src/api/database/temp-views.rst  |   55 +
 share/doc/src/api/ddoc/common.rst          |  464 +++++++
 share/doc/src/api/ddoc/index.rst           |   37 +
 share/doc/src/api/ddoc/render.rst          |  126 ++
 share/doc/src/api/ddoc/rewrites.rst        |   24 +
 share/doc/src/api/ddoc/views.rst           |  708 +++++++++++
 share/doc/src/api/design.rst               | 1306 --------------------
 share/doc/src/api/document/attachments.rst |  242 ++++
 share/doc/src/api/document/common.rst      |  781 ++++++++++++
 share/doc/src/api/document/index.rst       |   53 +
 share/doc/src/api/documents.rst            | 1045 ----------------
 share/doc/src/api/index.rst                |   11 +-
 share/doc/src/api/misc.rst                 |  898 --------------
 share/doc/src/api/server/authn.rst         |  460 +++++++
 share/doc/src/api/server/common.rst        |  862 +++++++++++++
 share/doc/src/api/server/configuration.rst |  307 +++++
 share/doc/src/api/server/index.rst         |   75 ++
 share/doc/src/config/http-handlers.rst     |   44 +-
 share/doc/src/config/http.rst              |    2 +-
 share/doc/src/intro.rst                    |    4 +-
 share/doc/src/replication/intro.rst        |    2 +-
 33 files changed, 5825 insertions(+), 5571 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/build/Makefile.am
----------------------------------------------------------------------
diff --git a/share/doc/build/Makefile.am b/share/doc/build/Makefile.am
index a85db77..c9fc423 100644
--- a/share/doc/build/Makefile.am
+++ b/share/doc/build/Makefile.am
@@ -45,15 +45,30 @@ html_files = \
     html/_images/futon-editeddoc.png \
     html/_images/futon-overview.png \
     html/_images/futon-replform.png \
-    html/_sources/api/authn.txt \
-    html/_sources/api/basics.txt \
-    html/_sources/api/configuration.txt \
-    html/_sources/api/database.txt \
-    html/_sources/api/design.txt \
-    html/_sources/api/documents.txt \
-    html/_sources/api/local.txt \
-    html/_sources/api/misc.txt \
-    html/_sources/api/reference.txt \
+    html/_source/api/basics.txt \
+    html/_source/api/index.txt \
+    html/_source/api/local.txt \
+    html/_source/api/database/all-docs.txt \
+    html/_source/api/database/bulk-docs.txt \
+    html/_source/api/database/changes.txt \
+    html/_source/api/database/common.txt \
+    html/_source/api/database/compact.txt \
+    html/_source/api/database/index.txt \
+    html/_source/api/database/misc.txt \
+    html/_source/api/database/security.txt \
+    html/_source/api/database/temp-views.txt \
+    html/_source/api/document/attachments.txt \
+    html/_source/api/document/common.txt \
+    html/_source/api/document/index.txt \
+    html/_source/api/ddoc/common.txt \
+    html/_source/api/ddoc/index.txt \
+    html/_source/api/ddoc/render.txt \
+    html/_source/api/ddoc/rewrites.txt \
+    html/_source/api/ddoc/views.txt \
+    html/_source/api/server/authn.txt \
+    html/_source/api/server/common.txt \
+    html/_source/api/server/configuration.txt \
+    html/_source/api/server/index.txt \
     html/_sources/config/auth.txt \
     html/_sources/config/compaction.txt \
     html/_sources/config/couchdb.txt \
@@ -106,15 +121,30 @@ html_files = \
     html/_static/up-pressed.png \
     html/_static/up.png \
     html/_static/websupport.js \
-    html/api/authn.html \
     html/api/basics.html \
-    html/api/configuration.html \
-    html/api/database.html \
-    html/api/design.html \
-    html/api/documents.html \
+    html/api/index.html \
     html/api/local.html \
-    html/api/misc.html \
-    html/api/reference.html \
+    html/api/database/all-docs.html \
+    html/api/database/bulk-docs.html \
+    html/api/database/changes.html \
+    html/api/database/common.html \
+    html/api/database/compact.html \
+    html/api/database/index.html \
+    html/api/database/misc.html \
+    html/api/database/security.html \
+    html/api/database/temp-views.html \
+    html/api/document/attachments.html \
+    html/api/document/common.html \
+    html/api/document/index.html \
+    html/api/ddoc/common.html \
+    html/api/ddoc/index.html \
+    html/api/ddoc/render.html \
+    html/api/ddoc/rewrites.html \
+    html/api/ddoc/views.html \
+    html/api/server/authn.html \
+    html/api/server/common.html \
+    html/api/server/configuration.html \
+    html/api/server/index.html \
     html/config/auth.html \
     html/config/compaction.html \
     html/config/couchdb.html \
@@ -165,15 +195,30 @@ image_files = \
     ../images/logo.png
 
 src_files = \
-    ../src/api/authn.rst \
     ../src/api/basics.rst \
-    ../src/api/configuration.rst \
-    ../src/api/database.rst \
-    ../src/api/design.rst \
-    ../src/api/documents.rst \
+    ../src/api/index.rst \
     ../src/api/local.rst \
-    ../src/api/misc.rst \
-    ../src/api/reference.rst \
+    ../src/api/database/all-docs.rst \
+    ../src/api/database/bulk-docs.rst \
+    ../src/api/database/changes.rst \
+    ../src/api/database/common.rst \
+    ../src/api/database/compact.rst \
+    ../src/api/database/index.rst \
+    ../src/api/database/misc.rst \
+    ../src/api/database/security.rst \
+    ../src/api/database/temp-views.rst \
+    ../src/api/document/attachments.rst \
+    ../src/api/document/common.rst \
+    ../src/api/document/index.rst \
+    ../src/api/ddoc/common.rst \
+    ../src/api/ddoc/index.rst \
+    ../src/api/ddoc/render.rst \
+    ../src/api/ddoc/rewrites.rst \
+    ../src/api/ddoc/views.rst \
+    ../src/api/server/authn.rst \
+    ../src/api/server/common.rst \
+    ../src/api/server/configuration.rst \
+    ../src/api/server/index.rst \
     ../src/config/auth.rst \
     ../src/config/compaction.rst \
     ../src/config/couchdb.rst \

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/authn.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/authn.rst b/share/doc/src/api/authn.rst
deleted file mode 100644
index 083a262..0000000
--- a/share/doc/src/api/authn.rst
+++ /dev/null
@@ -1,460 +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.
-
-.. _api/auth:
-
-======================
-Authentication Methods
-======================
-
-The CouchDB Authentication methods provide an interface for obtaining
-session and authorization data.
-
-A list of the available methods and URL paths are provided below:
-
-+--------+-------------------------+-------------------------------------------+
-| Method | Path                    | Description                               |
-+========+=========================+===========================================+
-| GET    | /_session               | Returns cookie based login user           |
-|        |                         | information                               |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /_session               | Do cookie based user login                |
-+--------+-------------------------+-------------------------------------------+
-| DELETE | /_session               | Logout cookie based user                  |
-+--------+-------------------------+-------------------------------------------+
-
-.. note:: We're also strongly recommend you to
-   :ref:`setup SSL <config/ssl>` to improve all authentication methods security.
-
-
-.. _api/auth/basic:
-
-Basic Authentication
-====================
-
-`Basic authentication`_ (:rfc:`2617`) is a quick and simple way to be
-authenticated by CouchDB. The main flaw of this simplicity is the need to send
-user credentials with each request which may be insecure and hurts operations
-performance (since CouchDB must compute password hash with every request):
-
-.. code-block:: http
-
-    GET / HTTP/1.1
-    Authorization: Basic cm9vdDpyZWxheA==
-    Host: localhost:5984
-    Accept: application/json
-
-.. code-block:: http
-
-    HTTP/1.1 200 OK
-    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
-    Date: Mon, 03 Dec 2012 00:44:47 GMT
-    Content-Type: application/json
-    Content-Length: 177
-    Cache-Control: must-revalidate
-
-.. code-block:: javascript
-
-    {
-      "couchdb":"Welcome",
-      "uuid":"0a959b9b8227188afc2ac26ccdf345a6",
-      "version":"1.3.0",
-      "vendor": {
-        "version":"1.3.0",
-        "name":"The Apache Software Foundation"
-      }
-    }
-
-.. _Basic authentication: http://en.wikipedia.org/wiki/Basic_access_authentication
-
-
-.. _api/auth/cookie:
-
-Cookie Authentication
-=====================
-
-For cookie authentication (:rfc:`2109`) CouchDB generates a one-time token that
-the client can use for next requests to CouchDB. When CouchDB sees non expired
-the token in a subsequent request, it will authenticate user by this token
-without requesting the password again. By default, cookies are valid for
-10 minutes, but it's :ref:`adjustable <config/couch_httpd_auth/timeout>`.
-Also it's possible to make cookies
-:ref:`persistent <config/couch_httpd_auth/allow_persistent_cookies>`
-
-To obtain the first token and thus authenticate a user for the first time, the
-`username` and `password` must be sent to the
-:ref:`_session API <api/auth/session>`.
-
-.. _api/auth/session:
-.. _api/auth/session.post:
-
-``POST /_session``
-------------------
-
-* **Method**: ``POST /_session``
-* **Request**: User credentials
-* **Response**: User information
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: next
-
-    * **Description**: Enforces redirect after successful login
-    * **Optional**: yes
-    * **Value**: Relative path from server root
-
-* **HTTP Headers**
-
-  * **Header**: ``Content-Type``
-
-    * **Description**: Credentials data format
-    * **Optional**: no
-    * **Value**: ``application/x-www-form-urlencoded``
-
-* **Return Codes**:
-
-  * **200**:
-    Successfully authenticated
-
-  * **302**:
-    Redirect after successful authentication
-
-  * **401**:
-    Username or password wasn't recognized
-
-Initiates new session for specified user credentials by providing `Cookie`
-value. Credentials should be defined in ``application/x-www-form-urlencoded``
-format with `name` and `password` fields.
-
-.. code-block:: http
-
-    POST /_session HTTP/1.1
-    Host: localhost:5984
-    Accept: application/json
-    Content-Length: 24
-    Content-Type: application/x-www-form-urlencoded
-
-.. code-block:: text
-
-    name=root&password=relax
-
-In case of success will be returned next response:
-
-.. code-block:: http
-
-    HTTP/1.1 200 OK
-    Set-Cookie: AuthSession=cm9vdDo1MEJCRkYwMjq0LO0ylOIwShrgt8y-UkhI-c6BGw; Version=1; Path=/; HttpOnly
-    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
-    Date: Mon, 03 Dec 2012 01:23:14 GMT
-    Content-Type: application/json
-    Content-Length: 43
-    Cache-Control: must-revalidate
-
-.. code-block:: javascript
-
-    {"ok":true,"name":null,"roles":["_admin"]}
-
-If ``next`` query parameter was provided the response will trigger redirection
-to the specified location in case of successful authentication:
-
-.. code-block:: http
-
-    GET /_session?next=/blog/_design/sofa/_rewrite/recent-posts HTTP/1.1
-    Host: localhost:5984
-    Accept: application/json
-
-.. code-block:: http
-
-    HTTP/1.1 302 Moved Temporarily
-    Set-Cookie: AuthSession=cm9vdDo1MEJDMDEzRTp7Vu5GKCkTxTVxwXbpXsBARQWnhQ; Version=1; Path=/; HttpOnly
-    Server: CouchDB/1.3.0 (Erlang OTP/R15B02)
-    Location: http://localhost:5984/blog/_design/sofa/_rewrite/recent-posts
-    Date: Mon, 03 Dec 2012 01:32:46 GMT
-    Content-Type: application/json
-    Content-Length: 43
-    Cache-Control: must-revalidate
-
-.. code-block:: javascript
-
-    {"ok":true,"name":null,"roles":["_admin"]}
-
-
-.. _api/auth/session.get:
-
-``GET /_session``
------------------
-
-* **Method**: ``GET /_session``
-* **Request**: None
-* **Response**: User information
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: basic
-
-    * **Description**: Accept `Basic Auth` by requesting this resource
-    * **Optional**: yes
-    * **Value**: ``true``
-
-* **Return Codes**:
-
-  * **200**:
-    Successfully authenticated.
-
-  * **401**:
-    Username or password wasn't recognized.
-
-Returns complete information about authenticated user:
-
-.. code-block:: http
-
-    GET /_session HTTP/1.1
-    Host: localhost:5984
-    Accept: application/json
-    Cookie: AuthSession=cm9vdDo1MEJDMDQxRDpqb-Ta9QfP9hpdPjHLxNTKg_Hf9w
-
-.. code-block:: javascript
-
-    {
-        "info": {
-            "authenticated": "cookie",
-            "authentication_db": "_users",
-            "authentication_handlers": [
-                "oauth",
-                "cookie",
-                "default"
-            ]
-        },
-        "ok": true,
-        "userCtx": {
-            "name": "root",
-            "roles": [
-                "_admin"
-            ]
-        }
-    }
-
-This information contains :ref:`userctx_object`, authentication method and
-available ones and authentication database.
-
-.. _api/auth/session.delete:
-
-``DELETE /_session``
---------------------
-
-* **Method**: ``DELETE /_session``
-* **Request**: None
-* **Response**: Status
-* **Admin Privileges Required**: no
-
-* **Return Codes**:
-
-  * **200**:
-    Successfully close session.
-
-  * **401**:
-    Username or password wasn't recognized.
-
-Closes user's session. If everything is ok, the response is:
-
-.. code-block:: javascript
-
-    {"ok":true}
-
-
-.. _api/auth/proxy:
-
-Proxy Authentication
-====================
-
-.. note::
-   To use this authentication method make sure that the
-   ``{couch_httpd_auth, proxy_authentication_handler}`` value in added to
-   the list of the active
-   :ref:`authentication handlers <config/httpd/authentication_handlers>`:
-
-   .. code-block:: ini
-
-      [httpd]
-      authentication_handlers = {couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, proxy_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
-
-
-`Proxy authentication` is very useful in case when your application is already
-uses some external authentication service and you won't duplicate users and
-their roles in CouchDB.
-
-This authentication method allows creation of a :ref:`userctx_object` for
-remotely authenticated user. By default, the client just need to pass specific
-headers to CouchDB with related request:
-
-- :ref:`X-Auth-CouchDB-UserName <config/couch_httpd_auth/x_auth_username>`:
-  username;
-- :ref:`X-Auth-CouchDB-Roles <config/couch_httpd_auth/x_auth_roles>`:
-  list of user roles separated by a comma (``,``);
-- :ref:`X-Auth-CouchDB-Token <config/couch_httpd_auth/x_auth_token>`:
-  authentication token. Optional, but strongly recommended to
-  :ref:`force token be required <config/couch_httpd_auth/proxy_use_secret>`
-  to prevent requests from untrusted sources.
-
-.. code-block:: http
-
-    GET /_session HTTP/1.1
-    Host: localhost:5984
-    Accept: application/json
-    Content-Type: application/json; charset=utf-8
-    X-Auth-CouchDB-Roles: users,blogger
-    X-Auth-CouchDB-UserName: foo
-
-CouchDB sends the response:
-
-.. code-block:: http
-
-    HTTP/1.1 200 OK
-    Cache-Control: must-revalidate
-    Content-Length: 190
-    Content-Type: application/json
-    Date: Fri, 14 Jun 2013 10:16:03 GMT
-    Server: CouchDB/1.3.0 (Erlang OTP/R15B03)
-
-.. code-block:: javascript
-
-    {
-        "info": {
-            "authenticated": "proxy",
-            "authentication_db": "_users",
-            "authentication_handlers": [
-                "oauth",
-                "cookie",
-                "proxy",
-                "default"
-            ]
-        },
-        "ok": true,
-        "userCtx": {
-            "name": "foo",
-            "roles": [
-                "users",
-                "blogger"
-            ]
-        }
-    }
-
-
-Note, that you don't need to request :ref:`session <api/auth/session>` resource
-to be authenticated by this method if all required HTTP headers are provided.
-
-
-.. _api/auth/oauth:
-
-OAuth Authentication
-====================
-
-CouchDB supports OAuth 1.0 authentication (:rfc:`5849`). OAuth provides a method
-for clients to access server resources  without sharing real credentials
-(username and password).
-
-First, :ref:`configure oauth <config/oauth>`, by setting consumer and token
-with their secrets and binding token to real CouchDB username.
-
-Probably, it's not good idea to work with plain curl, let use some scripting
-language like Python:
-
-.. code-block:: python
-
-  #!/usr/bin/env python2
-  from oauth import oauth # pip install oauth
-  import httplib
-
-  URL = 'http://localhost:5984/_session'
-  CONSUMER_KEY = 'consumer1'
-  CONSUMER_SECRET = 'sekr1t'
-  TOKEN = 'token1'
-  SECRET = 'tokensekr1t'
-
-  consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
-  token = oauth.OAuthToken(TOKEN, SECRET)
-  req = oauth.OAuthRequest.from_consumer_and_token(
-      consumer,
-      token=token,
-      http_method='GET',
-      http_url=URL,
-      parameters={}
-  )
-  req.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer,token)
-
-  headers = req.to_header()
-  headers['Accept'] = 'application/json'
-
-  con = httplib.HTTPConnection('localhost', 5984)
-  con.request('GET', URL, headers=headers)
-  resp = con.getresponse()
-  print resp.read()
-
-or Ruby:
-
-.. code-block:: ruby
-
-  #!/usr/bin/env ruby
-
-  require 'oauth' # gem install oauth
-
-  URL = 'http://localhost:5984'
-  CONSUMER_KEY = 'consumer1'
-  CONSUMER_SECRET = 'sekr1t'
-  TOKEN = 'token1'
-  SECRET = 'tokensekr1t'
-
-  @consumer = OAuth::Consumer.new CONSUMER_KEY,
-                                  CONSUMER_SECRET,
-                                  {:site => URL}
-
-  @access_token = OAuth::AccessToken.new(@consumer, TOKEN, SECRET)
-
-  puts @access_token.get('/_session').body
-
-
-Both snippets produces similar request and response pair:
-
-.. code-block:: http
-
-    GET /_session HTTP/1.1
-    Host: localhost:5984
-    Accept: application/json
-    Authorization: OAuth realm="", oauth_nonce="81430018", oauth_timestamp="1374561749", oauth_consumer_key="consumer1", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="token1", oauth_signature="o4FqJ8%2B9IzUpXH%2Bk4rgnv7L6eTY%3D"
-
-.. code-block:: http
-
-    HTTP/1.1 200 OK
-    Cache-Control : must-revalidate
-    Content-Length : 167
-    Content-Type : application/json
-    Date : Tue, 23 Jul 2013 06:51:15 GMT
-    Server : CouchDB/1.3.1 (Erlang OTP/R16B)
-
-.. code-block:: javascript
-
-  {
-    "ok": true,
-    "info": {
-      "authenticated": "oauth"
-      "authentication_db": "_users",
-      "authentication_handlers": ["oauth", "cookie", "default"]
-    },
-    "userCtx": {
-      "name": "couchdb_username",
-      "roles": []
-    }
-  }
-
-There we'd requested the :ref:`_session <api/auth/session>` resource to ensure
-that authentication was successful and target CouchDB username is correct.
-Change the target URL to request required resource.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/configuration.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/configuration.rst b/share/doc/src/api/configuration.rst
deleted file mode 100644
index 9fdec09..0000000
--- a/share/doc/src/api/configuration.rst
+++ /dev/null
@@ -1,307 +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.
-
-.. _api/config:
-
-=====================
-Configuration Methods
-=====================
-
-The CouchDB API Server Configuration Methods provide an interface to
-query and update the various configuration values within a running
-CouchDB instance.
-
-A list of the available methods and URL paths are provided below:
-
-+--------+-------------------------+-------------------------------------------+
-| Method | Path                    | Description                               |
-+========+=========================+===========================================+
-| GET    | /_config                | Obtain a list of the entire server        |
-|        |                         | configuration                             |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_config/section        | Get all the configuration values for the  |
-|        |                         | specified section                         |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /_config/section/key    | Get a specific section/configuration value|
-+--------+-------------------------+-------------------------------------------+
-| PUT    | /_config/section/key    | Set the specified configuration value     |
-+--------+-------------------------+-------------------------------------------+
-| DELETE | /_config/section/key    | Delete the current setting                |
-+--------+-------------------------+-------------------------------------------+
-
-.. _api/config.get:
-
-``GET /_config``
-================
-
-* **Method**: ``GET /_config``
-* **Request**: None
-* **Response**: Returns a structure configuration name and value pairs,
-  organized by section
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-Returns the entire CouchDB server configuration as a JSON structure. The
-structure is organized by different configuration sections, with
-individual values.
-
-For example, to get the configuration for a server:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/_config
-    Accept: application/json
-
-The response is the JSON structure:
-
-.. code-block:: javascript
-
-    {
-       "query_server_config" : {
-          "reduce_limit" : "true"
-       },
-       "couchdb" : {
-          "os_process_timeout" : "5000",
-          "max_attachment_chunk_size" : "4294967296",
-          "max_document_size" : "4294967296",
-          "uri_file" : "/var/lib/couchdb/couch.uri",
-          "max_dbs_open" : "100",
-          "view_index_dir" : "/var/lib/couchdb",
-          "util_driver_dir" : "/usr/lib64/couchdb/erlang/lib/couch-1.0.1/priv/lib",
-          "database_dir" : "/var/lib/couchdb",
-          "delayed_commits" : "true"
-       },
-       "attachments" : {
-          "compressible_types" : "text/*, application/javascript, application/json,  application/xml",
-          "compression_level" : "8"
-       },
-       "uuids" : {
-          "algorithm" : "utc_random"
-       },
-       "daemons" : {
-          "view_manager" : "{couch_view, start_link, []}",
-          "auth_cache" : "{couch_auth_cache, start_link, []}",
-          "uuids" : "{couch_uuids, start, []}",
-          "stats_aggregator" : "{couch_stats_aggregator, start, []}",
-          "query_servers" : "{couch_query_servers, start_link, []}",
-          "httpd" : "{couch_httpd, start_link, []}",
-          "stats_collector" : "{couch_stats_collector, start, []}",
-          "db_update_notifier" : "{couch_db_update_notifier_sup, start_link, []}",
-          "external_manager" : "{couch_external_manager, start_link, []}"
-       },
-       "stats" : {
-          "samples" : "[0, 60, 300, 900]",
-          "rate" : "1000"
-       },
-       "httpd" : {
-          "vhost_global_handlers" : "_utils, _uuids, _session, _oauth, _users",
-          "secure_rewrites" : "true",
-          "authentication_handlers" : "{couch_httpd_oauth, oauth_authentication_handler},
-                                       {couch_httpd_auth, cookie_authentication_handler},
-                                       {couch_httpd_auth, default_authentication_handler}",
-          "port" : "5984",
-          "default_handler" : "{couch_httpd_db, handle_request}",
-          "allow_jsonp" : "false",
-          "bind_address" : "192.168.0.2",
-          "max_connections" : "2048"
-       },
-       "query_servers" : {
-          "javascript" : "/usr/bin/couchjs /usr/share/couchdb/server/main.js"
-       },
-       "couch_httpd_auth" : {
-          "authentication_db" : "_users",
-          "require_valid_user" : "false",
-          "authentication_redirect" : "/_utils/session.html",
-          "timeout" : "600",
-          "auth_cache_size" : "50"
-       },
-       "httpd_db_handlers" : {
-          "_design" : "{couch_httpd_db, handle_design_req}",
-          "_compact" : "{couch_httpd_db, handle_compact_req}",
-          "_view_cleanup" : "{couch_httpd_db, handle_view_cleanup_req}",
-          "_temp_view" : "{couch_httpd_view, handle_temp_view_req}",
-          "_changes" : "{couch_httpd_db, handle_changes_req}"
-       },
-       "replicator" : {
-          "max_http_sessions" : "10",
-          "max_http_pipeline_size" : "10"
-       },
-       "log" : {
-          "include_sasl" : "true",
-          "level" : "info",
-          "file" : "/var/log/couchdb/couch.log"
-       },
-       "httpd_design_handlers" : {
-          "_update" : "{couch_httpd_show, handle_doc_update_req}",
-          "_show" : "{couch_httpd_show, handle_doc_show_req}",
-          "_info" : "{couch_httpd_db,   handle_design_info_req}",
-          "_list" : "{couch_httpd_show, handle_view_list_req}",
-          "_view" : "{couch_httpd_view, handle_view_req}",
-          "_rewrite" : "{couch_httpd_rewrite, handle_rewrite_req}"
-       },
-       "httpd_global_handlers" : {
-          "_replicate" : "{couch_httpd_misc_handlers, handle_replicate_req}",
-          "/" : "{couch_httpd_misc_handlers, handle_welcome_req, <<\"Welcome\">>}",
-          "_config" : "{couch_httpd_misc_handlers, handle_config_req}",
-          "_utils" : "{couch_httpd_misc_handlers, handle_utils_dir_req, \"/usr/share/couchdb/www\"}",
-          "_active_tasks" : "{couch_httpd_misc_handlers, handle_task_status_req}",
-          "_session" : "{couch_httpd_auth, handle_session_req}",
-          "_log" : "{couch_httpd_misc_handlers, handle_log_req}",
-          "favicon.ico" : "{couch_httpd_misc_handlers, handle_favicon_req, \"/usr/share/couchdb/www\"}",
-          "_all_dbs" : "{couch_httpd_misc_handlers, handle_all_dbs_req}",
-          "_oauth" : "{couch_httpd_oauth, handle_oauth_req}",
-          "_restart" : "{couch_httpd_misc_handlers, handle_restart_req}",
-          "_uuids" : "{couch_httpd_misc_handlers, handle_uuids_req}",
-          "_stats" : "{couch_httpd_stats_handlers, handle_stats_req}"
-       }
-    }
-        
-
-.. _api/config/section:
-.. _api/config/section.get:
-
-``GET /_config/section``
-========================
-
-* **Method**: ``GET /_config/section``
-* **Request**: None
-* **Response**: All the configuration values within a specified section
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-Gets the configuration structure for a single section. For example, to
-retrieve the CouchDB configuration section values:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/_config/couchdb
-    Accept: application/json
-
-The returned JSON contains just the configuration values for this
-section:
-
-.. code-block:: javascript
-
-    {
-       "os_process_timeout" : "5000",
-       "max_attachment_chunk_size" : "4294967296",
-       "max_document_size" : "4294967296",
-       "uri_file" : "/var/lib/couchdb/couch.uri",
-       "max_dbs_open" : "100",
-       "view_index_dir" : "/var/lib/couchdb",
-       "util_driver_dir" : "/usr/lib64/couchdb/erlang/lib/couch-1.0.1/priv/lib",
-       "database_dir" : "/var/lib/couchdb",
-       "delayed_commits" : "true"
-    }
-
-.. _api/config/section/key:
-.. _api/config/section/key.get:
-
-``GET /_config/section/key``
-============================
-
-* **Method**: ``GET /_config/section/key``
-* **Request**: None
-* **Response**: Value of the specified key/section
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **200**:
-    Request completed successfully.
-
-Gets a single configuration value from within a specific configuration
-section. For example, to obtain the current log level:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/_config/log/level
-    Accept: application/json
-
-Returns the string of the log level:
-
-.. code-block:: javascript
-
-    "info"
-
-.. note::
-   The returned value will be the JSON of the value, which may be a
-   string or numeric value, or an array or object. Some client
-   environments may not parse simple strings or numeric values as valid JSON.
-
-.. _api/config/section/key.put:
-
-``PUT /_config/section/key``
-============================
-
-* **Method**: ``PUT /_config/section/key``
-* **Request**: Value structure
-* **Response**: Previous value
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **200**:
-    Configuration option updated successfully
-
-  * **500**:
-    Error setting configuration
-
-Updates a configuration value. The new value should be supplied in the
-request body in the corresponding JSON format. For example, if you are
-setting a string value, you must supply a valid JSON string.
-
-For example, to set the function used to generate UUIDs by the
-``GET /_uuids`` API call to use the ``utc_random`` generator:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/_config/uuids/algorithm
-    Content-Type: application/json
-
-    "utc_random"
-
-The return value will be empty, with the response code indicating the
-success or failure of the configuration setting.
-
-.. _api/config/section/key.delete:
-
-``DELETE /_config/section/key``
-===============================
-
-* **Method**: ``DELETE /_config/section/key``
-* **Request**: None
-* **Response**: Previous value
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **409**:
-    Supplied revision is incorrect or missing
-
-Deletes a configuration value. The returned JSON will be the value of
-the configuration parameter before it was deleted. For example, to
-delete the UUID parameter:
-
-.. code-block:: http
-
-    DELETE http://couchdb:5984/_config/uuids/algorithm
-    Content-Type: application/json
-
-The returned value is the last configured UUID function:
-
-.. code-block:: javascript
-
-    "random"

http://git-wip-us.apache.org/repos/asf/couchdb/blob/d67c2733/share/doc/src/api/database.rst
----------------------------------------------------------------------
diff --git a/share/doc/src/api/database.rst b/share/doc/src/api/database.rst
deleted file mode 100644
index 38c8f7c..0000000
--- a/share/doc/src/api/database.rst
+++ /dev/null
@@ -1,1500 +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.
-
-.. _api/db:
-
-================
-Database Methods
-================
-
-The Database methods provide an interface to an entire database withing
-CouchDB. These are database, rather than document, level requests.
-
-A list of the available methods and URL paths are provided below:
-
-+--------+-------------------------+-------------------------------------------+
-| Method | Path                    | Description                               |
-+========+=========================+===========================================+
-| HEAD   | /db                     | Checks database existence                 |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /db                     | Returns database information              |
-+--------+-------------------------+-------------------------------------------+
-| PUT    | /db                     | Create a new database                     |
-+--------+-------------------------+-------------------------------------------+
-| DELETE | /db                     | Delete an existing database               |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /db/_all_docs           | Returns a built-in view of all documents  |
-|        |                         | in this database                          |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_all_docs           | Returns certain rows from the built-in    |
-|        |                         | view of all documents                     |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_bulk_docs          | Insert multiple documents in to the       |
-|        |                         | database in a single request              |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /db/_changes            | Returns changes for the given database    |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_compact            | Starts a compaction for the database      |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_compact/design-doc | Starts a compaction for all the views in  |
-|        |                         | the selected design document              |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_ensure_full_commit | Makes sure all uncommitted changes are    |
-|        |                         | written and synchronized to the disk      |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_missing_revs       | Given a list of document revisions,       |
-|        |                         | returns the document revisions that do not|
-|        |                         | exist in the database                     |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_purge              | Purge some historical documents entirely  |
-|        |                         | from database history                     |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_revs_diff          | Given a list of document revisions,       |
-|        |                         | returns differences between the given     |
-|        |                         | revisions and ones that are in the        |
-|        |                         | database                                  |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /db/_revs_limit         | Gets the limit of historical revisions to |
-|        |                         | store for a single document in the        |
-|        |                         | database                                  |
-+--------+-------------------------+-------------------------------------------+
-| PUT    | /db/_revs_limit         | Sets the limit of historical revisions to |
-|        |                         | store for a single document in the        |
-|        |                         | database                                  |
-+--------+-------------------------+-------------------------------------------+
-| GET    | /db/_security           | Returns the special security object for   |
-|        |                         | the database                              |
-+--------+-------------------------+-------------------------------------------+
-| PUT    | /db/_security           | Sets the special security object for the  |
-|        |                         | database                                  |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_temp_view          | Execute a given view function for all     |
-|        |                         | documents and return the result           |
-+--------+-------------------------+-------------------------------------------+
-| POST   | /db/_view_cleanup       | Removes view files that are not used by   |
-|        |                         | any design document                       |
-+--------+-------------------------+-------------------------------------------+
-
-For all the database methods, the database name within the URL path
-should be the database name that you wish to perform the operation on.
-For example, to obtain the meta information for the database
-``recipes``, you would use the HTTP request:
-
-.. code-block:: http
-
-    GET /recipes
-
-For clarity, the form below is used in the URL paths:
-
-.. code-block:: http
-
-    GET /db
-
-Where ``db`` is the name of any database.
-
-.. _api/db.head:
-
-``HEAD /db``
-============
-
-* **Method**: ``HEAD /db``
-* **Request**: None
-* **Response**: None
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **200**:
-    Database exists.
-
-  * **404**:
-    Requested database not found.
-
-Returns the HTTP Headers containing a minimal amount of information
-about the specified database. Since the response body is empty this method
-is a lightweight way to check is database exists or not.
-
-.. _api/db.get:
-
-``GET /db``
-===========
-
-* **Method**: ``GET /db``
-* **Request**: None
-* **Response**: Information about the database in JSON format
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **404**:
-    The requested content could not be found. The returned content will include
-    further information, as a JSON object, if available.
-
-Gets information about the specified database. For example, to retrieve
-the information for the database ``recipe``:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes
-    Accept: application/json
-
-The JSON response contains meta information about the database. A sample
-of the JSON returned for an empty database is provided below:
-
-.. code-block:: javascript
-
-    {
-       "compact_running" : false,
-       "committed_update_seq" : 375048,
-       "disk_format_version" : 5,
-       "disk_size" : 33153123,
-       "doc_count" : 18386,
-       "doc_del_count" : 0,
-       "db_name" : "recipes",
-       "instance_start_time" : "1290700340925570",
-       "purge_seq" : 10,
-       "update_seq" : 375048
-    }
-        
-
-The elements of the returned structure are shown in the table below:
-
-+----------------------------------+-------------------------------------------+
-| Field                            | Description                               |
-+==================================+===========================================+
-| committed_update_seq             | The number of committed update.           |
-+----------------------------------+-------------------------------------------+
-| compact_running                  | Set to true if the database compaction    |
-|                                  | routine is operating on this database.    |
-+----------------------------------+-------------------------------------------+
-| db_name                          | The name of the database.                 |
-+----------------------------------+-------------------------------------------+
-| disk_format_version              | The version of the physical format used   |
-|                                  | for the data when it is stored on disk.   |
-+----------------------------------+-------------------------------------------+
-| disk_size                        | Size in bytes of the data as stored on the|
-|                                  | disk. Views indexes are not included in   |
-|                                  | the calculation.                          |
-+----------------------------------+-------------------------------------------+
-| doc_count                        | A count of the documents in the specified |
-|                                  | database.                                 |
-+----------------------------------+-------------------------------------------+
-| doc_del_count                    | Number of deleted documents               |
-+----------------------------------+-------------------------------------------+
-| instance_start_time              | Timestamp of 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 to the      |
-|                                  | database.                                 |
-+----------------------------------+-------------------------------------------+
-
-.. _api/db.put:
-
-``PUT /db``
-===========
-
-* **Method**: ``PUT /db``
-* **Request**: None
-* **Response**: JSON success statement
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **400**:
-    Invalid database name
-
-  * **412**:
-    Database already exists
-
-Creates a new database. The database name must be composed of one or
-more of the following characters:
-
--  Lowercase characters (``a-z``)
-
--  Name must begin with a lowercase letter
-
--  Digits (``0-9``)
-
--  Any of the characters ``_``, ``$``, ``(``, ``)``, ``+``, ``-``, and
-   ``/``.
-
-Trying to create a database that does not meet these requirements will
-return an error quoting these restrictions.
-
-To create the database ``recipes``:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes
-    Content-Type: application/json
-
-The returned content contains the JSON status:
-
-.. code-block:: javascript
-
-    {
-       "ok" : true
-    }
-
-Anything should be treated as an error, and the problem should be taken
-form the HTTP response code.
-
-.. _api/db.delete:
-
-``DELETE /db``
-==============
-
-* **Method**: ``DELETE /db``
-* **Request**: None
-* **Response**: JSON success statement
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **200**:
-    Database has been deleted
-
-  * **404**:
-    The requested content could not be found. The returned content will include
-    further information, as a JSON object, if available.
-
-Deletes the specified database, and all the documents and attachments
-contained within it.
-
-To delete the database ``recipes`` you would send the request:
-
-.. code-block:: http
-
-    DELETE http://couchdb:5984/recipes
-    Content-Type: application/json
-
-If successful, the returned JSON will indicate success
-
-.. code-block:: javascript
-
-    {
-       "ok" : true
-    }
-
-.. _api/db/changes:
-.. _api/db/changes.get:
-
-``GET /db/_changes``
-====================
-
-* **Method**: ``GET /db/_changes``
-* **Request**: None
-* **Response**: JSON success statement
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: doc_ids
-
-    * **Description**:  Specify the list of documents IDs to be filtered
-    * **Optional**: yes
-    * **Type**: json
-    * **Default**: none
-
-  * **Argument**: feed
-
-    * **Description**: Type of the :ref:`changes <changes>` feed
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**: normal
-    * **Supported Values**:
-
-      * **continuous**: :ref:`Continuous <changes/continuous>` mode
-      * **eventsource**: :ref:`Event source <changes/eventsource>` mode
-      * **longpoll**: :ref:`Long polling <changes/longpoll>` mode
-      * **normal**: :ref:`Normal <changes/normal>` mode
-
-  * **Argument**: filter
-
-    * **Description**:  Filter function from a design document to get updates
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**: none
-    * **Supported Values**:
-
-  * **Argument**: heartbeat
-
-    * **Description**:  Period after which an empty line is sent during longpoll
-      or continuous
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 60000
-    * **Quantity**: milliseconds
-
-  * **Argument**: include_docs
-
-    * **Description**:  Include the document with the result
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: limit
-
-    * **Description**:  Maximum number of rows rows to return
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: none
-
-  * **Argument**: since
-
-    * **Description**:  Start the results from changes immediately after the
-      specified sequence number
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 0
-
-Obtains a list of the changes made to the database. This can be used to
-monitor for update and modifications to the database for post processing
-or synchronization.
-
-.. seealso::
-
-   :ref:`Detailed description of available changes feed types <changes>`
-
-The return structure for ``normal`` and ``longpoll`` modes is a JSON
-array of changes objects, and the last update sequence number. The
-structure is described in the following table.
-
-+----------------------------------+-------------------------------------------+
-| Field                            | Description                               |
-+==================================+===========================================+
-| last_seq                         | Last change sequence number.              |
-+----------------------------------+-------------------------------------------+
-| results [array]                  | Changes made to a database                |
-+----------------------------------+-------------------------------------------+
-|         changes [array]          | List of changes, field-by-field, for this |
-|                                  | document                                  |
-+----------------------------------+-------------------------------------------+
-|         id                       | Document ID                               |
-+----------------------------------+-------------------------------------------+
-|         seq                      | Update sequence number                    |
-+----------------------------------+-------------------------------------------+
-
-The return format for ``continuous`` mode the server sends a ``CRLF``
-(carriage-return, linefeed) delimited line for each change. Each line
-contains the `JSON object`_.
-
-You can also request the full contents of each document change (instead
-of just the change notification) by using the ``include_docs``
-parameter.
-
-Filtering
----------
-
-You can filter the contents of the changes feed in a number of ways. The
-most basic way is to specify one or more document IDs to the query. This
-causes the returned structure value to only contain changes for the
-specified IDs. Note that the value of this query argument should be a
-JSON formatted array.
-
-You can also filter the ``_changes`` feed by defining a filter function
-within a design document. The specification for the filter is the same
-as for replication filters. You specify the name of the filter function
-to the ``filter`` parameter, specifying the design document name and
-filter name. For example:
-
-.. code-block:: http
-
-    GET /db/_changes?filter=design_doc/filtername
-
-The ``_changes`` feed can be used to watch changes to specific document
-ID's or the list of ``_design`` documents in a database. If the
-``filters`` parameter is set to ``_doc_ids`` a list of doc IDs can be
-passed in the ``doc_ids`` parameter as a JSON array. For more
-information, see :ref:`changes`.
-
-.. _api/db/compact:
-.. _api/db/compact.post:
-
-``POST /db/_compact``
-=====================
-
-* **Method**: ``POST /db/_compact``
-* **Request**: None
-* **Response**: JSON success statement
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **202**:
-    Compaction request has been accepted
-
-  * **404**:
-    The requested content could not be found. The returned content will include
-    further information, as a JSON object, if available.
-
-Request compaction of the specified database. Compaction compresses the
-disk database file by performing the following operations:
-
--  Writes a new version of the database file, removing any unused
-   sections from the new version during write. Because a new file is
-   temporary created for this purpose, you will need twice the current
-   storage space of the specified database in order for the compaction
-   routine to complete.
-
--  Removes old revisions of documents from the database, up to the
-   per-database limit specified by the ``_revs_limit`` database
-   parameter. See :ref:`api/db.get`.
-
-Compaction can only be requested on an individual database; you cannot
-compact all the databases for a CouchDB instance. The compaction process
-runs as a background process.
-
-You can determine if the compaction process is operating on a database
-by obtaining the database meta information, the ``compact_running``
-value of the returned database structure will be set to true. See
-:ref:`api/db.get`.
-
-You can also obtain a list of running processes to determine whether
-compaction is currently running. See :ref:`api/misc/active_tasks`.
-
-.. _api/db/compact/ddoc:
-.. _api/db/compact/ddoc.post:
-
-``POST /db/_compact/design-doc``
-================================
-
-* **Method**: ``POST /db/_compact/design-doc``
-* **Request**: None
-* **Response**: JSON success statement
-* **Admin Privileges Required**: yes
-* **Return Codes**:
-
-  * **202**:
-    Compaction request has been accepted
-
-  * **404**:
-    The requested content could not be found. The returned content will include
-    further information, as a JSON object, if available.
-
-Compacts the view indexes associated with the specified design document.
-You can use this in place of the full database compaction if you know a
-specific set of view indexes have been affected by a recent database
-change.
-
-For example, to compact the views associated with the ``recipes`` design
-document:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_compact/recipes
-    Content-Type: application/json
-
-CouchDB will immediately return with a status indicating that the
-compaction request has been received (HTTP status code 202):
-
-.. code-block:: javascript
-
-    {
-       "ok" : true
-    }
-        
-
-.. _api/db/view_cleanup:
-.. _api/db/view_cleanup.post:
-
-``POST /db/_view_cleanup``
-==========================
-
-* **Method**: ``POST /db/_view_cleanup``
-* **Request**: None
-* **Response**: JSON success statement
-* **Admin Privileges Required**: yes
-
-Cleans up the cached view output on disk for a given view. For example:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_view_cleanup
-    Content-Type: application/json
-
-If the request is successful, a basic status message us returned:
-
-.. code-block:: javascript
-
-    {
-       "ok" : true
-    }
-        
-
-.. _api/db/ensure_full_commit:
-.. _api/db/ensure_full_commit.post:
-
-``POST /db/_ensure_full_commit``
-================================
-
-* **Method**: ``POST /db/_ensure_full_commit``
-* **Request**: None
-* **Response**: JSON success statement
-* **Admin Privileges Required**: no
-* **Return Codes**:
-
-  * **202**:
-    Commit completed successfully
-
-  * **404**:
-    The requested content could not be found. The returned content will include
-    further information, as a JSON object, if available.
-
-
-Commits any recent changes to the specified database to disk. You should
-call this if you want to ensure that recent changes have been written.
-For example, to commit all the changes to disk for the database
-``recipes`` you would use:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_ensure_full_commit
-    Content-Type: application/json
-
-This returns a status message, containing the success message and the
-timestamp for when the CouchDB instance was started:
-
-.. code-block:: javascript
-
-    {
-      "ok" : true,
-      "instance_start_time" : "1288186189373361"
-    }
-
-.. _api/db/bulk_docs:
-.. _api/db/bulk_docs.post:
-
-``POST /db/_bulk_docs``
-=======================
-
-* **Method**: ``POST /db/_bulk_docs``
-* **Request**: JSON of the docs and updates to be applied
-* **Response**: JSON success statement
-* **Admin Privileges Required**: no
-
-* **HTTP Headers**:
-
-  * **Header**: ``X-Couch-Full-Commit``
-
-    * **Description**: Overrides server's commit policy.
-    * **Optional**: yes
-    * **Values**:
-
-      * **true**: Ensures that any non-committed changes are committed to
-        physical storage.
-      * **false**: Uses the delay commit in opposite to ``true`` value. CouchDB
-        responses quickly, but without any guarantees that all data are
-        successfully stored on disk.
-
-* **Return Codes**:
-
-  * **201**:
-    Document(s) have been created or updated
-
-The bulk document API allows you to create and update multiple documents
-at the same time within a single request. The basic operation is similar
-to creating or updating a single document, except that you batch the
-document structure and information and . When creating new documents the
-document ID is optional. For updating existing documents, you must
-provide the document ID, revision information, and new document values.
-
-For both inserts and updates the basic structure of the JSON is the
-same:
-
-+----------------------------------+-------------------------------------------+
-| Field                            | Description                               |
-+==================================+===========================================+
-| all_or_nothing (optional)        | Sets the database commit mode to use      |
-|                                  | all-or-nothing semantics                  |
-+----------------------------------+-------------------------------------------+
-| docs [array]                     | Bulk Documents Document                   |
-+----------------------------------+-------------------------------------------+
-|         _id (optional)           | List of changes, field-by-field, for this |
-|                                  | document                                  |
-+----------------------------------+-------------------------------------------+
-|         _rev (optional)          | Document ID                               |
-+----------------------------------+-------------------------------------------+
-|         _deleted (optional)      | Update sequence number                    |
-+----------------------------------+-------------------------------------------+
-
-Inserting Documents in Bulk
----------------------------
-
-To insert documents in bulk into a database you need to supply a JSON
-structure with the array of documents that you want to add to the
-database. Using this method you can either include a document ID, or
-allow the document ID to be automatically generated.
-
-For example, the following inserts three new documents, two with the
-supplied document IDs, and one which will have a document ID generated:
-
-.. code-block:: javascript
-
-    {
-       "docs" : [
-          {
-             "_id" : "FishStew",
-             "servings" : 4,
-             "subtitle" : "Delicious with fresh bread",
-             "title" : "Fish Stew"
-          },
-          {
-             "_id" : "LambStew",
-             "servings" : 6,
-             "subtitle" : "Delicious with scone topping",
-             "title" : "Lamb Stew"
-          },
-          {
-             "servings" : 8,
-             "subtitle" : "Delicious with suet dumplings",
-             "title" : "Beef Stew"
-          },
-       ]
-    }
-          
-
-The return type from a bulk insertion will be 201, with the content of
-the returned structure indicating specific success or otherwise messages
-on a per-document basis.
-
-The return structure from the example above contains a list of the
-documents created, here with the combination and their revision IDs:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_bulk_docs
-    Content-Type: application/json
-
-    [
-       {
-          "id" : "FishStew",
-          "rev" : "1-9c65296036141e575d32ba9c034dd3ee",
-       },
-       {
-          "id" : "LambStew",
-          "rev" : "1-34c318924a8f327223eed702ddfdc66d",
-       },
-       {
-          "id" : "7f7638c86173eb440b8890839ff35433",
-          "rev" : "1-857c7cbeb6c8dd1dd34a0c73e8da3c44",
-       }
-    ]
-              
-
-The content and structure of the returned JSON will depend on the transaction
-semantics being used for the bulk update; see :ref:`api/db/bulk_docs/semantics`
-for more information. Conflicts and validation errors when updating documents in
-bulk must be handled separately; see :ref:`api/db/bulk_docs/validation`.
-
-Updating Documents in Bulk
---------------------------
-
-The bulk document update procedure is similar to the insertion
-procedure, except that you must specify the document ID and current
-revision for every document in the bulk update JSON string.
-
-For example, you could send the following request:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_bulk_docs
-    Content-Type: application/json
-
-    {
-       "docs" : [
-          {
-             "_id" : "FishStew",
-             "_rev" : "1-9c65296036141e575d32ba9c034dd3ee",
-             "servings" : 4,
-             "subtitle" : "Delicious with freshly baked bread",
-             "title" : "Fish Stew"
-          },
-          {
-             "_id" : "LambStew",
-             "_rev" : "1-34c318924a8f327223eed702ddfdc66d",
-             "servings" : 6,
-             "subtitle" : "Serve with a wholemeal scone topping",
-             "title" : "Lamb Stew"
-          },
-          {
-             "_id" : "7f7638c86173eb440b8890839ff35433"
-             "_rev" : "1-857c7cbeb6c8dd1dd34a0c73e8da3c44",
-             "servings" : 8,
-             "subtitle" : "Hand-made dumplings make a great accompaniment",
-             "title" : "Beef Stew"
-          }
-       ]
-    }
-
-The return structure is the JSON of the updated documents, with the new
-revision and ID information:
-
-.. code-block:: javascript
-
-    [
-       {
-          "id" : "FishStew",
-          "rev" : "2-e7af4c4e9981d960ecf78605d79b06d1"
-       },
-       {
-          "id" : "LambStew",
-          "rev" : "2-0786321986194c92dd3b57dfbfc741ce"
-       },
-       {
-          "id" : "7f7638c86173eb440b8890839ff35433",
-          "rev" : "2-bdd3bf3563bee516b96885a66c743f8e"
-       }
-    ]
-
-You can optionally delete documents during a bulk update by adding the
-``_deleted`` field with a value of ``true`` to each document ID/revision
-combination within the submitted JSON structure.
-
-The return type from a bulk insertion will be 201, with the content of
-the returned structure indicating specific success or otherwise messages
-on a per-document basis.
-
-The content and structure of the returned JSON will depend on the transaction
-semantics being used for the bulk update; see :ref:`api/db/bulk_docs/semantics`
-for more information. Conflicts and validation errors when updating documents in
-bulk must be handled separately; see :ref:`api/db/bulk_docs/validation`.
-
-.. _api/db/bulk_docs/semantics:
-
-Bulk Documents Transaction Semantics
-------------------------------------
-
-CouchDB supports two different modes for updating (or inserting)
-documents using the bulk documentation system. Each mode affects both
-the state of the documents in the event of system failure, and the level
-of conflict checking performed on each document. The two modes are:
-
--  ``non-atomic``
-
-   The default mode is non-atomic, that is, CouchDB will only guarantee
-   that some of the documents will be saved when you send the request.
-   The response will contain the list of documents successfully inserted
-   or updated during the process. In the event of a crash, some of the
-   documents may have been successfully saved, and some will have been
-   lost.
-
-   In this mode, the response structure will indicate whether the
-   document was updated by supplying the new ``_rev`` parameter
-   indicating a new document revision was created. If the update failed,
-   then you will get an ``error`` of type ``conflict``. For example:
-
-   .. code-block:: javascript
-
-       [
-          {
-             "id" : "FishStew",
-             "error" : "conflict",
-             "reason" : "Document update conflict."
-          },
-          {
-             "id" : "LambStew",
-             "error" : "conflict",
-             "reason" : "Document update conflict."
-          },
-          {
-             "id" : "7f7638c86173eb440b8890839ff35433",
-             "error" : "conflict",
-             "reason" : "Document update conflict."
-          }
-       ]
-           
-
-   In this case no new revision has been created and you will need to
-   submit the document update, with the correct revision tag, to update
-   the document.
-
--  ``all-or-nothing``
-
-   In all-or-nothing mode, either all documents are written to the
-   database, or no documents are written to the database, in the event
-   of a system failure during commit.
-
-   In addition, the per-document conflict checking is not performed.
-   Instead a new revision of the document is created, even if the new
-   revision is in conflict with the current revision in the database.
-   The returned structure contains the list of documents with new
-   revisions:
-
-   .. code-block:: javascript
-
-       [
-          {
-             "id" : "FishStew",
-             "rev" : "2-e7af4c4e9981d960ecf78605d79b06d1"
-          },
-          {
-             "id" : "LambStew",
-             "rev" : "2-0786321986194c92dd3b57dfbfc741ce"
-          },
-          {
-             "id" : "7f7638c86173eb440b8890839ff35433",
-             "rev" : "2-bdd3bf3563bee516b96885a66c743f8e"
-          }
-       ]
-
-   When updating documents using this mode the revision of a document
-   included in views will be arbitrary. You can check the conflict
-   status for a document by using the ``conflicts=true`` query argument
-   when accessing the view. Conflicts should be handled individually to
-   ensure the consistency of your database.
-
-   To use this mode, you must include the ``all_or_nothing`` field (set
-   to true) within the main body of the JSON of the request.
-
-The effects of different database operations on the different modes are
-summarized below:
-
-* **Transaction Mode**: ``Non-atomic``
-
-  * **Transaction**: ``Insert``
-
-    * **Cause**: Requested document ID already exists
-    * **Resolution**: Resubmit with different document ID, or update the
-      existing document
-
-  * **Transaction**: ``Update``
-
-    * **Cause**: Revision missing or incorrect
-    * **Resolution**: Resubmit with correct revision
-
-* **Transaction Mode**: ``All-or-nothing``
-
-  * **Transaction**: ``Insert`` / ``Update``
-
-    * **Cause**: Additional revision inserted
-    * **Resolution**: Resolve conflicted revisions
-
-Replication of documents is independent of the type of insert or update.
-The documents and revisions created during a bulk insert or update are
-replicated in the same way as any other document. This can mean that if
-you make use of the all-or-nothing mode the exact list of documents,
-revisions (and their conflict state) may or may not be replicated to
-other databases correctly.
-
-.. _api/db/bulk_docs/validation:
-
-Bulk Document Validation and Conflict Errors
---------------------------------------------
-
-The JSON returned by the ``_bulk_docs`` operation consists of an array
-of JSON structures, one for each document in the original submission.
-The returned JSON structure should be examined to ensure that all of the
-documents submitted in the original request were successfully added to
-the database.
-
-The exact structure of the returned information is:
-
-+----------------------------------+-------------------------------------------+
-| Field                            | Description                               |
-+==================================+===========================================+
-| docs [array]                     | Bulk Documents Document                   |
-+----------------------------------+-------------------------------------------+
-|         id                       | Document ID                               |
-+----------------------------------+-------------------------------------------+
-|         error                    | Error type                                |
-+----------------------------------+-------------------------------------------+
-|         reason                   | Error string with extended reason         |
-+----------------------------------+-------------------------------------------+
-
-When a document (or document revision) is not correctly committed to the
-database because of an error, you should check the ``error`` field to
-determine error type and course of action. Errors will be one of the
-following type:
-
--  ``conflict``
-
-   The document as submitted is in conflict. If you used the default
-   bulk transaction mode then the new revision will not have been
-   created and you will need to re-submit the document to the database.
-   If you used ``all-or-nothing`` mode then you will need to manually
-   resolve the conflicted revisions of the document.
-
-   Conflict resolution of documents added using the bulk docs interface
-   is identical to the resolution procedures used when resolving
-   conflict errors during replication.
-
--  ``forbidden``
-
-   Entries with this error type indicate that the validation routine
-   applied to the document during submission has returned an error.
-
-   For example, if your validation routine includes the following:
-
-   .. code-block:: javascript
-
-        throw({forbidden: 'invalid recipe ingredient'});
-
-   The error returned will be:
-
-   .. code-block:: javascript
-
-       {
-          "id" : "7f7638c86173eb440b8890839ff35433",
-          "error" : "forbidden",
-          "reason" : "invalid recipe ingredient"
-       }
-
-.. _api/db/temp_view:
-.. _api/db/temp_view.post:
-
-``POST /db/_temp_view``
-=======================
-
-* **Method**: ``POST /db/_temp_view``
-* **Request**: JSON with the temporary view definition
-* **Response**: Temporary view result set
-* **Admin Privileges Required**: yes
-
-Creates (and executes) a temporary view based on the view function
-supplied in the JSON request. For example:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_temp_view
-    Content-Type: application/json
-
-    {
-       "map" : "function(doc) { if (doc.value > 9995) { emit(null, doc.value); } }"
-    }
-
-The resulting JSON response is the result from the execution of the
-temporary view:
-
-.. code-block:: javascript
-
-    {
-       "total_rows" : 3,
-       "rows" : [
-          {
-             "value" : 9998.41913029012,
-             "id" : "05361cc6aa42033878acc1bacb1f39c2",
-             "key" : null
-          },
-          {
-             "value" : 9998.94149934853,
-             "id" : "1f443f471e5929dd7b252417625ed170",
-             "key" : null
-          },
-          {
-             "value" : 9998.01511339154,
-             "id" : "1f443f471e5929dd7b252417629c102b",
-             "key" : null
-          }
-       ],
-       "offset" : 0
-    }
-
-The arguments also available to standard view requests also apply to
-temporary views, but the execution of the view may take some time as it
-relies on being executed at the time of the request. In addition to the
-time taken, they are also computationally very expensive to produce. You
-should use a defined view if you want to achieve the best performance.
-
-.. _api/db/purge:
-.. _api/db/purge.post:
-
-``POST /db/_purge``
-===================
-
-* **Method**: ``POST /db/_purge``
-* **Request**: JSON of the document IDs/revisions to be purged
-* **Response**: JSON structure with purged documents and purge sequence
-* **Admin Privileges Required**: no
-
-A database purge permanently removes the references to deleted documents
-from the database. Deleting a document within CouchDB does not actually
-remove the document from the database, instead, the document is marked as
-a deleted (and a new revision is created). This is to ensure that
-deleted documents are replicated to other databases as having been
-deleted. This also means that you can check the status of a document and
-identify that the document has been deleted.
-
-The purge operation removes the references to the deleted documents from
-the database. The purging of old documents is not replicated to other
-databases. If you are replicating between databases and have deleted a
-large number of documents you should run purge on each database.
-
-.. note::
-
-   Purging documents does not remove the space used by them on disk. To
-   reclaim disk space, you should run a database compact (see
-   :ref:`api/db/compact`), and compact views (see :ref:`api/db/compact/ddoc`).
-
-To perform a purge operation you must send a request including the JSON
-of the document IDs that you want to purge. For example:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_purge
-    Content-Type: application/json
-
-    {
-      "FishStew" : [
-        "17-b3eb5ac6fbaef4428d712e66483dcb79"
-        ]
-    }
-
-The format of the request must include the document ID and one or more
-revisions that must be purged.
-
-The response will contain the purge sequence number, and a list of the
-document IDs and revisions successfully purged.
-
-.. code-block:: javascript
-
-    {
-       "purged" : {
-          "FishStew" : [
-             "17-b3eb5ac6fbaef4428d712e66483dcb79"
-          ]
-       },
-       "purge_seq" : 11
-    }
-
-Updating Indexes
-----------------
-
-The number of purges on a database is tracked using a purge sequence.
-This is used by the view indexer to optimize the updating of views that
-contain the purged documents.
-
-When the indexer identifies that the purge sequence on a database has
-changed, it compares the purge sequence of the database with that stored
-in the view index. If the difference between the stored sequence and
-database is sequence is only 1, then the indexer uses a cached list of
-the most recently purged documents, and then removes these documents
-from the index individually. This prevents completely rebuilding the
-index from scratch.
-
-If the difference between the stored sequence number and current
-database sequence is greater than 1, then the view index is entirely
-rebuilt. This is an expensive operation as every document in the
-database must be examined.
-
-.. _api/db/all_docs:
-.. _api/db/all_docs.get:
-
-``GET /db/_all_docs``
-=====================
-
-* **Method**: ``GET /db/_all_docs``
-* **Request**: None
-* **Response**: JSON object containing document information, ordered by the
-  document ID
-* **Admin Privileges Required**: no
-* **Query Arguments**:
-
-  * **Argument**: descending
-
-    * **Description**:  Return the documents in descending by key order
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: endkey
-
-    * **Description**:  Stop returning records when the specified key is reached
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: endkey_docid
-
-    * **Description**:  Stop returning records when the specified document ID is
-      reached
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: group
-
-    * **Description**:  Group the results using the reduce function to a group
-      or single row
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: group_level
-
-    * **Description**:  Specify the group level to be used
-    * **Optional**: yes
-    * **Type**: numeric
-
-  * **Argument**: include_docs
-
-    * **Description**:  Include the full content of the documents in the return
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: false
-
-  * **Argument**: inclusive_end
-
-    * **Description**:  Specifies whether the specified end key should be
-      included in the result
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: true
-
-  * **Argument**: key
-
-    * **Description**:  Return only documents that match the specified key
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: limit
-
-    * **Description**:  Limit the number of the returned documents to the
-      specified number
-    * **Optional**: yes
-    * **Type**: numeric
-
-  * **Argument**: reduce
-
-    * **Description**:  Use the reduction function
-    * **Optional**: yes
-    * **Type**: boolean
-    * **Default**: true
-
-  * **Argument**: skip
-
-    * **Description**:  Skip this number of records before starting to return
-      the results
-    * **Optional**: yes
-    * **Type**: numeric
-    * **Default**: 0
-
-  * **Argument**: stale
-
-    * **Description**:  Allow the results from a stale view to be used
-    * **Optional**: yes
-    * **Type**: string
-    * **Default**:
-    * **Supported Values**:
-
-      * **ok**: Allow stale views
-
-  * **Argument**: startkey
-
-    * **Description**:  Return records starting with the specified key
-    * **Optional**: yes
-    * **Type**: string
-
-  * **Argument**: startkey_docid
-
-    * **Description**:  Return records starting with the specified document ID
-    * **Optional**: yes
-    * **Type**: string
-
-Returns a JSON structure of all of the documents in a given database.
-The information is returned as a JSON structure containing meta
-information about the return structure, and the list documents and basic
-contents, consisting the ID, revision and key. The key is generated from
-the document ID.
-
-+----------------------------------+-------------------------------------------+
-| Field                            | Description                               |
-+==================================+===========================================+
-| offset                           | Offset where the document list started    |
-+----------------------------------+-------------------------------------------+
-| rows [array]                     | Array of document object                  |
-+----------------------------------+-------------------------------------------+
-| total_rows                       | Number of documents in the database/view  |
-+----------------------------------+-------------------------------------------+
-| update_seq                       | Current update sequence for the database  |
-+----------------------------------+-------------------------------------------+
-
-By default the information returned contains only the document ID and
-revision. For example, the request:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_all_docs
-    Accept: application/json
-
-Returns the following structure:
-
-.. code-block:: javascript
-
-    {
-       "total_rows" : 18386,
-       "rows" : [
-          {
-             "value" : {
-                "rev" : "1-bc0d5aed1e339b1cc1f29578f3220a45"
-             },
-             "id" : "Aberffrawcake",
-             "key" : "Aberffrawcake"
-          },
-          {
-             "value" : {
-                "rev" : "3-68a20c89a5e70357c20148f8e82ca331"
-             },
-             "id" : "Adukiandorangecasserole-microwave",
-             "key" : "Adukiandorangecasserole-microwave"
-          },
-          {
-             "value" : {
-                "rev" : "3-9b2851ed9b6f655cc4eb087808406c60"
-             },
-             "id" : "Aioli-garlicmayonnaise",
-             "key" : "Aioli-garlicmayonnaise"
-          },
-          ...
-             ],
-       "offset" : 0
-    }
-
-The information is returned in the form of a temporary view of all the
-database documents, with the returned key consisting of the ID of the
-document. The remainder of the interface is therefore identical to the
-View query arguments and their behavior.
-
-.. _api/db/all_docs.post:
-
-``POST /db/_all_docs``
-======================
-
-* **Method**: ``POST /db/_all_docs``
-* **Request**: JSON of the document IDs you want included
-* **Response**: JSON of the returned view
-* **Admin Privileges Required**: no
-
-The ``POST`` to ``_all_docs`` allows to specify multiple keys to be
-selected from the database. This enables you to request multiple
-documents in a single request, in place of multiple
-:ref:`api/doc.get` requests.
-
-The request body should contain a list of the keys to be returned as an
-array to a ``keys`` object. For example:
-
-.. code-block:: http
-
-    POST http://couchdb:5984/recipes/_all_docs
-    User-Agent: MyApp/0.1 libwww-perl/5.837
-
-    {
-       "keys" : [
-          "Zingylemontart",
-          "Yogurtraita"
-       ]
-    }
-
-The return JSON is the all documents structure, but with only the
-selected keys in the output:
-
-.. code-block:: javascript
-
-    {
-       "total_rows" : 2666,
-       "rows" : [
-          {
-             "value" : {
-                "rev" : "1-a3544d296de19e6f5b932ea77d886942"
-             },
-             "id" : "Zingylemontart",
-             "key" : "Zingylemontart"
-          },
-          {
-             "value" : {
-                "rev" : "1-91635098bfe7d40197a1b98d7ee085fc"
-             },
-             "id" : "Yogurtraita",
-             "key" : "Yogurtraita"
-          }
-       ],
-       "offset" : 0
-    }
-
-.. _api/db/missing_revs:
-.. _api/db/missing_revs.post:
-
-``POST /db/_missing_revs``
-==========================
-
-* **Method**: ``POST /db/_missing_revs``
-* **Request**: JSON list of document revisions
-* **Response**: JSON of missing revisions
-* **Admin Privileges Required**: no
-
-.. _api/db/revs_diff:
-.. _api/db/revs_diff.post:
-
-``POST /db/_revs_diff``
-=======================
-
-* **Method**: ``POST /db/_revs_diff``
-* **Request**: JSON list of document revisions
-* **Response**: JSON list of differences from supplied document/revision list
-* **Admin Privileges Required**: no
-
-.. _api/db/security:
-.. _api/db/security.get:
-
-``GET /db/_security``
-=====================
-
-* **Method**: ``GET /db/_security``
-* **Request**: None
-* **Response**: JSON of the security object
-* **Admin Privileges Required**: no
-
-Gets the current security object from the specified database. The
-security object consists of two compulsory elements, ``admins`` and
-``readers``, which are used to specify the list of users and/or roles
-that have admin and reader rights to the database respectively. Any
-additional fields in the security object are optional. The entire
-security object is made available to validation and other internal
-functions so that the database can control and limit functionality.
-
-To get the existing security object you would send the following
-request:
-
-.. code-block:: javascript
-
-    {
-       "admins" : {
-          "roles" : [],
-          "names" : [
-             "mc",
-             "slp"
-          ]
-       },
-       "readers" : {
-          "roles" : [],
-          "names" : [
-             "tim",
-             "brian"
-          ]
-       }
-    }
-
-Security object structure is:
-
-* **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
-
-.. note::
-   If the security object for a database has never been set, then the
-   value returned will be empty.
-
-.. _api/db/security.put:
-
-``PUT /db/_security``
-=====================
-
-* **Method**: ``PUT /db/_security``
-* **Request**: JSON specifying the admin and user security for the database
-* **Response**: JSON status message
-* **Admin Privileges Required**: no
-
-Sets the security object for the given database.For example, to set the
-security object for the ``recipes`` database:
-
-.. code-block:: javascript
-
-    PUT http://couchdb:5984/recipes/_security
-    Content-Type: application/json
-
-    {
-       "admins" : {
-          "roles" : [],
-          "names" : [
-             "mc",
-             "slp"
-          ]
-       },
-       "readers" : {
-          "roles" : [],
-          "names" : [
-             "tim",
-             "brian"
-          ]
-       }
-    }
-
-If the setting was successful, a JSON status object will be returned:
-
-.. code-block:: javascript
-
-    {
-       "ok" : true
-    }
-
-.. _api/db/revs_limit:
-.. _api/db/revs_limit.get:
-
-``GET /db/_revs_limit``
-=======================
-
-* **Method**: ``GET /db/_revs_limit``
-* **Request**: None
-* **Response**: The current revision limit setting
-* **Admin Privileges Required**: no
-
-
-Gets the current ``revs_limit`` (revision limit) setting.
-
-For example to get the current limit:
-
-.. code-block:: http
-
-    GET http://couchdb:5984/recipes/_revs_limit
-    Content-Type: application/json
-
-The returned information is the current setting as a numerical scalar:
-
-.. code-block:: javascript
-
-    1000
-
-.. _api/db/revs_limit.put:
-
-``PUT /db/_revs_limit``
-=======================
-
-* **Method**: ``PUT /db/_revs_limit``
-* **Request**: A scalar integer of the revision limit setting
-* **Response**: Confirmation of setting of the revision limit
-* **Admin Privileges Required**: no
-
-Sets the maximum number of document revisions that will be tracked by
-CouchDB, even after compaction has occurred. You can set the revision
-limit on a database by using ``PUT`` with a scalar integer of the limit
-that you want to set as the request body.
-
-For example to set the revs limit to 100 for the ``recipes`` database:
-
-.. code-block:: http
-
-    PUT http://couchdb:5984/recipes/_revs_limit
-    Content-Type: application/json
-
-    100
-
-If the setting was successful, a JSON status object will be returned:
-
-.. code-block:: javascript
-
-    {
-       "ok" : true
-    }
-
-.. _JSON object: #table-couchdb-api-db_db-json-changes