Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Core Types Reference

All core types are defined in the rouchdb-core crate and re-exported from the top-level rouchdb crate. You can import them with:

#![allow(unused)]
fn main() {
use rouchdb::*; // Re-exports all types from rouchdb-core::document
}

Types marked #[non_exhaustive] below are read by applications but built by the library (or by custom adapters, through their constructors); option and data structs are built with a struct literal ending in ..Default::default(). See API Stability for the rules.


Document

The fundamental unit of data in RouchDB.

#![allow(unused)]
fn main() {
pub struct Document {
    pub id: String,
    pub rev: Option<Revision>,
    pub deleted: bool,
    pub data: serde_json::Value,
    pub attachments: HashMap<String, AttachmentMeta>,
}
}
FieldTypeDescription
idStringThe document’s unique identifier (_id in CouchDB).
revOption<Revision>The current revision. None for new documents that have not yet been written.
deletedboolWhether this document is a deletion tombstone (_deleted in CouchDB).
dataserde_json::ValueThe document body as a JSON value. Does not include underscore-prefixed CouchDB metadata fields (_id, _rev, _deleted, _attachments).
attachmentsHashMap<String, AttachmentMeta>Map of attachment names to their metadata.

Methods

MethodSignatureDescription
newfn new(id: impl Into<String>, data: serde_json::Value) -> SelfA document to create: no revision, not deleted, no attachments. Document also implements Default, so a struct literal can end with ..Default::default() (or ..Document::new(id, data)).
from_jsonfn from_json(value: serde_json::Value) -> Result<Self>Parse a CouchDB-style JSON object. Extracts _id, _rev, _deleted, and _attachments from the value and puts the remaining fields in data. Returns RouchError::BadRequest if the value is not a JSON object.
to_jsonfn to_json(&self) -> serde_json::ValueConvert back to a CouchDB-style JSON object with underscore-prefixed metadata fields included.

Example

#![allow(unused)]
fn main() {
// Parse from CouchDB JSON
let doc = Document::from_json(json!({
    "_id": "user:alice",
    "_rev": "3-abc123",
    "name": "Alice",
    "age": 30
}))?;

assert_eq!(doc.id, "user:alice");
assert_eq!(doc.data["name"], "Alice");

// Convert back
let json = doc.to_json();
assert_eq!(json["_id"], "user:alice");
assert_eq!(json["_rev"], "3-abc123");
}

Revision

A CouchDB revision identifier in the format {pos}-{hash}.

#![allow(unused)]
fn main() {
pub struct Revision {
    pub pos: u64,
    pub hash: String,
}
}
FieldTypeDescription
posu64The generation number. Starts at 1, increments with each edit.
hashStringA hex digest string identifying this specific revision.

Trait Implementations

TraitBehavior
DisplayFormats as "{pos}-{hash}" (e.g., "3-abc123").
FromStrParses from "{pos}-{hash}" format. Returns RouchError::InvalidRev on failure.
Ord / PartialOrdOrders by pos first, then by hash lexicographically. This is the deterministic winning revision algorithm used by CouchDB.
Eq / HashTwo revisions are equal if both pos and hash match.
Serialize / DeserializeSerializes as a JSON object with pos and hash fields.

Example

#![allow(unused)]
fn main() {
// Create directly
let rev = Revision::new(3, "abc123".into());
assert_eq!(rev.to_string(), "3-abc123");

// Parse from string
let parsed: Revision = "3-abc123".parse()?;
assert_eq!(parsed.pos, 3);
assert_eq!(parsed.hash, "abc123");

// Ordering (deterministic winner)
let r1 = Revision::new(2, "aaa".into());
let r2 = Revision::new(2, "bbb".into());
assert!(r1 < r2); // Same pos, "bbb" > "aaa" lexicographically
}

Seq

A database sequence identifier. Local adapters use numeric sequences; CouchDB 3.x uses opaque string sequences.

#![allow(unused)]
fn main() {
pub enum Seq {
    Num(u64),
    Str(String),
}
}
VariantDescription
Num(u64)Numeric sequence, used by local adapters (memory, redb). Starts at 0.
Str(String)Opaque string sequence, used by CouchDB 3.x. Must be passed back as-is.

Methods

MethodSignatureDescription
zerofn zero() -> SelfReturns Seq::Num(0) – the starting point (beginning of changes).
as_numfn as_num(&self) -> u64Extract the numeric value. For Str variants, parses the numeric prefix before the first - (e.g., "13-g1A..." returns 13). Returns 0 if unparseable.
to_query_stringfn to_query_string(&self) -> StringFormat for use in HTTP query parameters. Num becomes its decimal string, Str is returned as-is.

