Couchbeam - simple erlang CouchDB framework.

Copyright 2009-2012 (c) Benoit Chesneau <benoitc@e-engura.org>

Version: 0.7.3

couchbeam is a simple erlang CouchDB framework. couchbeam provides you a full featured and easy client to access and manage multiple couchdb Nodes. Useful modules are:

couchbeam
The couchbeam module is the main interface for interaction with this application. It includes functions for managing connections to CouchDB servers and Couchdb Databases and for performings documents creations, updates, deletes, views...
couchbeam_doc
Module to manipulate Documents structures. You can set values, updates keys, ..
couchbeam_attachments
Module to manipulate attachments. You can add, remove attachments in a Document structure (inline attachments).
couchbeam_view
Module to manage view results you get from couchbeam:view and couchbeam:all_docs functions. You can count results, fetch all, get the first result of a view, fold between them or execute a function on each rows.

The goal of couchbeam is to give all access to CouchDB >0.10 API via HTTP in erlang.

Read the NEWS file to get last changelog.

Installation

Download the sources from our Github repository.

To buildd the application simply run 'make'. This should build .beam, .app files and documentation.

To run tests run 'make test'. To generate doc, run 'make doc'.

Basic Usage

The basic pattern of use of couchbeam is:

1. Start couchbeam

Couchbeam is an OTP application. You have to start it first before using all the functions. couchbeam applications will manage for you connections to CouchDB via ibrowse and will maintain a collections of unique ids from CouchDB to reduce the number of HTTP connections.

application:start(sasl),
application:start(ibrowse),
application:start(couchbeam).

Note if you want to use ssl, you will need to start crypto, public_key and ssl applications too.

2. Create a connection to the server

To create a connection to a server machine:

Host = "localhost",
Port = 5984,
Prefix = "",
Options = [],
S = couchbeam:server_connection(Host, Port, Prefix, Options).

Test the connection with couchbeam:server_info/1:

{ok, _Version} = couchbeam:server_info(S).

3. Open or Create a database

All CouchDB document operations are done in databases. To open a database simply do:

Options = [],
{ok, Db} = couchbeam:open_db(Server, "testdb", Options).

To create a new one :

Options = [],
{ok, Db} = couchbeam:create_db(Server, "testdb", Options).

You can also use the shorcut couchbeam:open_or_create_db/3 that will create a database if it doesn't exist.

4. Make a new document

Make a new document:

Doc = {[
{<<"_id">>, <<"test">>},
{<<"content">>, <<"some text">>}
]}.

And save it to the database:

{ok, Doc1} = couchbeam:save_doc(Db, Doc).

The couchbeam:save_doc/2 return a new document with updated revision and if you don't specify the _id, a unique document id.

To change an document property use functions from couchbeam_doc.

5. Retrieve a document

To retrieve a document do:

{ok, Doc2} = couchbeam:open_doc(Db, "test").

If you want a specific revision:

Rev = couchbeam_doc:get_rev(Doc1),
Options = [{rev, Rev}],
{ok, Doc3} = couchbeam:open_doc(Db, "test", Options).

Here we get the revision from the document we previously stored. Any options from the CouchDB API can be used.

6. Get all documents

To get all documents you have first to create an object that will keep all informations.

Options = [include_docs],
{ok, AllDocs} = couchbeam_view:fetch(Db, 'all_docs', Options).

Ex of results:

{ok,[{[{<<"id">>,<<"7a0ce91d0d0c5e5b51e904d1ee3266a3">>},
          {<<"key">>,<<"7a0ce91d0d0c5e5b51e904d1ee3266a3">>},
          {<<"value">>,
           {[{<<"rev">>,<<"15-15c0b3c4efa74f9a80d28ac040f18bdb">>}]}},
          {<<"doc">>,
           {[{<<"_id">>,<<"7a0ce91d0d0c5e5b51e904d1ee3266a3">>},
             {<<"_rev">>,<<"15-15c0b3c4efa74f9a80d28ac040f18"...>>}]}}]},
        ]}.

All functions to manipulate these results are in couchbeam_view module.

7. Couchdb views - Map/Reduce

Views are workin like all_docs. You have to create a View object before doing anything.

Options = [],
DesignNam = "designname",
ViewName = "viewname",
{ok, ViewResults} = couchbeam_view:fetch(Db, {DesignNam, ViewName}, Options).

Like the all_docs function, use the functions from couchbeam_view module to manipulate results. You can pass any querying options from the view API.

Design doc are created like any documents:

DesignDoc = {[
        {<<"_id">>, <<"_design/couchbeam">>},
        {<<"language">>,<<"javascript">>},
        {<<"views">>,
            {[{<<"test">>,
                {[{<<"map">>,
                    <<"function (doc) {\n if (doc.type == \"test\") {\n emit(doc._id, doc);\n}\n}">>
                }]}
            },{<<"test2">>,
                {[{<<"map">>,
                    <<"function (doc) {\n if (doc.type == \"test2\") {\n emit(doc._id, null);\n}\n}">>
                }]}
            }]}
        }
    ]},
{ok, DesignDoc1} = couchbeam:save_doc(Db, DesignDoc).

You can also use couchapp to manage them more easily.

8. Stream View results

New feature in couchbeam 0.7. While you can get results using couchbeam_views:fetch/2i, you can also retrieve all rows in a streaming fashion:

ViewFun = fun(Ref, F) ->
    receive
        {row, Ref, done} ->
            io:format("done", []),
            done;
        {row, Ref, Row} ->
            io:format("got ~p~n", [Row]),
            F(Ref, F);
        {error, Ref, Error} ->
            io:format("error: ~p~n", [Error])
    end
end,

{ok, StartRef, _ViewPid} = couchbeam_view:stream(Db, 'all_docs', self()),
ViewFun(StartRef, ViewFun),
{ok, StartRef2, _ViewPid2} = couchbeam_view:stream(Db, 'all_docs', self(), [include_docs]),
ViewFun(StartRef2, ViewFun).

You can of course do the same with a view:

DesignNam = "designname",
ViewName = "viewname",
{ok, StartRef3, _ViewPid3} = couchbeam_view:stream(Db, {DesignNam, ViewName}, self(), [include_docs]),
ViewFun(StartRef3, ViewFun).

9. Put,Fetch and Delete documents attachments

You can add attachments to any CouchDB documents. Attachments could be anything.

To send an attachment:

DocID = "test",
AttName = "test.txt",
Att = "some content I want to attach",
Options = []
{ok, _Result} = couchbeam:put_attachment(Db, DocId, AttName, Att, Options).

All attachments are streamed to CoucDB. Att could be also be an iolist or functions, see couchbeam:put_attachment/5 for more informations.

To fetch an attachment:

{ok Att1} = couchbeam:fetch_attachment(Db, DocId, AttName).

You can use couchbeam:stream_fetch_attachment/6 for the stream fetch.

To delete an attachment:

{ok, Doc4} = couchbeam:open_doc(Db, DocID),
ok = couchbeam:delete_attachment(Db, Doc4, AttName).

10. Changes

CouchDB provides a means to get a list of changes made to documents in the database. With couchbeam you can get changes using couchbeam_changes:fetch/2. This function returns all changes immediately. But you can also retrieve all changes rows using longpolling :

Options = [],
{ok, LastSeq, Rows} = couchbeam_changes:fetch(Db, Options).

Options can be any Changes query parameters. See http://wiki.apache.org/couchdb/HTTP_database_API#Changes for more informations.

You can also get continuous changes:

ChangesFun = fun(ReqId, F) ->
    receive
        {change, StartRef, {done, LastSeq}} ->
            io:format("stopped, last seq is ~p~n", [LastSeq]),
            ok;
        {change, StartRef, Row} ->
            io:format("change row ~p ~n", [Row]),
            F(StartRef, F);    
        {error, StartRef, LastSeq, Error}->
            io:format("error ? ~p ~n, last seq: ~p~n", [Error, LastSeq])
    end 
end,
Pid = self(),
Options = [continuous, heartbeat],
{ok, StartRef, _ChangePid} = couchbeam_changes:stream(Db, Pid, Options),
ChangesFun(StartRef, ChangesFun).

Authentication/ Connections options

You can authentication to the database or CouchDB server by filling options to the Option list in couchbeam:server_connection/4 for the server or in couchbeam:create_db/3, couchbeam:open_db/3, couchbeam:wopen_or_create_db/3 functions.

To set basic_auth on a server:

```
Host = "localhost",
Port = 5984,
Prefix = "",
UserName = "guest", 
Password = "test",
Options = [{basic_auth, {UserName, Password}],
S1 = couchbeam:server_connection(Host, Port, Prefix, Options).

Couchbeam support SSL, OAuth, Basic Authentication, and Proxy. You can also set a cookie. For more informations about the options have a look in couchbeam:server_connection/4 documentation.

Get involved

If you have any question don't hesitate to join us on #couchdbkit IRC channel or on the mailing-list.

Report bugs and make feature requests on the ticket system.


Generated by EDoc, Aug 31 2012, 10:02:31.