Struct couch_rs::database::Database

source ·
pub struct Database { /* private fields */ }
Expand description

Database operations on a CouchDB Database (sometimes called Collection in other NoSQL flavors such as MongoDB).

Implementations§

source§

impl Database

source

pub fn new(name: String, client: Client) -> Database

source

pub fn name(&self) -> &str

source

pub async fn compact(&self) -> bool

Launches the compact process

source

pub async fn compact_views(&self) -> bool

Starts the compaction of all views

source

pub async fn compact_index(&self, index: &str) -> bool

Starts the compaction of a given index

source

pub async fn exists(&self, id: &str) -> bool

Checks if a document ID exists

Usage:

use couch_rs::error::CouchResult;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    // check if the design document "_design/clip_view" exists
    if db.exists("_design/clip_view").await {
        println!("The design document exists");
    }

    return Ok(());
}
source

pub async fn get_raw(&self, id: &str) -> CouchResult<Value>

Convenience wrapper around get::(id)

source

pub async fn get<T: TypedCouchDocument>(&self, id: &str) -> CouchResult<T>

Gets one document

Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::error::CouchResult;
use serde_json::{from_value, to_value, Value};
use couch_rs::types::document::DocumentId;
use couch_rs::document::TypedCouchDocument;
use couch_rs::CouchDocument;
use serde::{Deserialize, Serialize};

const TEST_DB: &str = "test_db";

#[derive(Serialize, Deserialize, CouchDocument)]
pub struct UserDetails {
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _id: DocumentId,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _rev: String,
    #[serde(rename = "firstName")]
    pub first_name: Option<String>,
    #[serde(rename = "lastName")]
    pub last_name: String,
}

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    // before we can get the document, we need to create it first...
    let seed_doc = UserDetails {
        _id: "1234".to_string(),
        _rev: "".to_string(),
        first_name: None,
        last_name: "Doe".to_string(),
    };
    let mut value = to_value(seed_doc)?;
    db.create(&mut value).await?;

    // now that the document is created, we can get it; typed:
    let _user_details: UserDetails = db.get("1234").await?;

    // now that the document is created, we can get it; or untyped:
    let _raw_user: Value = db.get("1234").await?;

    Ok(())
}
source

pub async fn get_bulk<T: TypedCouchDocument>( &self, ids: Vec<DocumentId> ) -> CouchResult<DocumentCollection<T>>

Gets documents in bulk with provided IDs list

source

pub async fn get_bulk_raw( &self, ids: Vec<DocumentId> ) -> CouchResult<DocumentCollection<Value>>

Gets documents in bulk with provided IDs list, as raw Values

source

pub async fn bulk_docs<T: TypedCouchDocument>( &self, raw_docs: &mut [T] ) -> CouchResult<Vec<DocumentCreatedResult>>

Each time a document is stored or updated in CouchDB, the internal B-tree is updated. Bulk insertion provides efficiency gains in both storage space, and time, by consolidating many of the updates to intermediate B-tree nodes.

See the documentation on how to use bulk_docs here: db-bulk-docs

raw_docs is a vector of documents with or without an ID

This endpoint can also be used to delete a set of documents by including “_deleted”: true, in the document to be deleted. When deleting or updating, both _id and _rev are mandatory.

Usage:

use couch_rs::error::CouchResult;
use serde_json::json;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
   let client = couch_rs::Client::new_local_test()?;
   let db = client.db(TEST_DB).await?;

   let _ndoc_result = db
        .bulk_docs(&mut vec![
            json!({"_id": "first", "thing": true}),
            json!({"_id": "second", "thing": false}),
        ]).await?;

   return Ok(());
}
source

pub async fn get_bulk_params<T: TypedCouchDocument>( &self, ids: Vec<DocumentId>, params: Option<QueryParams<DocumentId>> ) -> CouchResult<DocumentCollection<T>>

Gets documents in bulk with provided IDs list, with added params. Params description can be found here: _all_docs

Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::error::CouchResult;
use serde_json::json;
use serde_json::Value;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;
    let mut doc_1 = json!({
                    "_id": "john",
                    "first_name": "John",
                    "last_name": "Doe"
                });

    let mut doc_2 = json!({
                    "_id": "jane",
                    "first_name": "Jane",
                    "last_name": "Doe"
                });

    // Save these documents
    db.save(&mut doc_1).await?;
    db.save(&mut doc_2).await?;

    // subsequent call updates the existing document
    let docs = db.get_bulk_params::<Value>(vec!["john".to_string(), "jane".to_string()], None).await?;

    // verify that we received the 2 documents
    assert_eq!(docs.rows.len(), 2);
    Ok(())
}
source