Trait Implementations

TraitBehavior
DefaultReturns Seq::Num(0).
DisplayFormats the numeric value or string.
From<u64>Creates Seq::Num(n).
Serialize / DeserializeUses #[serde(untagged)] – serializes as either a number or string in JSON.

DbInfo

Database metadata returned by Adapter::info().

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct DbInfo {
    pub db_name: String,
    pub doc_count: u64,
    pub doc_del_count: u64,
    pub update_seq: Seq,
}
}
FieldTypeDescription
db_nameStringThe name of the database.
doc_countu64Number of non-deleted documents.
doc_del_countu64Number of deleted documents.
update_seqSeqThe current update sequence number. Increments with every write.

Custom adapters build it with DbInfo::new(db_name, doc_count, doc_del_count, update_seq).


DocResult

The result of a single document write operation.

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct DocResult {
    pub ok: bool,
    pub id: String,
    pub rev: Option<String>,
    pub error: Option<String>,
    pub reason: Option<String>,
}
}
FieldTypeDescription
okbooltrue if the write succeeded.
idStringThe document ID.
revOption<String>The new revision string if the write succeeded.
errorOption<String>Error type (e.g., "conflict") if the write failed.
reasonOption<String>Human-readable error description.

Custom adapters and plugins build it with DocResult::ok(id, rev) or DocResult::error(id, error, reason).


AttachmentMeta

Metadata for a document attachment.

#![allow(unused)]
fn main() {
pub struct AttachmentMeta {
    pub content_type: String,
    pub revpos: u64,
    pub digest: String,
    pub length: u64,
    pub stub: bool,
    pub encoding: Option<String>,
    pub encoded_length: Option<u64>,
    pub data: Option<Vec<u8>>,
}
}
FieldTypeDescription
content_typeStringMIME type (e.g., "image/png").
revposu64Generation of the revision that uploaded the data (CouchDB’s revpos). A write that sends the data (inline or with put_attachment) sets it to the new generation, even for identical bytes; stubs, body edits and replication keep it. 0 when unknown (stored before 0.5), and then omitted from the JSON.
digestStringContent digest for deduplication.
lengthu64Size in bytes.
stubboolIf true, only metadata is present (no inline data). Defaults to false.
encodingOption<String>How the source stores the bytes (CouchDB reports "gzip" with att_encoding_info=true). Kept from stubs only: rouchdb stores and serves decoded bytes.
encoded_lengthOption<u64>Size of the encoded bytes at the source.
dataOption<Vec<u8>>Inline binary data, if available. Omitted from serialization when None.

AttachmentMeta implements Default; AttachmentMeta::new(content_type, bytes) builds an inline attachment (digest and length computed), and meta.to_json(data) gives the CouchDB _attachments member (inline with data, a stub otherwise).


DocMetadata

Internal metadata stored per document in an adapter. Not typically used in application code.

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct DocMetadata {
    pub id: String,
    pub rev_tree: RevTree,
    pub seq: u64,
}
}
FieldTypeDescription
idStringThe document ID.
rev_treeRevTreeThe full revision tree for this document.
sequ64The last sequence number at which this document was modified.

PutResponse

Simple response for a successful document write (used in some internal paths).

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct PutResponse {
    pub ok: bool,
    pub id: String,
    pub rev: String,
}
}
FieldTypeDescription
okboolAlways true for success.
idStringThe document ID.
revStringThe new revision string.

Options Structs

GetOptions

Options for document retrieval.

#![allow(unused)]
fn main() {
pub struct GetOptions {
    pub rev: Option<String>,
    pub conflicts: bool,
    pub open_revs: Option<OpenRevs>,
    pub revs: bool,
    pub revs_info: bool,
    pub latest: bool,
    pub attachments: bool,
}
}
FieldTypeDefaultDescription
revOption<String>NoneRetrieve a specific revision instead of the winner.
conflictsboolfalseInclude conflicting revisions in the response.
open_revsOption<OpenRevs>NoneReturn all open (leaf) revisions.
revsboolfalseInclude full revision history.
revs_infoboolfalseInclude revision info with status (available, missing, deleted) for each revision.
latestboolfalseIf rev is specified and is not a leaf, return the latest leaf revision instead.
attachmentsboolfalseInclude inline Base64 attachment data in the response.

OpenRevs

#![allow(unused)]
fn main() {
pub enum OpenRevs {
    All,
    Specific(Vec<String>),
}
}
VariantDescription
AllReturn all leaf revisions.
Specific(Vec<String>)Return only these specific revisions.

