monsta_client/
database.rs

1use monsta_proto::*;
2
3use crate::{client::Client, metadata, Collection, Error, Result};
4
5pub struct Database {
6    client: Client,
7    database_id: u64,
8}
9
10impl Database {
11    pub fn new(client: Client, database_id: u64) -> Self {
12        Self {
13            client,
14            database_id,
15        }
16    }
17
18    pub async fn desc(&self) -> Result<DatabaseDesc> {
19        let req = DatabaseRequest {
20            describe_database: Some(DescribeDatabaseRequest {
21                id: self.database_id,
22                ..Default::default()
23            }),
24            ..Default::default()
25        };
26        let res = self.client.database_call(req).await?;
27        let desc = res
28            .describe_database
29            .and_then(|x| x.desc)
30            .ok_or_else(|| Error::InvalidResponse)?;
31        Ok(desc)
32    }
33
34    pub async fn create_collection(
35        &self,
36        spec: impl Into<metadata::CollectionSpec>,
37    ) -> Result<Collection> {
38        let req = CollectionRequest {
39            database_id: self.database_id,
40            create_collection: Some(CreateCollectionRequest {
41                spec: Some(spec.into().into()),
42            }),
43            ..Default::default()
44        };
45        let res = self.client.collection_call(req).await?;
46        let desc = res
47            .create_collection
48            .and_then(|x| x.desc)
49            .ok_or_else(|| Error::InvalidResponse)?;
50        Ok(Collection::new(
51            self.client.clone(),
52            desc.database_id,
53            desc.id,
54        ))
55    }
56
57    pub async fn lookup_collection(&self, name: impl Into<String>) -> Result<Collection> {
58        let desc = self.describe_collection(name).await?;
59        Ok(Collection::new(
60            self.client.clone(),
61            desc.database_id,
62            desc.id,
63        ))
64    }
65
66    pub async fn describe_collection(&self, name: impl Into<String>) -> Result<CollectionDesc> {
67        let req = CollectionRequest {
68            database_id: self.database_id,
69            describe_collection: Some(DescribeCollectionRequest {
70                name: name.into(),
71                ..Default::default()
72            }),
73            ..Default::default()
74        };
75        let res = self.client.collection_call(req).await?;
76        let desc = res
77            .describe_collection
78            .and_then(|x| x.desc)
79            .ok_or_else(|| Error::InvalidResponse)?;
80        Ok(desc)
81    }
82}