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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use crate::common::unwrap_item;
use crate::PrimaryIterator;
use crate::{
KeyDefinition, PrimaryIteratorStartWith, Result, SDBItem, SecondaryIterator,
SecondaryIteratorStartWith,
};
use redb::ReadableTable as RedbReadableTable;
use std::marker::PhantomData;
use std::ops::RangeBounds;
pub trait ReadableTable<'db, 'txn> {
type Table: redb::ReadableTable<&'static [u8], &'static [u8]>;
type Transaction<'x>;
fn open_table(
&mut self,
txn: &'txn Self::Transaction<'db>,
table_name: &'static str,
) -> Result<()>;
fn get_table(&self, table_name: &'static str) -> Option<&Self::Table>;
/// Get a value from the table.
/// Returns `Ok(None)` if the key does not exist.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// ```
/// use serde::{Deserialize, Serialize};
/// use struct_db::*;
///
/// #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
/// #[struct_db(fn_primary_key(p_key))]
/// struct Data(u32);
/// impl Data {pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()}}
///
/// fn main() {
/// let mut db = Db::create_tmp("my_db_rt_g").unwrap();
/// // Initialize the table
/// db.define::<Data>();
///
/// // Insert a new data
/// let mut txn = db.transaction().unwrap();
/// {
/// let mut tables = txn.tables();
/// tables.insert(&txn, Data(1)).unwrap();
/// }
/// txn.commit().unwrap(); // /!\ Don't forget to commit
///
/// // Get a value from the table
/// let txn_read = db.read_transaction().unwrap();
/// let mut tables = txn_read.tables();
///
/// // Using explicit type (turbofish syntax)
/// let value = tables.primary_get::<Data>(&txn_read, &1u32.to_be_bytes());
///
/// // Using type inference
/// let value: Option<Data> = tables.primary_get(&txn_read, &1u32.to_be_bytes()).unwrap();
/// }
fn primary_get<T: SDBItem>(
&mut self,
txn: &'txn Self::Transaction<'db>,
key: &[u8],
) -> Result<Option<T>> {
let table_name = T::struct_db_schema().table_name;
self.open_table(txn, table_name)?;
let table = self.get_table(table_name).unwrap();
let item = table.get(key)?;
Ok(unwrap_item(item))
}
/// Iterate over all the values of the table.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// ```
/// use serde::{Deserialize, Serialize};
/// use struct_db::*;
///
/// #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
/// #[struct_db(fn_primary_key(p_key))]
/// struct Data(u32);
/// impl Data{ pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()} }
///
/// fn main() {
/// use std::arch::asm;
/// let mut db = Db::create_tmp("my_db_p_iter").unwrap();
/// // Initialize the table
/// db.define::<Data>();
///
/// // Insert a new data
/// let mut txn = db.transaction().unwrap();
/// {
/// let mut tables = txn.tables();
/// tables.insert(&txn, Data(1)).unwrap();
/// }
/// txn.commit().unwrap(); // /!\ Don't forget to commit
///
/// // Iterate over all the values of the table
/// let txn_read = db.read_transaction().unwrap();
/// let mut tables = txn_read.tables();
///
/// for value in tables.primary_iter::<Data>(&txn_read).unwrap() {
/// assert_eq!(value, Data(1));
/// }
/// }
fn primary_iter<'a, T: SDBItem>(
&'a mut self,
txn: &'txn Self::Transaction<'db>,
) -> Result<PrimaryIterator<'_, 'txn, 'db, T>>
where
'db: 'a,
'txn: 'a,
{
self.primary_iter_range(txn, ..)
}
/// Iterate over all the values of the table that are in the given range.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// - Similar to [`primary_iter`](ReadableTable::primary_iter) but with a range.
/// - See tests/09_iterator.rs for more examples.
fn primary_iter_range<'a, 'b, T>(
&'a mut self,
txn: &'txn Self::Transaction<'db>,
range_value: impl RangeBounds<&'a [u8]> + 'a,
) -> Result<PrimaryIterator<'_, 'txn, 'db, T>>
where
T: SDBItem,
'db: 'a,
'txn: 'a,
{
let table_name = T::struct_db_schema().table_name;
self.open_table(txn, table_name)?;
let table = self.get_table(table_name).unwrap();
let range = table.range::<&'_ [u8]>(range_value)?;
Ok(PrimaryIterator {
range,
_marker: PhantomData,
})
}
/// Iterate over all the values of the table that start with the given prefix.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// - Similar to [`primary_iter`](ReadableTable::primary_iter) but with a prefix.
/// - See tests/09_iterator.rs for more examples.
fn primary_iter_start_with<'a, T>(
&'a mut self,
txn: &'txn Self::Transaction<'db>,
prefix_value: &'a [u8],
) -> Result<PrimaryIteratorStartWith<'_, 'txn, 'db, T>>
where
T: SDBItem,
'db: 'a,
'txn: 'a,
{
let table_name = T::struct_db_schema().table_name;
self.open_table(txn, table_name)?;
let table = self.get_table(table_name).unwrap();
let range = table.range::<&'_ [u8]>(prefix_value..)?;
Ok(PrimaryIteratorStartWith {
range,
start_with: prefix_value,
_marker: PhantomData,
})
}
/// Get a value from the table using a secondary key.
/// Returns `Ok(None)` if the key does not exist.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// Set the key_definition: use the `<your_type>Key` enum generated by the `struct_db`
/// macro to specify the key. Like this: `<your_type>Key::<your_secondary_key>`.
///
/// E.g: `tables.get_by_key(&txn_read, <your_type>Key::<your_secondary_key>, &your_key)`
///
/// # Example
/// ```
/// use serde::{Deserialize, Serialize};
/// use struct_db::*;
///
/// #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
/// #[struct_db(fn_primary_key(p_key),fn_secondary_key(s_key))]
/// struct Data(u32, String);
/// impl Data {
/// pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()}
/// pub fn s_key(&self) -> Vec<u8> {self.1.as_bytes().to_vec()}
/// }
///
/// fn main() {
/// let mut db = Db::create_tmp("my_db_rt_gk").unwrap();
/// // Initialize the table
/// db.define::<Data>();
///
/// // Insert a new data
/// let mut txn = db.transaction().unwrap();
/// {
/// let mut tables = txn.tables();
/// tables.insert(&txn, Data(1, "hello".to_string())).unwrap();
/// }
/// txn.commit().unwrap(); // /!\ Don't forget to commit
///
/// // Get a value from the table
/// let txn_read = db.read_transaction().unwrap();
/// let mut tables = txn_read.tables();
/// // Using explicit type (turbofish syntax)
/// let value = tables.secondary_get::<Data>(&txn_read, DataKey::s_key, &"hello".as_bytes());
///
/// // Using type inference
/// let value: Option<Data> = tables.secondary_get(&txn_read, DataKey::s_key, &"hello".as_bytes()).unwrap();
/// }
fn secondary_get<T: SDBItem>(
&mut self,
txn: &'txn Self::Transaction<'db>,
key_def: impl KeyDefinition,
key: &[u8],
) -> Result<Option<T>> {
let table_name = key_def.secondary_table_name();
let primary_key: Vec<u8> = {
self.open_table(txn, table_name)?;
let table = self.get_table(table_name).unwrap();
let value = table.get(key)?;
if let Some(value) = value {
value.value().into()
} else {
return Ok(None);
}
};
Ok(Some(self.primary_get(txn, &primary_key)?.ok_or(
crate::Error::PrimaryKeyNotFound {
primary_key: primary_key.to_vec(),
},
)?))
}
/// Iterate over all the values of the table that start with the given prefix.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// - Similar to [`primary_iter`](ReadableTable::primary_iter) but with a prefix.
/// - See [`get_by_key`](crate::Tables::secondary_get) too know how to set the key_definition.
/// - See tests/09_iterator.rs for more examples.
fn secondary_iter<'a, T: SDBItem>(
&mut self,
txn: &'txn Self::Transaction<'db>,
key_def: impl KeyDefinition,
) -> Result<SecondaryIterator<'_, 'txn, 'db, T, Self::Table>> {
self.secondary_iter_range(txn, key_def, ..)
}
/// Iterate over all the values of the table that start with the given prefix.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// - Similar to [`primary_iter`](ReadableTable::primary_iter) but with a prefix.
/// - See [`get_by_key`](crate::Tables::secondary_get) too know how to set the key_definition.
/// - See tests/09_iterator.rs for more examples.
fn secondary_iter_range<'a, 'b, T>(
&'a mut self,
txn: &'txn Self::Transaction<'db>,
key_def: impl KeyDefinition,
range_key: impl RangeBounds<&'b [u8]> + 'b,
) -> Result<SecondaryIterator<'_, 'txn, 'db, T, Self::Table>>
where
T: SDBItem,
'a: 'b,
{
let main_table_name = T::struct_db_schema().table_name;
self.open_table(txn, main_table_name)?;
let secondary_table_name = key_def.secondary_table_name();
self.open_table(txn, secondary_table_name)?;
let main_table = self.get_table(main_table_name).unwrap();
let secondary_table = self.get_table(secondary_table_name).unwrap();
let range = secondary_table.range::<&'_ [u8]>(range_key)?;
Ok(SecondaryIterator {
range,
main_table,
_marker: PhantomData,
})
}
/// Iterate over all the values of the table that start with the given prefix.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// - Similar to [`primary_iter`](ReadableTable::primary_iter) but with a prefix.
/// - See [`get_by_key`](crate::Tables::secondary_get) too know how to set the key_definition.
/// - See tests/09_iterator.rs for more examples.
fn secondary_iter_start_with<'a, 'b, T>(
&'a mut self,
txn: &'txn Self::Transaction<'db>,
key_def: impl KeyDefinition,
key_prefix: &'b [u8],
) -> Result<SecondaryIteratorStartWith<'a, 'txn, 'db, T, Self::Table>>
where
T: SDBItem,
'b: 'a,
{
let main_table_name = T::struct_db_schema().table_name;
self.open_table(txn, main_table_name)?;
let secondary_table_name = key_def.secondary_table_name();
self.open_table(txn, secondary_table_name)?;
let main_table = self.get_table(main_table_name).unwrap();
let secondary_table = self.get_table(secondary_table_name).unwrap();
let range = secondary_table.range::<&'_ [u8]>(key_prefix..)?;
Ok(SecondaryIteratorStartWith {
range,
start_with: key_prefix,
main_table,
_marker: PhantomData,
})
}
/// Returns the number of elements in the table.
/// Available in [`Tables`](crate::Tables) and [`ReadOnlyTables`](crate::ReadOnlyTables).
///
/// # Example
/// ```
/// use serde::{Deserialize, Serialize};
/// use struct_db::*;
///
/// #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
/// #[struct_db(fn_primary_key(p_key))]
/// struct Data(u32);
/// impl Data{ pub fn p_key(&self) -> Vec<u8> {self.0.to_be_bytes().to_vec()} }
///
/// fn main() {
/// use std::arch::asm;
/// let mut db = Db::create_tmp("my_db_len").unwrap();
/// // Initialize the table
/// db.define::<Data>();
///
/// // Insert a new data
/// let mut txn = db.transaction().unwrap();
/// {
/// let mut tables = txn.tables();
/// tables.insert(&txn, Data(1)).unwrap();
/// }
/// txn.commit().unwrap(); // /!\ Don't forget to commit
///
/// // Get the number of elements
/// let txn_read = db.read_transaction().unwrap();
/// let mut tables = txn_read.tables();
/// let len = tables.len::<Data>(&txn_read).unwrap();
/// assert_eq!(len, 1);
/// }
fn len<T: SDBItem>(&mut self, txn: &'txn Self::Transaction<'db>) -> Result<u64> {
let table_name = T::struct_db_schema().table_name;
self.open_table(txn, table_name)?;
let table = self.get_table(table_name).unwrap();
let result = table.len()?;
Ok(result)
}
}