BulkDocsOptions

Options for bulk document writes.

#![allow(unused)]
fn main() {
pub struct BulkDocsOptions {
    pub new_edits: bool,
}
}
FieldTypeDefaultDescription
new_editsbooltrueWhen true, the adapter generates new revisions and checks for conflicts. When false (replication mode), revisions are accepted as-is and merged into the revision tree.

BulkDocsOptions::default() is the same as BulkDocsOptions::new() (user-mode writes, new_edits: true); replication mode must be requested explicitly with BulkDocsOptions::replication(). (Before 0.5, Default meant replication mode.)

Constructornew_edits ValueUse Case
BulkDocsOptions::new()trueNormal application writes.
BulkDocsOptions::replication()falseReplication protocol writes.

AllDocsOptions

Options for querying all documents.

#![allow(unused)]
fn main() {
pub struct AllDocsOptions {
    pub start_key: Option<String>,
    pub end_key: Option<String>,
    pub key: Option<String>,
    pub keys: Option<Vec<String>>,
    pub include_docs: bool,
    pub descending: bool,
    pub skip: u64,
    pub limit: Option<u64>,
    pub inclusive_end: bool,
    pub conflicts: bool,
    pub update_seq: bool,
}
}
FieldTypeDefaultDescription
start_keyOption<String>NoneStart of the key range (inclusive).
end_keyOption<String>NoneEnd of the key range (inclusive by default, see inclusive_end).
keyOption<String>NoneReturn only the row matching this exact key.
keysOption<Vec<String>>NoneReturn only the rows matching these exact keys.
include_docsboolfalseInclude the full document body in each row.
descendingboolfalseReturn rows in descending key order.
skipu640Number of rows to skip before returning results.
limitOption<u64>NoneMaximum number of rows to return.
inclusive_endbooltrueWhether the end_key is included in the range.
conflictsboolfalseInclude _conflicts for each document (requires include_docs).
update_seqboolfalseInclude the current update_seq in the response.

AllDocsOptions::default() is the same as AllDocsOptions::new(): inclusive_end: true, like CouchDB. (Before 0.5, Default set inclusive_end: false.)


ChangesOptions

Options for the changes feed.

#![allow(unused)]
fn main() {
pub struct ChangesOptions {
    pub since: Seq,
    pub limit: Option<u64>,
    pub descending: bool,
    pub include_docs: bool,
    pub live: bool,
    pub doc_ids: Option<Vec<String>>,
    pub selector: Option<serde_json::Value>,
    pub conflicts: bool,
    pub style: ChangesStyle,
}
}
FieldTypeDefaultDescription
sinceSeqSeq::Num(0)Return changes after this sequence. Use Seq::zero() for all changes.
limitOption<u64>NoneMaximum number of change events to return.
descendingboolfalseReturn changes in reverse sequence order.
include_docsboolfalseInclude the full document body in each change event.
liveboolfalseEnable continuous (live) changes feed.
doc_idsOption<Vec<String>>NoneFilter changes to only these document IDs.
selectorOption<serde_json::Value>NoneMango selector to filter changes. Only changes matching the selector are returned.
conflictsboolfalseInclude conflicting revisions per change event.
styleChangesStyleMainOnlyMainOnly returns only the winning revision; AllDocs returns all leaf revisions.

FindOptions

Options for a Mango find query (from rouchdb-query).

#![allow(unused)]
fn main() {
pub struct FindOptions {
    pub selector: serde_json::Value,
    pub fields: Option<Vec<String>>,
    pub sort: Option<Vec<SortField>>,
    pub limit: Option<u64>,
    pub skip: Option<u64>,
}
}
FieldTypeDefaultDescription
selectorserde_json::ValueValue::NullThe Mango selector (query) to match documents against. Must be a JSON object.
fieldsOption<Vec<String>>NoneField projection – only include these fields in results. _id is always included.
sortOption<Vec<SortField>>NoneSort specification. Each entry is a field name or a {field: direction} map.
limitOption<u64>NoneMaximum number of matching documents to return.
skipOption<u64>NoneNumber of matching documents to skip.

SortField

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub enum SortField {
    Simple(String),
    WithDirection(HashMap<String, String>),
}
}
VariantExample JSONDescription
Simple(String)"name"Sort by field in ascending order.
WithDirection(HashMap<String, String>){"age": "desc"}Sort by field with explicit direction ("asc" or "desc").

ViewQueryOptions

Options for map/reduce view queries (from rouchdb-query).

