1use crate::err::Error;
18use crate::Database;
19use imbl::ordmap::Entry;
20use imbl::OrdMap;
21use std::borrow::Borrow;
22use std::fmt::Debug;
23use std::mem::drop;
24use std::ops::Range;
25use std::sync::Arc;
26use tokio::sync::OwnedMutexGuard;
27
28pub struct Transaction<K, V>
30where
31 K: Ord + Clone + Debug + Sync + Send + 'static,
32 V: Eq + Clone + Debug + Sync + Send + 'static,
33{
34 done: bool,
36 write: bool,
38 snapshot: OrdMap<K, V>,
40 database: Database<K, V>,
42 writelock: Option<OwnedMutexGuard<()>>,
44}
45
46impl<K, V> Transaction<K, V>
47where
48 K: Ord + Clone + Debug + Sync + Send + 'static,
49 V: Eq + Clone + Debug + Sync + Send + 'static,
50{
51 pub(crate) fn read(db: Database<K, V>, lock: Option<OwnedMutexGuard<()>>) -> Transaction<K, V> {
53 Transaction {
54 done: false,
55 write: false,
56 snapshot: (*(*db.datastore.load())).clone(),
57 database: db,
58 writelock: lock,
59 }
60 }
61 pub(crate) fn write(
63 db: Database<K, V>,
64 lock: Option<OwnedMutexGuard<()>>,
65 ) -> Transaction<K, V> {
66 Transaction {
67 done: false,
68 write: true,
69 snapshot: (*(*db.datastore.load())).clone(),
70 database: db,
71 writelock: lock,
72 }
73 }
74
75 pub fn closed(&self) -> bool {
77 self.done
78 }
79
80 pub fn cancel(&mut self) -> Result<(), Error> {
82 if self.done == true {
84 return Err(Error::TxClosed);
85 }
86 self.done = true;
88 if let Some(lock) = self.writelock.take() {
90 drop(lock);
91 }
92 Ok(())
94 }
95
96 pub fn commit(&mut self) -> Result<(), Error> {
98 if self.done == true {
100 return Err(Error::TxClosed);
101 }
102 if self.write == false {
104 return Err(Error::TxNotWritable);
105 }
106 self.done = true;
108 self.database.datastore.store(Arc::new(self.snapshot.clone()));
110 if let Some(lock) = self.writelock.take() {
112 drop(lock);
113 }
114 Ok(())
116 }
117
118 pub fn exists<Q>(&self, key: Q) -> Result<bool, Error>
120 where
121 Q: Borrow<K>,
122 {
123 if self.done == true {
125 return Err(Error::TxClosed);
126 }
127 let res = self.snapshot.contains_key(key.borrow());
129 Ok(res)
131 }
132
133 pub fn get<Q>(&self, key: Q) -> Result<Option<V>, Error>
135 where
136 Q: Borrow<K>,
137 {
138 if self.done == true {
140 return Err(Error::TxClosed);
141 }
142 let res = self.snapshot.get(key.borrow()).cloned();
144 Ok(res)
146 }
147
148 pub fn set<Q>(&mut self, key: Q, val: V) -> Result<(), Error>
150 where
151 Q: Into<K>,
152 {
153 if self.done == true {
155 return Err(Error::TxClosed);
156 }
157 if self.write == false {
159 return Err(Error::TxNotWritable);
160 }
161 self.snapshot.insert(key.into(), val);
163 Ok(())
165 }
166
167 pub fn put<Q>(&mut self, key: Q, val: V) -> Result<(), Error>
169 where
170 Q: Borrow<K> + Into<K>,
171 {
172 if self.done == true {
174 return Err(Error::TxClosed);
175 }
176 if self.write == false {
178 return Err(Error::TxNotWritable);
179 }
180 match self.snapshot.entry(key.into()) {
182 Entry::Vacant(v) => {
183 v.insert(val);
184 }
185 _ => return Err(Error::KeyAlreadyExists),
186 };
187 Ok(())
189 }
190
191 pub fn putc<Q>(&mut self, key: Q, val: V, chk: Option<V>) -> Result<(), Error>
193 where
194 Q: Borrow<K> + Into<K>,
195 {
196 if self.done == true {
198 return Err(Error::TxClosed);
199 }
200 if self.write == false {
202 return Err(Error::TxNotWritable);
203 }
204 match (self.snapshot.entry(key.into()), &chk) {
206 (Entry::Occupied(mut v), Some(w)) if v.get() == w => {
207 v.insert(val);
208 }
209 (Entry::Vacant(v), None) => {
210 v.insert(val);
211 }
212 _ => return Err(Error::ValNotExpectedValue),
213 };
214 Ok(())
216 }
217
218 pub fn del<Q>(&mut self, key: Q) -> Result<(), Error>
220 where
221 Q: Borrow<K>,
222 {
223 if self.done == true {
225 return Err(Error::TxClosed);
226 }
227 if self.write == false {
229 return Err(Error::TxNotWritable);
230 }
231 self.snapshot.remove(key.borrow());
233 Ok(())
235 }
236
237 pub fn delc<Q>(&mut self, key: Q, chk: Option<V>) -> Result<(), Error>
239 where
240 Q: Borrow<K> + Into<K>,
241 {
242 if self.done == true {
244 return Err(Error::TxClosed);
245 }
246 if self.write == false {
248 return Err(Error::TxNotWritable);
249 }
250 match (self.snapshot.entry(key.into()), &chk) {
252 (Entry::Occupied(v), Some(w)) if v.get() == w => {
253 v.remove();
254 }
255 (Entry::Vacant(_), None) => {
256 }
258 _ => return Err(Error::ValNotExpectedValue),
259 };
260 Ok(())
262 }
263
264 pub fn keys<Q>(&self, rng: Range<Q>, limit: usize) -> Result<Vec<K>, Error>
266 where
267 Q: Into<K>,
268 {
269 if self.done == true {
271 return Err(Error::TxClosed);
272 }
273 let beg = rng.start.into();
275 let end = rng.end.into();
276 let res = self.snapshot.range(beg..end).take(limit).map(|(k, _)| k.clone()).collect();
278 Ok(res)
280 }
281
282 pub fn scan<Q>(&self, rng: Range<Q>, limit: usize) -> Result<Vec<(K, V)>, Error>
284 where
285 Q: Into<K>,
286 {
287 if self.done == true {
289 return Err(Error::TxClosed);
290 }
291 let beg = rng.start.into();
293 let end = rng.end.into();
294 let res = self
296 .snapshot
297 .range(beg..end)
298 .take(limit)
299 .map(|(k, v)| (k.clone(), v.clone()))
300 .collect();
301 Ok(res)
303 }
304}