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

Migrating from 0.4 to 0.5

RouchDB 0.5 is a CouchDB-fidelity release: behavior was checked against CouchDB 3.5.1 and changed wherever RouchDB disagreed. Most programs only need the first few sections below; the rest lists behavior changes you may rely on without knowing it. The full list is in the changelog.

Using redb files (Database::open, rouchdb-server, the CLI)? Read redb files first. 0.5 refuses a file written by 0.4 until you upgrade it once (rouchdb migrate app.redb, which keeps a verified backup and needs about three times the file size of free disk space; --dry-run only reads the file), and afterwards 0.4 cannot open it. The first compact() after the upgrade permanently deletes old revision bodies.


Update the dependency

[dependencies]
rouchdb = "0.5"

HTTPS now uses rustls with bundled Mozilla roots by default. If your CouchDB certificate is signed by a private CA installed in the OS trust store, pick a TLS feature that reads the OS store:

[dependencies]
rouchdb = { version = "0.5", default-features = false, features = ["rustls-tls-native-roots"] }
# or features = ["native-tls"] for the platform TLS stack (the only option in 0.4)

The minimum supported Rust version is 1.88.


redb files: upgrade once, explicitly

The redb file format changed, and a file cannot be used by both versions: a 0.4 build writing to a file 0.5 wrote would treat its documents as missing and silently replace their history. So:

  • 0.5 does not open a file written by 0.4. Database::open / RedbAdapter::open return RouchError::UpgradeRequired, and the file is not modified. This includes read-only uses (rouchdb info, rouchdb get) and rouchdb-server.
  • You upgrade each file once, keeping a verified backup, in one of three ways:
rouchdb migrate app.redb --dry-run  # report only: the file is only read
rouchdb migrate app.redb            # backup to app.redb.rouchdb-0.4.bak, then upgrade
rouchdb migrate app.redb --backup /elsewhere/app.bak
rouchdb migrate app.redb --no-backup
use rouchdb::{Database, OpenOptions, RedbAdapter, UpgradePolicy};

// Explicitly, before opening:
let report = RedbAdapter::upgrade("app.redb", UpgradePolicy::WithBackup(None))?;
println!("{report}");

// Or when opening (a 0.4 file is upgraded; others open as usual):
let db = Database::open_with(
    "app.redb",
    "app",
    OpenOptions::new().upgrade(UpgradePolicy::WithBackup(None)),
)?;

