sqlite-collections 0.1.0

Rust collection types backed by sqlite database files.
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use crate::serializer::Serializer;
use crate::Savepointable;
use crate::{db, identifier::Identifier};
use rusqlite::{params, Connection, OptionalExtension, Savepoint};

use std::ops::Range;
use std::{borrow::Borrow, marker::PhantomData};

mod error;
// mod iter;
// pub use iter::Iter;

pub use error::{Error, OpenError};

#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)]
pub struct Config<'db, 'table> {
    pub database: Identifier<'db>,
    pub table_base: Identifier<'table>,
    pub max_elements_per_node: u16,
}

impl Default for Config<'static, 'static> {
    fn default() -> Self {
        Config {
            database: "main".try_into().unwrap(),
            table_base: "btree::set".try_into().unwrap(),
            max_elements_per_node: 64,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum ElementPosition {
    Exists { node: i64, index: u16 },
    Prospective { node: i64, index: u16 },
}

/// A b-tree set.  The database does not ensure uniqueness of the elements.
/// Uniqueness is checked at the application level via the Ord trait. This
/// is useful for non-deterministic serialization, but is slower and more
/// complicated than the DSSet.
#[derive(Debug)]
pub struct BTreeSet<'db, S, C>
where
    S: Serializer,
    C: Savepointable,
{
    connection: C,
    database: Identifier<'db>,
    nodes_table: Identifier<'static>,
    elements_table: Identifier<'static>,
    max_elements_per_node: u16,
    serializer: PhantomData<S>,
}

impl<S, C> BTreeSet<'static, S, C>
where
    S: Serializer,
    C: Savepointable,
{
    pub fn open(connection: C) -> Result<Self, OpenError> {
        BTreeSet::open_with_config(connection, Config::default())
    }

    /// Open a set without creating it or checking if it exists.  This is safe
    /// if you call a safe open in (or under) the same transaction or savepoint
    /// beforehand.
    pub fn unchecked_open(connection: C) -> Self {
        BTreeSet::unchecked_open_with_config(connection, Config::default())
    }
}

impl<'db, S, C> BTreeSet<'db, S, C>
where
    S: Serializer,
    C: Savepointable,
{
    pub fn open_with_config(mut connection: C, config: Config<'db, '_>) -> Result<Self, OpenError> {
        let database = config.database;
        let nodes_table = config.table_base.clone() + &Identifier::try_from("::nodes").unwrap();
        let elements_table = config.table_base + &Identifier::try_from("::elements").unwrap();
        let nodes_index = nodes_table.clone() + &Identifier::try_from("::index").unwrap();
        let max_elements_per_node = config.max_elements_per_node;

        {
            let sp = connection.savepoint()?;

            let mut nodes_version = db::setup(
                &sp,
                &database,
                &nodes_table,
                &format!("btree::set::nodes<{max_elements_per_node}>"),
            )?;
            let mut elements_version = db::setup(
                &sp,
                &database,
                &nodes_table,
                &format!("btree::set::elements<{max_elements_per_node}>"),
            )?;
            if nodes_version < 0 {
                return Err(OpenError::TableVersion(nodes_version));
            }
            if elements_version < 0 {
                return Err(OpenError::TableVersion(elements_version));
            }
            let prev_nodes_version = nodes_version;
            if nodes_version < 1 {
                let trailer = db::strict();
                let sql_type = S::sql_type();

                sp.execute(
                    &format!(
                        "CREATE TABLE {database}.{nodes_table} (
                            id INTEGER PRIMARY KEY NOT NULL,
                            parent INTEGER NULL DEFAULT NULL REFERENCES {database}.{nodes_table} (id) ON DELETE CASCADE,
                            index INTEGER NULL DEFAULT NULL,
                            CHECK ((parent IS NULL AND index IS NULL) OR (parent IS NOT NULL AND index IS NOT NULL))
                        ){trailer}"
                    ),
                    [],
                )?;

                sp.execute(
                    &format!(
                        "CREATE UNIQUE INDEX {database}.{nodes_index} ON (parent ASC, index ASC)"
                    ),
                    [],
                )?;

                // Create root node.
                sp.execute(
                    &format!("INSERT INTO {database}.{nodes_table} DEFAULT VALUES"),
                    [],
                )?;
                nodes_version = 1;
            }
            if nodes_version > 1 {
                return Err(OpenError::TableVersion(nodes_version));
            }
            if prev_nodes_version != nodes_version {
                db::set_version(&sp, &database, &nodes_table, nodes_version)?;
            }
            let prev_elements_version = elements_version;
            if elements_version < 1 {
                let trailer = db::strict_without_rowid();
                let sql_type = S::sql_type();

                sp.execute(
                    &format!(
                        "CREATE TABLE {database}.{elements_table} (
                            node INTEGER NOT NULL REFERENCES {database}.{nodes_table} (id) ON DELETE RESTRICT,
                            index INTEGER NOT NULL,
                            key {sql_type} NOT NULL,
                            PRIMARY KEY (node, index)
                        ){trailer}"
                    ),
                    [],
                )?;
                elements_version = 1;
            }
            if elements_version > 1 {
                return Err(OpenError::TableVersion(elements_version));
            }
            if prev_elements_version != elements_version {
                db::set_version(&sp, &database, &elements_table, elements_version)?;
            }

            sp.commit()?;
        }
        Ok(Self {
            connection,
            database,
            elements_table,
            nodes_table,
            max_elements_per_node,
            serializer: PhantomData,
        })
    }

    /// Open a set without creating it or checking if it exists.  This is safe
    /// if you call a safe open in (or under) the same transaction or savepoint
    /// beforehand.
    pub fn unchecked_open_with_config(connection: C, config: Config<'db, '_>) -> Self {
        let database = config.database;
        let nodes_table = config.table_base;
        let nodes_table = config.table_base.clone() + &Identifier::try_from("::nodes").unwrap();
        let elements_table = config.table_base + &Identifier::try_from("::elements").unwrap();

        Self {
            connection,
            database,
            elements_table,
            nodes_table,
            max_elements_per_node: config.max_elements_per_node,
            serializer: PhantomData,
        }
    }

    /// Binary search for element insertion point in node
    fn find_element_in_node(
        database: &Identifier,
        nodes_table: &Identifier,
        elements_table: &Identifier,
        connection: &Connection,
        value: &S::TargetBorrowed,
        node: i64,
        search: Option<Range<u16>>,
    ) -> Result<ElementPosition, Error<S>>
    where
        S::TargetBorrowed: Ord,
    {
        match search {
            Some(Range { start, end }) => {
                if start <= end {
                    Ok(ElementPosition::Prospective { node, index: start })
                } else {
                    let mid = start / 2 + end / 2;
                    let buffer: S::Buffer = connection
                        .prepare_cached(&format!(
                            "SELECT value FROM {database}.{elements_table} WHERE node = ? AND index = ?"
                        ))?
                        .query_row(params![node, mid], |row| row.get(0))?;
                    let checker = S::deserialize(buffer).map_err(|e| Error::Deserialize(e))?;

                    match checker.cmp(value) {
                        std::cmp::Ordering::Less => Self::find_element_in_node(
                            database,
                            nodes_table,
                            elements_table,
                            connection,
                            value,
                            node,
                            Some(start..mid),
                        ),
                        std::cmp::Ordering::Equal => {
                            Ok(ElementPosition::Exists { node, index: mid })
                        }
                        std::cmp::Ordering::Greater => Self::find_element_in_node(
                            database,
                            nodes_table,
                            elements_table,
                            connection,
                            value,
                            node,
                            Some((mid + 1)..end),
                        ),
                    }
                }
            }
            None => {
                let node_length = connection
                    .prepare_cached(&format!(
                        "SELECT COUNT(*) FROM {database}.{elements_table} WHERE node = ?"
                    ))?
                    .query_row(params![node], |row| row.get(0))?;

                Self::find_element_in_node(
                    database,
                    nodes_table,
                    elements_table,
                    connection,
                    value,
                    node,
                    Some(0..node_length),
                )
            }
        }
    }

    /// Find the position where the element already exists, or where it would
    /// be inserted.
    /// Exists may be in any node, Prospective will always be a leaf node.
    fn find_element_position(
        database: &Identifier,
        nodes_table: &Identifier,
        elements_table: &Identifier,
        connection: &Connection,
        value: &S::TargetBorrowed,
        node: Option<i64>,
    ) -> Result<ElementPosition, Error<S>>
    where
        S::TargetBorrowed: Ord,
    {
        match node {
            Some(node) => {
                match Self::find_element_in_node(
                    database,
                    nodes_table,
                    elements_table,
                    connection,
                    value,
                    node,
                    None,
                )? {
                    ElementPosition::Exists { node, index } => {
                        Ok(ElementPosition::Exists { node, index })
                    }
                    ElementPosition::Prospective { node, index } => {
                        let node_id = connection
                            .prepare_cached(&format!("SELECT id FROM {database}.{nodes_table} WHERE parent = ? AND index = ?"))?
                            .query_row(params![node, index], |row| row.get(0))
                            .optional()?;
                        match node_id {
                            Some(node) => Self::find_element_position(
                                database,
                                nodes_table,
                                elements_table,
                                connection,
                                value,
                                node,
                            ),
                            None => Ok(ElementPosition::Prospective { node, index }),
                        }
                    }
                }
            }
            None => {
                let id = connection
                    .prepare_cached(&format!("SELECT id FROM {database}.{nodes_table} WHERE parent IS NULL AND index IS NULL"))?
                    .query_row([], |row| row.get(0))?;

                Self::find_element_position(
                    database,
                    nodes_table,
                    elements_table,
                    connection,
                    value,
                    Some(id),
                )
            }
        }
    }

    pub fn insert(&mut self, value: &S::TargetBorrowed) -> Result<bool, Error<S>> {
        // TODO
        let database = &self.database;
        let table = &self.table;
        let serialized = match S::serialize(value) {
            Ok(s) => s,
            Err(e) => return Err(Error::Serialize(e)),
        };

        let sp = self.connection.savepoint()?;
        let ret = if db::has_upsert() {
            sp.prepare_cached(&format!(
                "INSERT INTO {database}.{table} (key) VALUES (?) ON CONFLICT DO NOTHING"
            ))?
            .execute(params![serialized])?;
            sp.changes() > 0
        } else if Self::contains_serialized(database, table, &sp, serialized)? {
            false
        } else {
            sp.prepare_cached(&format!("INSERT INTO {database}.{table} (key) VALUES (?)"))?
                .execute(params![serialized])?;
            true
        };
        sp.commit()?;
        Ok(ret)
    }

    pub fn contains(&mut self, value: &S::TargetBorrowed) -> Result<bool, Error<S>> {
        // TODO
        let serialized = match S::serialize(value) {
            Ok(s) => s,
            Err(e) => return Err(Error::Serialize(e)),
        };
        Self::contains_serialized(
            &self.database,
            &self.table,
            &*self.connection.savepoint()?,
            serialized,
        )
    }

    fn contains_serialized(
        database: &Identifier,
        table: &Identifier,
        connection: &Connection,
        value: &S::BufferBorrowed,
    ) -> Result<bool, Error<S>> {
        // TODO
        Ok(connection
            .prepare_cached(&format!("SELECT 1 FROM {database}.{table} WHERE key = ?"))?
            .query_row(params![value], |_| Ok(()))
            .optional()?
            .is_some())
    }

    pub fn remove<Q>(&mut self, value: &S::TargetBorrowed) -> Result<bool, Error<S>> {
        // TODO
        let database = &self.database;
        let table = &self.table;
        let serialized = match S::serialize(value) {
            Ok(s) => s,
            Err(e) => return Err(Error::Serialize(e)),
        };

        let sp = self.connection.savepoint()?;
        let changes = sp
            .prepare_cached(&format!("DELETE FROM {database}.{table} WHERE key = ?"))?
            .execute(params![serialized])?;

        sp.commit()?;

        Ok(changes > 0)
    }

    pub fn clear(&mut self) -> Result<(), Error<S>> {
        let database = &self.database;
        let table = &self.nodes_table;
        let sp = self.connection.savepoint()?;
        sp.prepare_cached(&format!("DELETE FROM {database}.{table}"))?
            .execute([])?;
        sp.commit()?;
        Ok(())
    }

    pub fn first(&mut self) -> Result<Option<S::Target>, Error<S>> {
        // TODO
        let database = &self.database;
        let table = &self.table;

        let serialized: Option<S::Buffer> = self
            .connection
            .savepoint()?
            .prepare_cached(&format!(
                "SELECT key FROM {database}.{table} ORDER BY key ASC"
            ))?
            .query_row([], |row| row.get(0))
            .optional()?;

        match serialized.map(|s| S::deserialize(s)).transpose() {
            Ok(s) => Ok(s),
            Err(e) => Err(Error::Deserialize(e)),
        }
    }

    pub fn last(&mut self) -> Result<Option<S::Target>, Error<S>> {
        // TODO
        let database = &self.database;
        let table = &self.table;
        let serialized: Option<S::Buffer> = self
            .connection
            .savepoint()?
            .prepare_cached(&format!(
                "SELECT key FROM {database}.{table} ORDER BY key DESC"
            ))?
            .query_row([], |row| row.get(0))
            .optional()?;
        match serialized.map(|s| S::deserialize(s)).transpose() {
            Ok(s) => Ok(s),
            Err(e) => Err(Error::Deserialize(e)),
        }
    }

    pub fn len(&mut self) -> Result<u64, Error<S>> {
        let database = &self.database;
        let elements_table = &self.elements_table;
        Ok(self
            .connection
            .savepoint()?
            .prepare_cached(&format!("SELECT COUNT(*) FROM {database}.{elements_table}"))?
            .query_row([], |row| row.get(0))?)
    }

    pub fn iter(&mut self) -> Result<Iter<'db, S, Savepoint<'_>>, Error<S>> {
        // TODO
        Ok(Iter::new(
            self.connection.savepoint()?,
            self.database.clone(),
            self.table.clone(),
        )?)
    }
}

#[cfg(test)]
mod test;