#![allow(unused)]
fn main() {
pub struct ViewQueryOptions {
    pub key: Option<serde_json::Value>,
    pub keys: Option<Vec<serde_json::Value>>,
    pub start_key: Option<serde_json::Value>,
    pub end_key: Option<serde_json::Value>,
    pub inclusive_end: bool,
    pub descending: bool,
    pub skip: u64,
    pub limit: Option<u64>,
    pub include_docs: bool,
    pub reduce: bool,
    pub group: bool,
    pub group_level: Option<u64>,
    pub stale: StaleOption,
}
}
FieldTypeDefaultDescription
keyOption<serde_json::Value>NoneReturn only rows with this exact key (with start_key or end_key, the other bound of the range).
keysOption<Vec<serde_json::Value>>NoneReturn only rows matching any of these keys, in the given order. Several keys exclude key, start_key and end_key.
start_keyOption<serde_json::Value>NoneStart of key range (inclusive). A range no row can be in is a BadRequest.
end_keyOption<serde_json::Value>NoneEnd of key range (inclusive by default).
inclusive_endbooltrueWhether the end_key is included in the range.
descendingboolfalseReverse row order.
skipu640Number of rows to skip.
limitOption<u64>NoneMaximum number of rows to return.
include_docsboolfalseInclude full document body in each row.
reducebooltrueWhether to run the reduce function, if one is given.
groupboolfalseGroup results by key (requires a reduce; without one it is a BadRequest).
group_levelOption<u64>NoneGroup to this many array elements of the key (above 0 it requires a reduce).
staleStaleOptionFalseFalse rebuilds the index before querying (default). Ok uses a potentially stale index. UpdateAfter returns stale results then rebuilds.

ViewQueryOptions::default() is the same as ViewQueryOptions::new() (CouchDB’s defaults above). (Before 0.5, Default left reduce and inclusive_end off.)


GetAttachmentOptions

Options for retrieving attachments.

#![allow(unused)]
fn main() {
pub struct GetAttachmentOptions {
    pub rev: Option<String>,
}
}
FieldTypeDefaultDescription
revOption<String>NoneRetrieve the attachment from a specific revision.

Response Structs

AllDocsResponse

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct AllDocsResponse {
    pub total_rows: u64,
    pub offset: u64,
    pub rows: Vec<AllDocsRow>,
    pub update_seq: Option<Seq>,
}
}
FieldTypeDescription
total_rowsu64Total number of non-deleted documents in the database.
offsetu64Local adapters: the skip applied (like PouchDB). CouchDB / HTTP adapter: the global position of the first row (0 for keys queries, where CouchDB sends null). See Differences from CouchDB.
rowsVec<AllDocsRow>The result rows.
update_seqOption<Seq>The current update sequence, present when update_seq: true was requested.

AllDocsRow

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct AllDocsRow {
    pub id: Option<String>,
    pub key: String,
    pub value: Option<AllDocsRowValue>,
    pub doc: Option<serde_json::Value>,
    pub error: Option<String>,
}
}
FieldTypeDescription
idOption<String>The document ID; None for an error row.
keyStringThe requested key; for a document row, its ID. Set on every row.
valueOption<AllDocsRowValue>The winning revision and deletion flag; None for an error row.
docOption<serde_json::Value>Full document body, present only when include_docs is true and the document is not deleted.
errorOption<String>Some("not_found") when a key requested with keys names no document.

Range and key queries only return live documents, so id and value are always set there. A keys query returns exactly one row per requested key, in request order (reversed with descending, duplicates kept), so rows[i] answers keys[i], as in CouchDB and PouchDB:

Requested keyRow
a live documentid, key, value, and doc with include_docs
a deleted documentvalue.deleted == Some(true), never a doc (CouchDB sends "doc": null)
an unknown IDonly key and error: Some("not_found")

skip and limit count every kind of row. Helpers: row.rev() (the winning revision, if any), row.is_deleted(), row.is_error(), and the constructors AllDocsRow::document(id, value) and AllDocsRow::not_found(key).

The row is a struct with optional members rather than an enum so it maps one-to-one onto the CouchDB/PouchDB JSON row and row.key works for every kind of row.

AllDocsRowValue

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct AllDocsRowValue {
    pub rev: String,
    pub deleted: Option<bool>,
}
}
FieldTypeDescription
revStringThe winning revision string.
deletedOption<bool>Set to Some(true) for deleted documents. Omitted from JSON when None.

ChangesResponse

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct ChangesResponse {
    pub results: Vec<ChangeEvent>,
    pub last_seq: Seq,
}
}
FieldTypeDescription
resultsVec<ChangeEvent>The list of change events.
last_seqSeqThe sequence of the last change. Pass this as since for the next poll.