pub async fn get_all<T: TypedCouchDocument>( &self ) -> CouchResult<DocumentCollection<T>>

Gets all the documents in database

source

pub async fn get_all_raw(&self) -> CouchResult<DocumentCollection<Value>>

Gets all the documents in database as raw Values

source

pub async fn get_all_batched<T: TypedCouchDocument>( &self, tx: Sender<DocumentCollection<T>>, batch_size: u64, max_results: u64 ) -> CouchResult<u64>

Gets all documents in the database, using bookmarks to iterate through all the documents. Results are returned through an mpcs channel for async processing. Use this for very large databases only. Batch size can be requested. A value of 0, means the default batch_size of 1000 is used. max_results of 0 means all documents will be returned. A given max_results is always rounded up to the nearest multiplication of batch_size. This operation is identical to find_batched(FindQuery::find_all(), tx, batch_size, max_results)

Check out the async_batch_read example for usage details

source

pub async fn find_batched<T: TypedCouchDocument>( &self, query: FindQuery, tx: Sender<DocumentCollection<T>>, batch_size: u64, max_results: u64 ) -> CouchResult<u64>

Finds documents in the database, using bookmarks to iterate through all the documents. Results are returned through an mpcs channel for async processing. Use this for very large databases only. Batch size can be requested. A value of 0, means the default batch_size of 1000 is used. max_results of 0 means all documents will be returned. A given max_results is always rounded up to the nearest multiplication of batch_size.

Check out the async_batch_read example for usage details

source

pub async fn query_many_all_docs( &self, queries: QueriesParams ) -> CouchResult<Vec<ViewCollection<Value, Value, Value>>>

Executes multiple specified built-in view queries of all documents in this database. This enables you to request multiple queries in a single request, in place of multiple POST /{db}/_all_docs requests. More information Parameters description can be found here

Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::types::query::{QueryParams, QueriesParams};
use couch_rs::error::CouchResult;
use serde_json::{json, Value};

const TEST_DB: &str = "vehicles";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    // imagine we have a database (e.g. vehicles) with multiple documents of different types; e.g. cars, planes and boats
    // document IDs have been generated taking this into account, so cars have IDs starting with "car:",
    // planes have IDs starting with "plane:", and boats have IDs starting with "boat:"
    //
    // let's query for all cars and all boats, sending just 1 request
    let mut cars = QueryParams::default();
    cars.start_key = Some("car".to_string());
    cars.end_key = Some("car:\u{fff0}".to_string());

    let mut boats = QueryParams::default();
    boats.start_key = Some("boat".to_string());
    boats.end_key = Some("boat:\u{fff0}".to_string());

    let mut collections = db.query_many_all_docs(QueriesParams::new(vec![cars, boats])).await?;
    println!("Succeeded querying for cars and boats");
    let mut collections = collections.iter_mut();
    let car_collection = collections.next().unwrap();
    println!("Retrieved cars {:?}", car_collection);
    let boat_collection = collections.next().unwrap();
    println!("Retrieved boats {:?}", boat_collection);

    Ok(())
}
source

pub async fn query_many( &self, design_name: &str, view_name: &str, queries: QueriesParams ) -> CouchResult<Vec<ViewCollection<Value, Value, Value>>>

Executes multiple queries against a view.

source

pub async fn get_all_params_raw( &self, params: Option<QueryParams<DocumentId>> ) -> CouchResult<DocumentCollection<Value>>

source

pub async fn get_all_params<T: TypedCouchDocument>( &self, params: Option<QueryParams<DocumentId>> ) -> CouchResult<DocumentCollection<T>>

Gets all the documents in database, with applied parameters. Parameters description can be found here: api-ddoc-view

source

pub async fn find_raw( &self, query: &FindQuery ) -> CouchResult<DocumentCollection<Value>>

Finds a document in the database through a Mango query as raw Values. Convenience function for find::(query)

Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::error::CouchResult;
use serde_json::Value;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;
    let find_all = FindQuery::find_all();
    let docs = db.find_raw(&find_all).await?;
    Ok(())
}
source

pub async fn find<T: TypedCouchDocument>( &self, query: &FindQuery ) -> CouchResult<DocumentCollection<T>>

Finds a document in the database through a Mango query.

Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::error::CouchResult;
use serde_json::Value;
use couch_rs::document::TypedCouchDocument;
use couch_rs::types::document::DocumentId;
use couch_rs::CouchDocument;
use couch_rs::document::DocumentCollection;
use serde::{Deserialize, Serialize};

const TEST_DB: &str = "user_db";

