1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::{marker::PhantomData, sync::Arc};
use engula_apis::*;
use crate::{Any, Client, CollectionTxn, DatabaseTxn, Error, Object, ObjectValue, Result};
#[derive(Clone)]
pub struct Collection<T> {
inner: Arc<CollectionInner>,
_marker: PhantomData<T>,
}
impl<T: Object> Collection<T> {
pub(crate) fn new(coname: String, dbname: String, client: Client) -> Self {
let inner = CollectionInner {
dbname,
coname,
client,
};
Self {
inner: Arc::new(inner),
_marker: PhantomData,
}
}
pub fn name(&self) -> &str {
&self.inner.coname
}
pub async fn desc(&self) -> Result<CollectionDesc> {
let req = DescribeCollectionRequest {
name: self.inner.coname.clone(),
};
let req = collection_request_union::Request::DescribeCollection(req);
let res = self.inner.collection_union_call(req).await?;
let desc = if let collection_response_union::Response::DescribeCollection(res) = res {
res.desc
} else {
None
};
desc.ok_or_else(|| Error::internal("missing collection description"))
}
pub fn begin(&self) -> CollectionTxn<T> {
self.inner.new_txn()
}
pub fn begin_with(&self, parent: DatabaseTxn) -> CollectionTxn<T> {
parent.collection(self.inner.coname.clone())
}
pub fn object(&self, id: impl Into<Vec<u8>>) -> T {
self.inner.new_object(id.into())
}
}
impl<T: Object> Collection<T> {
fn any(&self, id: impl Into<Vec<u8>>) -> Any {
self.inner.new_object(id.into())
}
pub async fn get(&self, id: impl Into<Vec<u8>>) -> Result<Option<T::Value>> {
let value = self.any(id).load().await?;
T::Value::cast_from_option(value)
}
pub async fn set(&self, id: impl Into<Vec<u8>>, value: impl Into<T::Value>) -> Result<()> {
self.any(id).store(value.into()).await
}
pub async fn delete(&self, id: impl Into<Vec<u8>>) -> Result<()> {
self.any(id).reset().await
}
}
pub struct CollectionInner {
dbname: String,
coname: String,
client: Client,
}
impl CollectionInner {
fn new_txn<T: Object>(&self) -> CollectionTxn<T> {
CollectionTxn::new(
self.dbname.clone(),
self.coname.clone(),
self.client.clone(),
)
}
fn new_object<T: Object>(&self, id: Vec<u8>) -> T {
Any::new(
id,
self.dbname.clone(),
self.coname.clone(),
self.client.clone(),
)
.into()
}
async fn collection_union_call(
&self,
req: collection_request_union::Request,
) -> Result<collection_response_union::Response> {
self.client.collection_union(self.dbname.clone(), req).await
}
}