ChangeEvent

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct ChangeEvent {
    pub seq: Seq,
    pub id: String,
    pub changes: Vec<ChangeRev>,
    pub deleted: bool,
    pub doc: Option<serde_json::Value>,
    pub conflicts: Option<Vec<String>>,
}
}
FieldTypeDescription
seqSeqThe sequence number for this change.
idStringThe document ID.
changesVec<ChangeRev>List of changed revision strings.
deletedbooltrue if the document was deleted. Defaults to false.
docOption<serde_json::Value>Full document body, present only when include_docs is true.
conflictsOption<Vec<String>>Conflicting revisions, present when conflicts: true was requested.

ChangeRev

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct ChangeRev {
    pub rev: String,
}
}
FieldTypeDescription
revStringThe revision string for this change.

FindResponse

Result of a Mango find query (from rouchdb-query).

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct FindResponse {
    pub docs: Vec<serde_json::Value>,
}
}
FieldTypeDescription
docsVec<serde_json::Value>Matching documents as JSON values. Includes _id and _rev fields. If fields was specified in FindOptions, only the projected fields are present (plus _id).

ViewResult

Result of a map/reduce view query (from rouchdb-query).

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct ViewResult {
    pub total_rows: u64,
    pub offset: u64,
    pub rows: Vec<ViewRow>,
}
}
FieldTypeDescription
total_rowsu64Total number of rows emitted by the map function (before skip/limit).
offsetu64Local adapters: the skip applied (like PouchDB). CouchDB / HTTP adapter: the global position of the first row (0 for keys queries, where CouchDB sends null). See Differences from CouchDB.
rowsVec<ViewRow>The result rows.

ViewRow

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct ViewRow {
    pub id: Option<String>,
    pub key: serde_json::Value,
    pub value: serde_json::Value,
    pub doc: Option<serde_json::Value>,
}
}
FieldTypeDescription
idOption<String>The source document ID. None for reduce results.
keyserde_json::ValueThe emitted key.
valueserde_json::ValueThe emitted value (or reduced value).
docOption<serde_json::Value>Full document body, present only when include_docs is true.

Replication Types

BulkGetItem

A request to fetch a specific document (optionally at a specific revision).

#![allow(unused)]
fn main() {
pub struct BulkGetItem {
    pub id: String,
    pub rev: Option<String>,
}
}
FieldTypeDescription
idStringThe document ID to fetch.
revOption<String>Specific revision to fetch. If None, returns the winning revision.

BulkGetResponse

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct BulkGetResponse {
    pub results: Vec<BulkGetResult>,
}
}

BulkGetResult

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct BulkGetResult {
    pub id: String,
    pub docs: Vec<BulkGetDoc>,
}
}

BulkGetDoc

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct BulkGetDoc {
    pub ok: Option<serde_json::Value>,
    pub error: Option<BulkGetError>,
}
}
FieldTypeDescription
okOption<serde_json::Value>The document JSON if fetch succeeded.
errorOption<BulkGetError>Error details if fetch failed.

BulkGetError

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct BulkGetError {
    pub id: String,
    pub rev: String,
    pub error: String,
    pub reason: String,
}
}
FieldTypeDescription
idStringThe document ID that failed.
revStringThe revision that was requested.
errorStringError type (e.g., "not_found").
reasonStringHuman-readable error description.

RevsDiffResponse

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct RevsDiffResponse {
    pub results: HashMap<String, RevsDiffResult>,
}
}

The results field is flattened during serialization (#[serde(flatten)]), so it serializes as a flat JSON object keyed by document ID.

RevsDiffResult

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct RevsDiffResult {
    pub missing: Vec<String>,
    pub possible_ancestors: Vec<String>,
}
}
FieldTypeDescription
missingVec<String>Revisions the adapter does not have.
possible_ancestorsVec<String>Revisions the adapter does have that could be ancestors of the missing ones. Empty vec is omitted from JSON.

ReduceFn

Built-in reduce functions for map/reduce views (from rouchdb-query).

#![allow(unused)]
fn main() {
#[non_exhaustive]
pub enum ReduceFn {
    Sum,
    Count,
    Stats,
    Custom(Box<dyn Fn(&[serde_json::Value], &[serde_json::Value], bool) -> serde_json::Value>),
}
}
VariantDescription
SumSum all numeric values.
CountCount the number of rows.
StatsCompute statistics: sum, count, min, max, sumsqr.
Custom(Fn)Custom reduce function. Arguments: (keys, values, rereduce).