rouchdb-server --upgrade app.redb does the same before serving. RedbAdapter::inspect_upgrade(path) is the dry run from Rust. The CLI is installed from the repository (cargo install --git https://github.com/rubylab-app/rouchdb --tag v0.5.0 rouchdb-cli, or cargo install --path crates/rouchdb-cli from a checkout).

The dry run (--dry-run, RedbAdapter::inspect_upgrade) only reads the file, in read transactions: not a byte of it changes and it needs no free space. It runs the upgrade’s analysis: it validates every record and computes the plan, so a file the upgrade would refuse for its content (see below) is refused with the same error, and its report has the same counts the upgrade will report. It does not exercise the rest of the upgrade: it does not check the backup path, write or verify the backup, check the free disk space, or write and commit the upgrade, so the upgrade can still fail at one of those steps (an existing backup path, a full disk).

The backup (default <file>.rouchdb-0.4.bak) is a complete copy that 0.4 opens exactly like the original: every table is copied from one read transaction, reopened and compared entry by entry, synced, then renamed into place. The upgrade is refused if the backup path exists. If a previous attempt was interrupted:

  • a <backup>.partial file is what a killed process left while writing the backup: it is not a backup, the database file was not changed by that attempt, and the error says to delete it and retry;
  • a <backup> file left by an attempt interrupted after the backup is a complete backup (it gets its final name only after it has been verified): move it elsewhere to keep it, or pass another --backup path. The same messages appear when rouchdb-server --upgrade is restarted.

Disk space and memory. The upgrade needs about twice the file size of free disk space (redb copies every page it changes and commits in two phases), and the backup about the file size again: plan for about three times the file size free when backing up (about twice with --no-backup). There is no space check beforehand: running out of space fails cleanly, leaving the file as it was. Memory stays small whatever the file size (records and attachments are processed one at a time with a 32 MiB page cache): a 2.2 GB file holding 1 GB of attachments upgrades with a backup in about 110 MB of memory.

The upgrade is one atomic transaction with two-phase commit: the file is upgraded completely or not at all. What an error leaves behind depends on when it happens:

  • Before the commit (writing the backup, or applying the plan): nothing was written to the file, which is exactly as it was, and the backup made for that attempt is removed (it is redundant, and would block a retry).
  • During the commit (the final write fails): the backup is kept, and the error says so. If rouchdb still reports that the file must be upgraded, the file was not changed: move the backup elsewhere (or choose another backup path) before retrying. Otherwise the upgrade was committed, and the backup is your copy of the old file.

The upgrade:

  1. re-keys attachment bytes by digest (0.4 kept one copy per document and attachment name) and counts the documents;
  2. moves _local/… documents that 0.4 stored as ordinary documents (written with put("_local/…") or bulk_docs) to the local document store, where 0.5 reads them: the latest body is kept with revision 0-N (N = its generation), deleted ones and conflicting branches are dropped (see _local/ ids);
  3. rewrites revision ids stored in upper-case hex (accepted by 0.4 through new_edits: false) in lower case, so 0.5 can address them (see Revision ids that differ only in case);
  4. installs the format guard: from then on, and for every file 0.5 creates, rouchdb 0.1–0.4 fail to open the file with metadata is of type Table<&str, rouchdb-format-2 (this file requires rouchdb >= 0.5)> and write nothing. Downgrading means restoring the backup.

It reports what it found: documents, _local/ documents moved, revisions normalized, case-duplicate revisions merged and bodies discarded, documents whose winning revision changes, attachment references whose bytes 0.4 had already lost (re-attaching a name in 0.4 overwrote the bytes of older revisions), old revision bodies, and documents whose attachment bytes only old revisions reference. The report ends with advice that matches what was done (dry run or not, backup or not). If a record cannot be decoded, the upgrade stops with an error naming it, and changes nothing: repair or remove that record with 0.4 and retry. The same applies to a _local/x document that collides with a local document x written with put_local, and to a live document whose id is exactly _local/ (a local document with an empty name, which 0.5 cannot address): copy it if needed and delete it with 0.4. These checks run before the backup is written.

Revision ids that differ only in case

0.4 accepted replicated revision ids in upper-case hex and compared ids as written, so a file can hold the same revision under two spellings (2-ABC… and 2-abc…, which 0.4 saw as two revisions), and 0.4 may have picked a different winner among conflicting revisions than 0.5 does (0.4 ranked B… below a…; 0.5 compares b… with a…). The upgrade:

  • merges the spellings of a revision into one lower-case revision, which keeps the children of both;
  • keeps one copy of their bodies when both are stored and identical;
  • when the bodies differ, keeps the body of the spelling 0.4 ranked first — a leaf before an inner revision, a live leaf before a deleted one, then the greater id in byte order (lower case sorts after upper case). This is the order in which 0.4 picked the winning revision, so if one of the spellings was the document’s winner in 0.4, its body is kept. The other body is listed in UpgradeReport::case_duplicate_bodies_discarded (document, discarded spelling, kept spelling) and printed by rouchdb migrate; it stays in the backup;
  • reports the documents whose winning revision changes (docs_with_changed_winner and its count).

Files of 0.5 development builds

Files written by unreleased 0.5 development builds (which 0.4 cannot open either) are upgraded on any open, after a verified backup to <file>.rouchdb-0.5-pre.bak, a copy of the file as the development build left it (0.4 cannot open that copy; this version upgrades it again). UpgradePolicy::InPlaceNoBackup skips the backup.

The first compact() after the upgrade deletes data 0.4 kept. 0.4’s compact did nothing; 0.5 keeps only the bodies of leaf revisions and the attachment bytes they reference. The first compaction therefore permanently deletes every old revision body and every attachment only old revisions reference (0.4 dropped the attachments of a document whose body was updated without them, so this is common). Read the report, and keep the backup until you are sure.

Revision trees stay in 0.4’s nested format until each document is next written (both are readable). Attachments stored by 0.4 read back with revpos 0. Files written by a newer RouchDB, and redb files RouchDB did not create, are refused and left untouched.


Single-document writes return errors

put, update, remove, post and put_design used to return Ok with ok: false when the write failed. They now return Err, like every other failing call. bulk_docs still returns one DocResult per document.

#![allow(unused)]
fn main() {
// 0.4
let res = db.update("doc1", &rev, json!({"n": 2})).await?;
if !res.ok {
    // stale revision
}

// 0.5
match db.update("doc1", &rev, json!({"n": 2})).await {
    Ok(res) => println!("new rev {}", res.rev.unwrap_or_default()),
    Err(RouchError::Conflict) => { /* stale revision: re-read and retry */ }
    Err(e) => return Err(e),
}
}

Related changes, identical on the memory, redb and HTTP adapters:

Call0.40.5
update of a document that does not existok: false (not_found)Err(Conflict)
remove of a missing or already deleted documentok: false (over HTTP it could write a tombstone)Err(NotFound)
get with a malformed rev ("garbage")NotFound (local), BadRequest (HTTP)Err(InvalidRev)
get of a stemmed or compacted revisionOk with a stale or empty bodyErr(NotFound)

Option defaults equal new()

BulkDocsOptions::default() used to mean replication mode (new_edits: false), AllDocsOptions::default() an exclusive end_key, and ViewQueryOptions::default() no reduce and an exclusive end_key. All three now equal new().

#![allow(unused)]
fn main() {
// 0.4: silently wrote in replication mode
db.bulk_docs(docs, BulkDocsOptions::default()).await?;
// 0.5: Default is a normal write; ask for replication explicitly
db.bulk_docs(docs, BulkDocsOptions::replication()).await?;

// 0.4: end_key excluded unless you used new()
AllDocsOptions { end_key: Some("m".into()), ..Default::default() }
// 0.5: end_key is inclusive, like CouchDB; opt out explicitly
AllDocsOptions { end_key: Some("m".into()), inclusive_end: false, ..Default::default() }

// 0.4: map rows and an exclusive end_key, even with a reduce function
ViewQueryOptions { end_key: Some(json!("m")), ..Default::default() }
// 0.5: reduces (when given a reduce function) and includes end_key, like
// CouchDB and `new()`; opt out explicitly
ViewQueryOptions { end_key: Some(json!("m")), reduce: false, inclusive_end: false, ..Default::default() }
}

all_docs rows

AllDocsRow has an optional id and value and a new error:

#![allow(unused)]
fn main() {
// 0.4
pub struct AllDocsRow { pub id: String, pub key: String, pub value: AllDocsRowValue, pub doc: Option<Value> }
// 0.5
pub struct AllDocsRow {
    pub id: Option<String>,             // None for an error row
    pub key: String,                    // always set; the id for document rows
    pub value: Option<AllDocsRowValue>, // None for an error row
    pub doc: Option<Value>,
    pub error: Option<String>,          // Some("not_found") for an unknown key
}
}
#![allow(unused)]
fn main() {
// 0.4
for row in &resp.rows {
    println!("{} {}", row.id, row.value.rev);
}
// 0.5: `key` is the document id of a document row; `rev()` its revision
for row in &resp.rows {
    println!("{} {}", row.key, row.rev().unwrap_or_default());
}
}

With keys, rows match the request one to one, as in CouchDB and PouchDB. Unknown ids are no longer skipped, and deleted documents get a row too:

#![allow(unused)]
fn main() {
let resp = db.all_docs(AllDocsOptions {
    keys: Some(vec!["a".into(), "nope".into()]),
    ..AllDocsOptions::new()
}).await?;
// 0.4: rows == [a]     (memory/redb skipped "nope", HTTP dropped CouchDB's row)
// 0.5: rows == [a, not_found]    rows[1] == AllDocsRow::not_found("nope")
for row in &resp.rows {
    if row.is_error() { /* no such document */ }
    else if row.is_deleted() { /* value.deleted == Some(true), no doc */ }
    else if let Some(doc) = &row.doc { /* include_docs */ }
}
}

skip and limit count error rows too.


Design documents

DesignDocument is lossless: any design document CouchDB accepts reads and writes back unchanged.

#![allow(unused)]
fn main() {
// 0.4
pub struct DesignDocument {
    pub id: String, pub rev: Option<String>,
    pub views: HashMap<String, ViewDef>,
    pub filters: HashMap<String, String>, pub validate_doc_update: Option<String>,
    pub shows: HashMap<String, String>, pub lists: HashMap<String, String>,
    pub updates: HashMap<String, String>, pub language: Option<String>,
}
pub struct ViewDef { pub map: String, pub reduce: Option<String> }

// 0.5
pub struct DesignDocument {
    pub id: String, pub rev: Option<String>,
    pub views: HashMap<String, ViewDef>,     // JavaScript views (string `map`)
    pub other_views: Map<String, Value>,     // new: `lib`, Mango (`language: "query"`) views
    pub filters: HashMap<String, Value>,     // String -> Value (CouchDB accepts objects)
    pub validate_doc_update: Option<String>,
    pub shows: HashMap<String, Value>,
    pub lists: HashMap<String, Value>,
    pub updates: HashMap<String, Value>,
    pub language: Option<String>,
    pub extra: Map<String, Value>,           // new: options, autoupdate, rewrites, custom fields
}
pub struct ViewDef { pub map: String, pub reduce: Option<String>, pub extra: Map<String, Value> }
}

Both types implement Default and have builders:

#![allow(unused)]
fn main() {
// 0.4
let ddoc = DesignDocument {
    id: "_design/app".into(), rev: None,
    views: HashMap::from([("by_type".into(), ViewDef { map: MAP.into(), reduce: Some("_count".into()) })]),
    filters: HashMap::new(), validate_doc_update: None, shows: HashMap::new(),
    lists: HashMap::new(), updates: HashMap::new(), language: None,
};
// 0.5 (or a struct literal with ..Default::default())
let ddoc = DesignDocument::new("app")
    .with_view("by_type", ViewDef::new(MAP).with_reduce("_count"))
    .with_filter("users", "function(doc) { return doc.type === 'user'; }");
}

Filter, show, list and update functions are serde_json::Values:

#![allow(unused)]
fn main() {
// 0.4
ddoc.filters.insert("f".into(), "function(doc) { ... }".to_string());
let src: &String = &ddoc.filters["f"];
// 0.5
ddoc.filters.insert("f".into(), "function(doc) { ... }".into());
let src: Option<&str> = ddoc.filters["f"].as_str();
}

put_design writes exactly the struct it is given, like a PUT. In 0.4 it copied members the struct could not hold (views.lib, Mango views, custom fields) from the revision it replaced. If you build a fresh DesignDocument with a rev, start from the stored one instead, or those members are removed:

#![allow(unused)]
fn main() {
// 0.4: members not in the struct were copied from the stored revision
db.put_design(DesignDocument { rev: Some(rev), views: my_views, ..my_other_fields }).await?;
// 0.5: start from the stored document
let mut ddoc = db.get_design("app").await?;
ddoc.views = my_views;
db.put_design(ddoc).await?;
}

Writes are validated like CouchDB

Documents written with put, post, update or bulk_docs (normal mode) are rejected with BadRequest when they:

  • are not JSON objects;
  • contain _-prefixed members CouchDB does not know (_foo), or reserved _ ids;
  • have a wrongly typed _id, _rev, _deleted or _attachments, or an empty _id;
  • are nested deeper than MAX_NESTING_DEPTH (1000) levels.

Read-only metadata that get adds (_conflicts, _revs_info, _revisions) is dropped on write, so writing back a document you read is safe.

In bulk_docs results, the local adapters now give an invalid document’s bare reason ("Bad special document member: _foo"), like the HTTP adapter and CouchDB; 0.4 prefixed it with bad request: .

Generated ids

Ids generated by post, by bulk_docs for documents without _id and by the server’s POST /{db} are 32 lower-case hex digits, as in CouchDB (still random UUID v4 values):

#![allow(unused)]
fn main() {
// 0.4: "0b9e4c52-5d7a-4f7e-9c1b-3a2f6e8d9c10"
// 0.5: "0b9e4c525d7a4f7e9c1b3a2f6e8d9c10"
let id = db.post(json!({"n": 1})).await?.id;
}

Over HTTP a document without an id is sent without _id, so CouchDB generates it.

Nesting

Documents nested up to MAX_NESTING_DEPTH (1000) levels are accepted on every path, including the server and the CLI (0.4 failed above serde_json’s 128 levels). HttpAdapter::bulk_docs rejects a deeper document with a per-document BadRequest instead of sending it.

#![allow(unused)]
fn main() {
// 0.5: Err(BadRequest), as in CouchDB: `_meta` is not a known special member
db.put("doc1", json!({"_meta": {"source": "import"}})).await?;

// 0.5: keep application metadata in a normal member
db.put("doc1", json!({"meta": {"source": "import"}})).await?;
}

_local/ ids

A _local/… id now means a local document on every adapter, as in CouchDB: revisions are 0-1, 0-2, …, there is no conflict check, and the document is not listed by all_docs, not in the changes feed and not replicated. In 0.4 the memory and redb adapters stored it as a normal, replicated document.

#![allow(unused)]
fn main() {
db.put("_local/settings", json!({"theme": "dark"})).await?; // rev "0-1"
db.get("_local/settings").await?;                           // still readable
// but it no longer appears in all_docs() or changes(), and does not replicate
}

If you relied on _local/ documents replicating, rename them. The redb upgrade moves the _local/… documents 0.4 stored as ordinary documents to the local store (see redb files).

Attachments

  • Deleting a document drops its attachments.
  • An explicit _attachments map is exact: entries you omit are removed (stubs keep an attachment). An empty map still keeps the parent’s attachments.
  • Stubs are matched by name; the stored metadata wins over the stub’s. A stub for a name that has no stored attachment fails with missing_stub.

AttachmentMeta gains revpos, encoding and encoded_length:

#![allow(unused)]
fn main() {
// 0.4
let meta = AttachmentMeta { content_type: "image/png".into(), digest: String::new(), length: bytes.len() as u64, stub: false, data: Some(bytes) };
// 0.5: inline attachment, digest and length computed
let meta = AttachmentMeta::new("image/png", bytes);
// or add ..Default::default() to existing struct literals
}

revpos is the generation of the revision that uploaded the data, set by the write as in CouchDB, and it is now included in stubs (Document::to_json, get, bulk_get) and replicated, so attachments pushed to CouchDB no longer arrive with revpos: 0. Attachments stored by 0.4 in redb read back with revpos 0. AttachmentMeta::to_json(data) builds the CouchDB _attachments member.


Revision history

  • Stemming (revs_limit, default 1000) now prunes every branch, and the bodies of stemmed revisions are gone. Configure it with MemoryAdapter::with_rev_limit or RedbAdapter::with_rev_limit (0 = unlimited).
  • Re-creating a deleted document continues its history (3-… after 2-… was deleted) instead of starting at 1-….
  • Revision ids are normalized to lower-case hex (the redb upgrade rewrites upper-case ids 0.4 stored).
  • rouchdb_core::merge::latest_rev was removed. Use latest_leaf, which the adapters already used:
#![allow(unused)]
fn main() {
// 0.4
let rev = rouchdb_core::merge::latest_rev(&tree, pos, &hash);
// 0.5
let rev = rouchdb_core::merge::latest_leaf(&tree, pos, &hash);
}

Mango queries

Mango now follows CouchDB, which differs from PouchDB and from 0.4 in a few places. This applies to find, changes with a selector, and selector-filtered replication.

Missing fields. A document without the field only matches {"$exists": false}. $ne, $nin, $not and $nor no longer match it:

#![allow(unused)]
fn main() {
// docs: {"_id": "a", "status": "archived"}, {"_id": "b"}  (no status)
let opts = FindOptions { selector: json!({"status": {"$ne": "archived"}}), ..Default::default() };
// 0.4: ["b"]   0.5: []

// 0.5: say it explicitly to keep the 0.4 result
let opts = FindOptions {
    selector: json!({"$or": [
        {"status": {"$ne": "archived"}},
        {"status": {"$exists": false}}
    ]}),
    ..Default::default()
};
}

Projection. fields returns only the fields you ask for; _id is no longer added. Nested paths keep their structure:

#![allow(unused)]
fn main() {
let opts = FindOptions {
    selector: json!({"type": "user"}),
    fields: Some(vec!["_id".into(), "address.city".into()]), // add "_id" if you need it
    ..Default::default()
};
// 0.5 result: {"_id": "u1", "address": {"city": "Lima"}}
}

Errors instead of empty results. Invalid selectors, unknown operators, bad operator arguments ({"$not": 5}, {"$elemMatch": 1}), invalid regexes and invalid sort fields are Err(BadRequest) with CouchDB’s messages. A null selector is an error too; use json!({}) to match everything. A replication with an invalid ReplicationFilter::Selector fails with BadRequest before it reads or writes anything (replicate_live sends an Error event and stops, even with retry).

Other changes:

  • Nested objects are paths: {"a": {"b": 1}} means {"a.b": 1}.
  • $in / $nin compare against array elements; $all uses exact equality.
  • find never returns design documents.
  • A selector that is only an empty combinator ({"$and": []}) returns nothing.
  • {} below the top level is an equality test with {}: {"$and": [{}]} matches nothing, {"o": {"$and": [{}]}} matches o == {}. Operators without a field inside $and/$or/$nor ({"$and": [{"$gt": 1}]}) apply to the whole document instead of being rejected.
  • Descending sort ties come in reverse index order.
  • A sorted find skips documents that lack a sort field.
  • $regex accepts PCRE-style lookaround and backreferences.
  • SortField only deserializes from "field" or {"field": "asc" | "desc"}.

On Database::http, find, create_index, get_indexes, delete_index and explain now run on the CouchDB server, so results (including string order) are CouchDB’s own.


Views

ViewQueryOptions::new() now enables reduce, like CouchDB. If you pass a reduce function but want map rows, say so:

#![allow(unused)]
fn main() {
// 0.4: map rows, because new() left reduce off
let opts = ViewQueryOptions::new();
// 0.5: new() reduces; ask for map rows explicitly
let opts = ViewQueryOptions { reduce: false, ..ViewQueryOptions::new() };
}

Also:

  • _sum and _stats keep integers (90, not 90.0); arrays are summed element-wise and objects per field.

  • _sum over values it cannot add (strings, mixed types) no longer fails the query: the row’s value is CouchDB’s error object, so check for it if your map functions can emit such values. _stats over such values is still Err(BadRequest).

    #![allow(unused)]
    fn main() {
    // 0.5: emit(doc.type, doc.name) with _sum
    // rows[0].value == {"error": "builtin_reduce_error", "reason": "The _sum function requires ...", "caused_by": "alice"}
    if row.value.get("error").is_some() { /* not summable */ }
    }
  • These queries are now Err(BadRequest), as in CouchDB: a key range that cannot match (start_key after end_key without descending, or the reverse with it), several keys together with key/start_key/end_key, and group/group_level on a map-only view or with reduce: false.

    #![allow(unused)]
    fn main() {
    // 0.4: Ok with no rows.  0.5: Err(BadRequest("No rows can match your key range, ..."))
    let opts = ViewQueryOptions { start_key: Some(json!("z")), end_key: Some(json!("a")), ..ViewQueryOptions::new() };
    // 0.5: say descending if you meant it
    let opts = ViewQueryOptions { start_key: Some(json!("z")), end_key: Some(json!("a")), descending: true, ..ViewQueryOptions::new() };
    }
  • start_key/end_key are honored next to key (an explicit bound replaces the one key implies), and group + keys keeps the keys’ order when descending.

  • Custom reduce functions receive [key, doc_id] pairs as keys, and rereduce is always false.

  • Several keys with a reduce require group: true (and no group_level); include_docs with a reduce is an error.

  • total_rows counts the whole view and offset is the position of the first returned row.

  • Design documents are not passed to map functions.

Collation

-0.0 equals 0, large integers and floats compare exactly, and strings compare by UTF-16 code units (PouchDB’s order; only characters above U+FFFF move). to_indexable_string has a new format: rebuild anything you stored with it.


Partitions

Partition::all_docs lists every id of the partition (0.4 missed ids sorting after p:\u{10FFFF}) and applies inclusive_end only to the end key you pass, never to the partition’s own bound. Partition::find validates your selector as a whole selector first, and {} means every document of the partition.


Plugins

before_write now also runs for put_attachment and remove_attachment, with the revision the attachment write creates. As for replicated documents it can only accept or reject: a rejection is returned and nothing is written, modifications are ignored, and dropping the document is Forbidden. If a plugin rejects documents by shape, check that it accepts attachment-only revisions of documents it accepted before.


Replication and the HTTP adapter

The remote database is created on first use, as PouchDB does. To keep failing with NotFound when it is missing:

#![allow(unused)]
fn main() {
use std::sync::Arc;
use rouchdb::{Database, HttpAdapter, HttpAdapterOptions};

// 0.4
let db = Database::http("http://admin:password@localhost:5984/mydb");

// 0.5: same call creates `mydb` if needed; opt out with skip_setup
let adapter = HttpAdapter::with_options(
    "http://admin:password@localhost:5984/mydb",
    HttpAdapterOptions { skip_setup: true, ..Default::default() },
);
let db = Database::from_adapter(Arc::new(adapter));
}

HttpAdapterOptions also sets the timeouts (30 s to connect, 60 s of inactivity by default).

One rescan after upgrading. Every replication gets a new replication id, so its first run re-reads the changes feed from the start; revs_diff means no document is transferred again, and the old _local checkpoints are left unused:

  • an HTTP peer is identified by the server uuid plus the database name;
  • a memory or redb database is identified by a uuid of its own, not by its name (two local databases with the same name used to share checkpoints, so sync between them skipped documents). destroy() gives the database a new one. redb stores the uuid in the file and combines it with the file’s canonical path: a file reopened at the same path (directly or through a symlink) keeps its checkpoints whatever name it is opened with, while a copy of the file (which holds the same uuid) is a different database, so syncing a file with its copy works both ways. Moving or copying a file makes its next replication with each peer rescan the changes feed once (no document is transferred again). Never destroy() a copy to give it a new identity: that deletes its documents;
  • ReplicationFilter::DocIds selections are fingerprinted as a JSON array of ids (ids joined with NUL could collide).

A custom Adapter should override Adapter::id() (the default is the database name) with an identity that tells apart same-named databases and changes on destroy(). When both peers of a replication report the same id, their checkpoints cannot be told apart, so the replication runs without them (scanning the whole changes feed each time) and reports it in ReplicationResult::warnings and a ReplicationEvent::Warning.

Other changes:

  • Documents rejected by a validation function (forbidden / unauthorized) are listed in errors and ok is false, but the replication moves past them instead of stopping forever.
  • ReplicationFilter::Custom closures no longer use checkpoints: every run starts from since.
  • For replicated documents, before_write plugins only accept or reject (their modifications are ignored), like CouchDB’s validate_doc_update.
  • HTTP errors are mapped from the status and CouchDB’s {error, reason}: 400/413/415 → BadRequest, 412 file_exists → DatabaseExists, 401 → Unauthorized.

Live feeds react immediately

Live changes feeds (live_changes, live_changes_events, LiveChangesStream) and replicate_live from a memory or redb database are woken by the adapter on each commit instead of polling. poll_interval now only applies to HTTP sources, to identity checks of HTTP targets and to retry delays, and live replication emits Paused as soon as it is caught up (0.4 needed one more empty poll). Tests that counted polls or slept for poll_interval may need adjusting. rouchdb_changes::ChangeNotification is now an alias of rouchdb_core::adapter::ChangeNotice (same fields).

destroy

After destroy() the handle stays usable and behaves as a new, empty database on every adapter (documents, local documents, attachments, security and Mango indexes are gone). The HTTP adapter re-creates the remote database on its next use, and destroying a database that no longer exists is Ok.

A destroyed memory or redb database gets a new identity (Adapter::id()), so replications from or to it start over instead of resuming from a checkpoint of the old database. It also announces the reset to its subscribers (ChangeNotice::reset(), with reset: true). A running replicate_live notices it right away, whether the destroyed database is the source or the target (even while the source is idle), and starts over from the start of the source’s changes feed, so a destroyed and reused target gets every document again. A target that cannot announce resets (HTTP) has its id compared every poll_interval; the HTTP adapter identifies a remote database by the server’s uuid and the database name, so a remote database that is deleted and re-created is not detected: cancel the replications that use it and copy everything again with since: Some(Seq::zero()) and checkpoint: false (see Re-creating a remote database); retrying with the existing checkpoints does not recover the lost documents.

Live changes streams (live_changes, live_changes_events, LiveChangesStream) do not start over after destroy(): they keep their last_seq and miss the new database’s changes. Cancel them and create new ones from Seq::zero() after destroying the database.


Non-exhaustive enums and result types

So that later releases can add fields and variants without breaking your code, 0.5 marks the types that may grow #[non_exhaustive] (see API Stability):

  • A match on RouchError, ChangesEvent, ReplicationEvent, ReplicationFilter, ReduceFn, StaleOption or SortField needs a catch-all arm, and the struct-like variants ChangesEvent::Complete and ReplicationEvent::Change need ..:
#![allow(unused)]
fn main() {
match event {
    ReplicationEvent::Change { docs_read, .. } => println!("{docs_read} read"),
    ReplicationEvent::Complete(result) => println!("{} written", result.docs_written),
    ReplicationEvent::Error(msg) => eprintln!("{msg}"),
    _ => {} // Active, Paused, and events added later
}
}
  • Result types can no longer be built with struct literals outside their crate (reading their public fields is unchanged): DocResult, DbInfo, AllDocsResponse, AllDocsRow, AllDocsRowValue, ChangesResponse, ChangeEvent, ChangeRev, RevsDiffResponse, RevsDiffResult, BulkGetResponse, BulkGetResult, BulkGetDoc, BulkGetError, PurgeResponse, ChangeNotice, FindResponse, IndexInfo, IndexFields, CreateIndexResponse, ExplainResponse, ExplainIndex, BuiltIndex, EmittedRow, and (library-built only) PutResponse, RevInfo, DocMetadata, ViewResult, ViewRow, ReplicationResult, PersistentViewIndex, Session, UserContext, PlannedWrite, LeafInfo. Use the constructors instead, typically in custom adapters, plugins and tests:
#![allow(unused)]
fn main() {
// 0.4
let r = DocResult { ok: true, id: "a".into(), rev: Some(rev), error: None, reason: None };
// 0.5
let r = DocResult::ok("a", rev);
let e = DocResult::error("b", "forbidden", "not allowed");
let info = DbInfo::new("mydb", doc_count, doc_del_count, update_seq);
}
  • Option and data structs are unchanged (GetOptions, AllDocsOptions, ChangesOptions, FindOptions, ViewQueryOptions, ReplicationOptions, ChangesStreamOptions, HttpAdapterOptions, IndexDefinition, BulkGetItem, Document, AttachmentMeta, DesignDocument, ViewDef, SecurityDocument, …), but write their literals with ..Default::default() (or ..X::new()) so the next field added is not a breaking change for you. Document::new(id, data), BulkGetItem::new(id).with_rev(rev) and Default for Document, IndexDefinition and BulkGetItem are new.

Custom adapters

  • Build the results you return with their constructors: see Non-exhaustive enums and result types and Building Results.
  • Adapter::put_security’s default now returns Err(BadRequest) instead of silently succeeding. Implement it if your adapter stores security documents.
  • New default method Adapter::id() (the database name). Override it if two instances of your adapter can share a name but not their data, so replications do not share checkpoints.
  • destroy must leave the adapter usable as an empty database.
  • New default method Adapter::subscribe() returning None: existing adapters compile unchanged and keep being polled. To wake live feeds and live replication immediately, return a receiver and send a notice after each commit:
#![allow(unused)]
fn main() {
// 0.5, in a custom adapter
fn subscribe(&self) -> Option<tokio::sync::broadcast::Receiver<ChangeNotice>> {
    Some(self.notices.subscribe()) // send ChangeNotice::new(seq, doc_id) after each commit
}
}

Exact numbers (opt-in)

Nothing changes by default. The new arbitrary-precision feature keeps JSON numbers exactly as written (integers beyond i64/u64, long decimals):

rouchdb = { version = "0.5", features = ["arbitrary-precision"] }

It enables serde_json’s arbitrary_precision for the whole build: serde_json::Number then compares textually (1.0 != 1.00), and revision ids of documents containing such numbers differ from those computed without the feature. See also “Differences from CouchDB” in the reference.


Server (rouchdb-server)

ServerConfig has new fields, so add ..Default::default() to struct literals:

#![allow(unused)]
fn main() {
use rouchdb_server::{AdminCredentials, ServerConfig};

// 0.4
let config = ServerConfig { port: 5984, host: "0.0.0.0".into(), db_name: "mydb".into() };

// 0.5
let config = ServerConfig {
    port: 5984,
    host: "0.0.0.0".into(),
    db_name: "mydb".into(),
    admin: Some(AdminCredentials::parse("admin:secret").expect("user:password")),
    cors_origins: vec!["http://localhost:3000".into()],
    ..Default::default() // max_request_size: 64 MiB, session_timeout: 10 min
};
}

CORS is off by default. A browser app served from another origin must be allowed explicitly; in 0.4 every origin was mirrored with credentials:

rouchdb-server mydb.redb --cors-origin http://localhost:3000   # or ROUCHDB_CORS_ORIGINS

Authentication is opt-in and recommended whenever other software can reach the port (the server warns when it listens on a non-loopback address without it):

ROUCHDB_ADMIN=admin:secret rouchdb-server mydb.redb --host 0.0.0.0

Everything except /, /_session, /_uuids and /_utils then needs Basic auth or a _session cookie. Wrong credentials are a 401 on every route, and session cookies expire after 10 minutes without use (--session-timeout).

HTTP clients of the server may notice:

Request0.40.5 (CouchDB)
DELETE /{db}database still served404 on every route until PUT /{db}
wrong-shape JSON body422400
DELETE /{db}/{docid} without a rev400409
design-document conflict201 "ok": false409
_bulk_docs with an invalid document201 (written, or a per-document error)400, nothing written
_bulk_docs with new_edits: falseone result per documentfailures only ([])
_find without limitevery matchat most 25, with a bookmark
POST /{db}/_index response idindex name_design/<ddoc> (also listed in _all_docs / _changes)
_all_docs?key=baccepted400; JSON-encode keys (?key="b")
_changes with an unknown feed or filterignored400 / 404
POST /{db}/_compact without Content-Type: application/json202415
/_uuids, POST /{db} generated idshyphenated UUIDs32 hex digits
POST /{db}/_all_docs with keysunknown keys droppedone row per key: {"key": …, "error": "not_found"}, "offset": null, "doc": null for deleted docs
GET /{db}/_design/{ddoc}typed members onlythe stored document, with the usual document options and headers
PUT/DELETE /{db}/{doc}/{att} with a malformed ?rev404/409 when the document is missing400 Invalid rev format
anonymous POST/PUT/DELETE / or /_active_tasksaccepted405 Only GET,HEAD allowed
several AuthSession cookiesany valid oneonly the first counts
malformed AuthSession cookieignored400 on every route, even with valid Basic credentials
malformed JSON bodyaxum’s message400 bad_request “invalid UTF-8 JSON”
request body over 2 MB413accepted up to 64 MiB (--max-request-size)
error bodiessometimes plain text; reasons like the doc idalways JSON, CouchDB names and reasons (missing, deleted, Document update conflict.)

CLI (rouchdb)

  • rouchdb migrate <path> upgrades a file written by 0.4 (see redb files); every other command refuses such a file and says so.
  • Read-only commands fail with exit 1 on a missing file instead of creating an empty one.
  • replicate exits 1 when ok is false; its output gains errors and last_seq.
  • dump inlines attachments (base64) and import restores them. dump still exports only winning revisions; use replicate to copy conflicts and history.
  • ROUCHDB_USER / ROUCHDB_PASSWORD supply credentials for http(s) URLs that carry none, and errors never print user:password@.