#[derive(Serialize, Deserialize, CouchDocument, Default, Debug)]
pub struct TestDoc {
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _id: DocumentId,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _rev: String,
    pub first_name: String,
    pub last_name: String,
}

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;
    let find_all = FindQuery::find_all();
    let docs: DocumentCollection<TestDoc> = db.find(&find_all).await?;
    Ok(())
}
source

pub async fn save<T: TypedCouchDocument>( &self, doc: &mut T ) -> DocumentCreatedResult

Saves a document to CouchDB. When the provided document includes both an _id and a _rev CouchDB will attempt to update the document. When only an _id is provided, the save method behaves like create and will attempt to create the document.

Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::error::CouchResult;
use serde_json::{from_value, to_value};
use couch_rs::types::document::DocumentId;
use couch_rs::document::TypedCouchDocument;
use couch_rs::CouchDocument;
use serde::{Deserialize, Serialize};

const TEST_DB: &str = "test_db";

#[derive(Serialize, Deserialize, CouchDocument)]
pub struct UserDetails {
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _id: DocumentId,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub _rev: String,
    #[serde(rename = "firstName")]
    pub first_name: Option<String>,
    #[serde(rename = "lastName")]
    pub last_name: String,
}

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    // before we can get the document, we need to create it first...
    let seed_doc = UserDetails {
        _id: "123".to_string(),
        _rev: "".to_string(),
        first_name: None,
        last_name: "Doe".to_string(),
    };
    let mut value = to_value(seed_doc)?;
    db.create(&mut value).await?;

    // now that the document is created, we can get it, update it, and save it...
    let mut user_details: UserDetails = db.get("123").await?;
    user_details.first_name = Some("John".to_string());

    db.save(&mut user_details).await?;
    Ok(())
}
source

pub async fn create<T: TypedCouchDocument>( &self, doc: &mut T ) -> DocumentCreatedResult

Creates a document from a raw JSON document Value. Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::error::CouchResult;
use serde_json::json;
use couch_rs::document::TypedCouchDocument;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;
    let mut doc = json!({
                    "first_name": "John",
                    "last_name": "Doe"
                });

    let details = db.create(&mut doc).await?;

    // verify that this is the 1st revision of the document
    assert!(details.rev.starts_with('1'));
    Ok(())
}
source

pub async fn upsert<T: TypedCouchDocument>( &self, doc: &mut T ) -> DocumentCreatedResult

The upsert function combines a get with a save function. If the document with the provided _id can be found it will be merged with the provided Document’s value, otherwise the document will be created. This operation always performs a get, so if you have a documents _rev using a save is quicker. Same is true when you know a document does not exist.

Usage:

use couch_rs::types::find::FindQuery;
use couch_rs::error::CouchResult;
use couch_rs::document::TypedCouchDocument;
use serde_json::json;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;
    let mut doc = json!({
                    "_id": "doe",
                    "first_name": "John",
                    "last_name": "Doe"
                });

    // initial call creates the document
    db.upsert(&mut doc).await?;

    // subsequent call updates the existing document
    let details = db.upsert(&mut doc).await?;

    // verify that this is the 2nd revision of the document
    assert!(details.rev.starts_with('2'));
    Ok(())
}
source

pub async fn bulk_upsert<T: TypedCouchDocument + Clone>( &self, docs: &mut [T] ) -> CouchResult<Vec<DocumentCreatedResult>>

Bulk upsert a list of documents.

This will first fetch the latest rev for each document that does not have a rev set. It will then insert all documents into the database.

source

pub async fn create_view<T: Into<Value>>( &self, design_name: &str, views: T ) -> CouchResult<DesignCreated>

Creates a design with one of more view documents.

Usage:

use couch_rs::types::view::{CouchFunc, CouchViews};
use couch_rs::error::CouchResult;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    let couch_func = CouchFunc {
            map: "function (doc) { if (doc.funny == true) { emit(doc._id, doc.funny); } }".to_string(),
            reduce: None,
    };

    let couch_views = CouchViews::new("clip_view", couch_func);
    db.create_view("clip_design", couch_views).await?;
    Ok(())
}
source

pub async fn query_raw( &self, design_name: &str, view_name: &str, options: Option<QueryParams<Value>> ) -> CouchResult<ViewCollection<Value, Value, Value>>

Executes a query against a view, returning untyped Values

source

pub async fn query<K: Serialize + DeserializeOwned + PartialEq + Debug + Clone, V: DeserializeOwned, T: TypedCouchDocument>( &self, design_name: &str, view_name: &str, options: Option<QueryParams<K>> ) -> CouchResult<ViewCollection<K, V, T>>

