[][src]Struct couch_rs::database::Database

pub struct Database { /* fields omitted */ }

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

Implementations

impl Database[src]

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

pub fn name(&self) -> &str[src]

pub async fn compact<'_>(&'_ self) -> bool[src]

Launches the compact process

pub async fn compact_views<'_>(&'_ self) -> bool[src]

Starts the compaction of all views

pub async fn compact_index<'_, '_>(&'_ self, index: &'_ str) -> bool[src]

Starts the compaction of a given index

pub async fn exists<'_, '_>(&'_ self, id: &'_ str) -> bool[src]

Checks if a document ID exists

Usage:

use std::error::Error;

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    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(());
}

pub async fn get<'_, '_>(&'_ self, id: &'_ str) -> Result<Document, CouchError>[src]

Gets one document

pub async fn get_bulk<'_>(
    &'_ self,
    ids: Vec<DocumentId>
) -> Result<DocumentCollection, CouchError>
[src]

Gets documents in bulk with provided IDs list

pub async fn bulk_docs<'_>(
    &'_ self,
    raw_docs: Vec<Value>
) -> Result<Vec<DocumentCreatedResult>, CouchError>
[src]

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.

pub async fn get_bulk_params<'_>(
    &'_ self,
    ids: Vec<DocumentId>,
    params: Option<QueryParams>
) -> Result<DocumentCollection, CouchError>
[src]

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::document::Document;
use std::error::Error;
use serde_json::json;

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    let db = client.db(TEST_DB).await?;
    let doc_1 = Document::new(json!({
                    "_id": "john",
                    "first_name": "John",
                    "last_name": "Doe"
                }));

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

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

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

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

pub async fn get_all<'_>(&'_ self) -> Result<DocumentCollection, CouchError>[src]

Gets all the documents in database

pub async fn get_all_batched<'_>(
    &'_ self,
    tx: Sender<DocumentCollection>,
    batch_size: u64,
    max_results: u64
) -> Result<u64, CouchError>
[src]

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

pub async fn find_batched<'_>(
    &'_ self,
    __arg1: FindQuery,
    __arg2: Sender<DocumentCollection>,
    batch_size: u64,
    max_results: u64
) -> Result<u64, CouchError>
[src]

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

pub async fn query_many_all_docs<'_>(
    &'_ self,
    queries: QueriesParams
) -> Result<Vec<ViewCollection>, CouchError>
[src]

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::document::Document;
use std::error::Error;
use serde_json::json;

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "vehicles";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    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(())
}

pub async fn query_many<'_, '_, '_>(
    &'_ self,
    design_name: &'_ str,
    view_name: &'_ str,
    queries: QueriesParams
) -> Result<Vec<ViewCollection>, CouchError>
[src]

Executes multiple queries against a view.

pub async fn get_all_params<'_>(
    &'_ self,
    params: Option<QueryParams>
) -> Result<DocumentCollection, CouchError>
[src]

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

pub async fn find<'_, '_>(
    &'_ self,
    query: &'_ FindQuery
) -> Result<DocumentCollection, CouchError>
[src]

Finds a document in the database through a Mango query. Usage:

use couch_rs::types::find::FindQuery;
use std::error::Error;

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    let db = client.db(TEST_DB).await?;
    let find_all = FindQuery::find_all();
    let docs = db.find(&find_all).await?;
    Ok(())
}

pub async fn save<'_>(&'_ self, doc: Document) -> Result<Document, CouchError>[src]

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 std::error::Error;
use serde_json::{from_value, to_value};
use couch_rs::types::document::DocumentId;

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "test_db";

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    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 value = to_value(seed_doc)?;
    db.create(value).await?;

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

    db.save(doc).await?;
    Ok(())
}

pub async fn create<'_>(
    &'_ self,
    raw_doc: Value
) -> Result<Document, CouchError>
[src]

Creates a document from a raw JSON document Value.

pub async fn upsert<'_>(&'_ self, doc: Document) -> Result<Document, CouchError>[src]

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::document::Document;
use std::error::Error;
use serde_json::json;

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    let db = client.db(TEST_DB).await?;
    let doc = Document::new(json!({
                    "_id": "doe",
                    "first_name": "John",
                    "last_name": "Doe"
                }));

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

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

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

pub async fn create_view<T: Into<Value>, '_, '_>(
    &'_ self,
    design_name: &'_ str,
    views: T
) -> Result<DesignCreated, CouchError>
[src]

Creates a design with one of more view documents.

Usage:

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

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    let db = client.db(TEST_DB).await?;

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

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

pub async fn query<'_, '_, '_>(
    &'_ self,
    design_name: &'_ str,
    view_name: &'_ str,
    __arg3: Option<QueryParams>
) -> Result<ViewCollection, CouchError>
[src]

Executes a query against a view.

pub async fn execute_update<'_, '_, '_, '_>(
    &'_ self,
    design_id: &'_ str,
    name: &'_ str,
    document_id: &'_ str,
    body: Option<Value>
) -> Result<String, CouchError>
[src]

Executes an update function.

pub async fn remove<'_>(&'_ self, doc: Document) -> bool[src]

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

use couch_rs::types::find::FindQuery;
use std::error::Error;
use serde_json::{from_value, to_value};
use couch_rs::types::document::DocumentId;
use couch_rs::document::Document;

const DB_HOST: &str = "http://admin:password@localhost:5984";
const TEST_DB: &str = "test_db";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = couch_rs::Client::new(DB_HOST)?;
    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("123").await.ok() {
        db.remove(doc).await;
    }

    Ok(())
}

pub async fn insert_index<'_, '_>(
    &'_ self,
    name: &'_ str,
    spec: IndexFields
) -> Result<DesignCreated, CouchError>
[src]

Inserts an index in a naive way, if it already exists, will throw an Err

pub async fn read_indexes<'_>(&'_ self) -> Result<DatabaseIndexList, CouchError>[src]

Reads the database's indexes and returns them

pub async fn ensure_index<'_, '_>(
    &'_ self,
    name: &'_ str,
    spec: IndexFields
) -> Result<bool, CouchError>
[src]

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.

Trait Implementations

impl Clone for Database[src]

impl Debug for Database[src]

Auto Trait Implementations

impl !RefUnwindSafe for Database

impl Send for Database

impl Sync for Database

impl Unpin for Database

impl !UnwindSafe for Database

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Sealed<T> for T where
    T: ?Sized

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.