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
}

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
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() {
pub struct DbInfo {
    pub db_name: String,
    pub doc_count: u64,
    pub update_seq: Seq,
}
}
FieldTypeDescription
db_nameStringThe name of the database.
doc_countu64Number of non-deleted documents.
update_seqSeqThe current update sequence number. Increments with every write.

DocResult

The result of a single document write operation.

#![allow(unused)]
fn main() {
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.

AttachmentMeta

Metadata for a document attachment.

#![allow(unused)]
fn main() {
pub struct AttachmentMeta {
    pub content_type: String,
    pub digest: String,
    pub length: u64,
    pub stub: bool,
    pub data: Option<Vec<u8>>,
}
}
FieldTypeDescription
content_typeStringMIME type (e.g., "image/png").
digestStringContent digest for deduplication.
lengthu64Size in bytes.
stubboolIf true, only metadata is present (no inline data). Defaults to false.
dataOption<Vec<u8>>Inline binary data, if available. Omitted from serialization when None.

DocMetadata

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

#![allow(unused)]
fn main() {
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() {
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_editsbooltrue (via BulkDocsOptions::new())When 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.

Note: The Default trait implementation sets new_edits to false. Use BulkDocsOptions::new() for user-mode writes (which sets new_edits: true) and BulkDocsOptions::replication() for replication-mode writes (which sets new_edits: false).

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_endbooltrue (via AllDocsOptions::new())Whether 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.

Note: Use AllDocsOptions::new() instead of Default::default() to get inclusive_end: true, which matches CouchDB’s default behavior.


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() {
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.
keysOption<Vec<serde_json::Value>>NoneReturn only rows matching any of these keys, in the given order.
start_keyOption<serde_json::Value>NoneStart of key range (inclusive).
end_keyOption<serde_json::Value>NoneEnd of key range (inclusive by default).
inclusive_endbooltrue (via ViewQueryOptions::new())Whether 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.
reduceboolfalseWhether to run the reduce function.
groupboolfalseGroup results by key (requires reduce: true).
group_levelOption<u64>NoneGroup to this many array elements of the key (requires reduce: true).
staleStaleOptionFalseFalse rebuilds the index before querying (default). Ok uses a potentially stale index. UpdateAfter returns stale results then rebuilds.

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() {
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.
offsetu64Number of rows skipped.
rowsVec<AllDocsRow>The result rows.
update_seqOption<Seq>The current update sequence, present when update_seq: true was requested.

AllDocsRow

#![allow(unused)]
fn main() {
pub struct AllDocsRow {
    pub id: String,
    pub key: String,
    pub value: AllDocsRowValue,
    pub doc: Option<serde_json::Value>,
}
}
FieldTypeDescription
idStringThe document ID.
keyStringThe row key (same as id for all_docs).
valueAllDocsRowValueContains the revision and optional deletion flag.
docOption<serde_json::Value>Full document body, present only when include_docs is true.

AllDocsRowValue

#![allow(unused)]
fn main() {
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() {
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() {
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() {
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() {
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() {
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).
offsetu64Number of rows skipped.
rowsVec<ViewRow>The result rows.

ViewRow

#![allow(unused)]
fn main() {
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() {
pub struct BulkGetResponse {
    pub results: Vec<BulkGetResult>,
}
}

BulkGetResult

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

BulkGetDoc

#![allow(unused)]
fn main() {
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() {
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() {
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() {
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() {
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).