Executes a query against a view. Make sure the types you use for K, V and T represent the structures the query will return. For example, if a query can return a null value, but the type used for query() is <K:String, V:String, T:TypedCouchDocument> the couchdb query will succeed but deserialising the overall result will fail (‘null’ cannot be deserialized to String). In such case, you can use serde::Value since it can hold both ‘null’ and String.

Usage:

use couch_rs::error::CouchResult;
use couch_rs::types::view::RawViewCollection;
use couch_rs::types::view::{CouchFunc, CouchViews};
use serde_json::json;

const TEST_DB: &str = "view_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    let mut doc = json!({
                    "_id": "jdoe",
                    "first_name": "John",
                    "last_name": "Doe",
                    "funny": true
                });

    db.create(&mut doc).await?;

    let couch_func = CouchFunc {
            map: "function (doc) { if (doc.funny == true) { emit(doc._id, doc.funny); } }".to_string(),
            reduce: None,
    };

    let couch_views = CouchViews::new("funny_guys", couch_func);
    db.create_view("test_design", couch_views).await?;
    let result: RawViewCollection<String, bool> = db.query("test_design", "funny_guys", None).await?;

    println!("Funny guys:");
    for item in result.rows.into_iter() {
        let id = item.key;
        let is_funny = item.value;
        println!("{} is funny: {}", id, is_funny);
    }
    Ok(())
}
source

pub async fn execute_update( &self, design_id: &str, name: &str, document_id: &str, body: Option<Value> ) -> CouchResult<String>

Executes an update function.

source

pub async fn remove<T: TypedCouchDocument>(&self, doc: &T) -> bool

Removes a document from the database. Returns success in a bool Usage:

use couch_rs::types::find::FindQuery;
use serde_json::{from_value, to_value, Value};
use couch_rs::types::document::DocumentId;
use couch_rs::error::CouchResult;

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    // first we need to get the document, because we need both the _id and _rev in order
    // to delete
    if let Some(doc) = db.get::<Value>("123").await.ok() {
        db.remove(&doc).await;
    }

    Ok(())
}
source

pub async fn insert_index( &self, name: &str, def: IndexFields, index_type: Option<IndexType>, ddoc: Option<DocumentId> ) -> CouchResult<DesignCreated>

Inserts an index on a database, using the _index endpoint.

Arguments to this function include name, index specification, index type, and the design document to which the index will be written. See CouchDB docs for more explanation on parameters for indices. The index_type and design doc fields are optional.

Indexes do not have unique names, so no index can be “edited”. If insert_index is called where there is an existing index with the same name but a different definition, then a new index is created and the DesignCreated return value’s result field will be “exists”. If insert_index is called where there is an existing index with both the same name and same definition, no new index is created, and the DesignCreated return value’s result field will be “created”. Usage:

use couch_rs::error::CouchResult;
use couch_rs::types::{find::SortSpec, index::{Index, IndexFields}};

const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> CouchResult<()> {
    let client = couch_rs::Client::new_local_test()?;
    let db = client.db(TEST_DB).await?;

    let index_name = "name";
    let index_def = IndexFields {
        fields: vec!{
            SortSpec::Simple("lastname".to_string()),
            SortSpec::Simple("firstname".to_string()),
        }
    };

    match db.insert_index(index_name, index_def, None, None).await {
        Ok(doc_created) => match doc_created.result {
            // Expected value of 'r' is 'created' if the index did not previously exist or
            // "exists" otherwise.
            Some(r) => println!("Index {} {}", index_name, r),  
            // This shold not happen!
            None => println!("Index {} validated", index_name),
        },
        Err(e) => {
            println!("Unable to validate index {}: {}", index_name, e);
        }
    };

    Ok(())
}
§Panics

When the internal json! macro fails to create a json object. Not expected to happen.

source

pub async fn read_indexes(&self) -> CouchResult<DatabaseIndexList>

Reads the database’s indexes and returns them

source

pub async fn delete_index( &self, ddoc: DocumentId, name: String ) -> CouchResult<bool>

Deletes a db index. Returns true if successful, false otherwise.

source

pub async fn ensure_index( &self, name: &str, spec: IndexFields ) -> CouchResult<bool>

👎Deprecated since 0.9.1: please use insert_index instead

Method to ensure an index is created on the database with the following spec. Returns true when we created a new one, or false when the index was already existing.

source

pub fn changes(&self, last_seq: Option<Value>) -> ChangesStream

A streaming handler for the CouchDB _changes endpoint.

See the CouchDB docs for details on the semantics.

It can return all changes from a seq string, and can optionally run in infinite (live) mode.

Trait Implementations§

source§

impl Clone for Database

source§

fn clone(&self) -> Database

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Database

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more