Sofa.Bulk (sofa v0.7.0)

Copy Markdown View Source

Writes and reads documents in bulk, via _bulk_docs and _bulk_get.

If the only tool you have is CouchDB, then everything looks like {:ok, :relax}

See the bulk API section of https://docs.couchdb.org/en/stable/api/database/bulk-api.html. Both endpoints answer per document rather than per request: a bulk write returns 201 even when some documents conflicted, and a bulk read returns 200 with the missing ones marked. So the results are a list, one entry per requested document and in the same order, each either {:ok, %Sofa.Doc{}} or {:error, reason, document_or_id}, with the reason an atom such as :conflict or :not_found.

Examples

{:ok, results} = Sofa.Bulk.save(db, [fish, lamb])
Enum.map(results, fn {:ok, doc} -> doc.rev; {:error, :conflict, doc} -> doc.id end)

{:ok, [{:ok, fish}, {:error, :not_found, "nobody"}]} = Sofa.Bulk.get(db, ["FishStew", "nobody"])

Summary

Functions

Deletes documents in one request, each needing its current rev. The results carry the documents with their deletion revisions.

Fetches documents in one request, by id or by {id, rev} for a specific revision. Options are the documented query parameters: revs: true adds the revision history under "_revisions" in each document's body, latest: true the latest leaf revisions, attachments: true inline attachment content.

Saves documents in one request. New documents get a revision, updated ones need their current rev, and a document saved via delete/2 or with "_deleted" => true in its body is deleted.

Types

error()

@type error() :: Sofa.Response.error() | term()

reason()

@type reason() :: :conflict | :forbidden | :not_found | :bad_request | atom()

result()

@type result() :: {:ok, Sofa.Doc.t()} | {:error, reason(), Sofa.Doc.t() | String.t()}

Functions

delete(sofa, docs)

@spec delete(Sofa.t(), [Sofa.Doc.t()]) :: {:ok, [result()]} | {:error, error()}

Deletes documents in one request, each needing its current rev. The results carry the documents with their deletion revisions.

get(sofa, refs, opts \\ [])

@spec get(Sofa.t(), [String.t() | {String.t(), String.t()}], keyword()) ::
  {:ok, [result()]} | {:error, error()}

Fetches documents in one request, by id or by {id, rev} for a specific revision. Options are the documented query parameters: revs: true adds the revision history under "_revisions" in each document's body, latest: true the latest leaf revisions, attachments: true inline attachment content.

save(sofa, docs, opts \\ [])

@spec save(Sofa.t(), [Sofa.Doc.t()], keyword()) ::
  {:ok, [result()]} | {:error, error()}

Saves documents in one request. New documents get a revision, updated ones need their current rev, and a document saved via delete/2 or with "_deleted" => true in its body is deleted.

With new_edits: false the revisions are stored as given, as a replicator does. CouchDB then returns no per-document results and every document is reported as {:ok, doc} unchanged.