microrm 0.6.3

Lightweight ORM using sqlite as a backend
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Schema specification types.
//!
//! The following terminology used in some types in this module:
//! - *domain*: one side of a relation, the "pointed-from" side for one-sided relations
//! - *range*: one side of a relation, the "pointed-to" side for one-sided relations
//! - *local*: the current side of a relation
//! - *remote*: the opposite side of a relation

use crate::{
    db::{StatementContext, StatementRow, Transaction},
    DBResult, Error,
};

use self::{
    datum::{Datum, DatumDiscriminator, DatumDiscriminatorRef, OwnedDatum},
    entity::{Entity, EntityPartList, EntityRef},
};

/// Types related to datums, or struct fields.
pub mod datum;
/// Types related to entities, or structs that can be serialized into/deserialized from the
/// database.
pub mod entity;

/// Types related to inter-entity relationships.
pub mod relation;

/// Types related to indexes.
pub mod index;

mod build;
mod check;
mod collect;
pub(crate) mod meta;
#[cfg(feature = "track_typesig")]
pub(crate) mod typesig;

/// Types and functionality related to schema migration.
pub mod migration;

mod detail;

// ----------------------------------------------------------------------
// API types
// ----------------------------------------------------------------------

/// Wrapper struct that holds both an EntityID and an Entity itself.
pub struct Stored<T: Entity> {
    id: T::ID,
    wrap: T,
}

impl<T: Entity> Stored<T> {
    pub(crate) fn new(id: T::ID, value: T) -> Self {
        Self { id, wrap: value }
    }

    /// Retrieve the entity ID of the stored entity.
    pub fn id(&self) -> T::ID {
        self.id
    }

    /// Consume the `Stored<>` wrapper and return the wrapped data.
    pub fn wrapped(self) -> T {
        self.wrap
    }
}

impl<T: Entity + std::fmt::Debug> std::fmt::Debug for Stored<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "Stored {{ id: {:?}, value: {:?} }}",
            self.id, self.wrap
        ))
    }
}

impl<T: Entity> AsRef<T> for Stored<T> {
    fn as_ref(&self) -> &T {
        &self.wrap
    }
}

impl<T: Entity> AsMut<T> for Stored<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.wrap
    }
}

impl<T: Entity> std::ops::Deref for Stored<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.wrap
    }
}

impl<T: Entity> std::ops::DerefMut for Stored<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.wrap
    }
}

impl<T: Entity + Clone> Clone for Stored<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            wrap: self.wrap.clone(),
        }
    }
}

impl<T: Entity> PartialEq for Stored<T> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<T: Entity + PartialEq> PartialEq<T> for Stored<T> {
    fn eq(&self, other: &T) -> bool {
        &self.wrap == other
    }
}

/// Wrapper struct that holds both an EntityID and an EntityRef.
pub struct Borrowed<'a, T: EntityRef<'a>> {
    id: <T::Entity as Entity>::ID,
    wrap: T,
}

impl<'a, T: EntityRef<'a>> Borrowed<'a, T> {
    pub(crate) fn new(id: <T::Entity as Entity>::ID, value: T) -> Self {
        Self { id, wrap: value }
    }

    /// Retrieve the entity ID of the stored entity.
    pub fn id(&self) -> <T::Entity as Entity>::ID {
        self.id
    }

    /// Consume the `Stored<>` wrapper and return the wrapped data.
    pub fn wrapped(self) -> T {
        self.wrap
    }
}

impl<'a, T: EntityRef<'a> + std::fmt::Debug> std::fmt::Debug for Borrowed<'a, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "Borrowed {{ id: {:?}, value: {:?} }}",
            self.id, self.wrap
        ))
    }
}

impl<'a, T: EntityRef<'a>> AsRef<T> for Borrowed<'a, T> {
    fn as_ref(&self) -> &T {
        &self.wrap
    }
}

impl<'a, T: EntityRef<'a>> AsMut<T> for Borrowed<'a, T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.wrap
    }
}

impl<'a, T: EntityRef<'a>> std::ops::Deref for Borrowed<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.wrap
    }
}

impl<'a, T: EntityRef<'a>> Clone for Borrowed<'a, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, T: EntityRef<'a>> Copy for Borrowed<'a, T> {}

impl<'a, T: EntityRef<'a>> PartialEq for Borrowed<'a, T> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<'a, T: EntityRef<'a> + PartialEq> PartialEq<T> for Borrowed<'a, T> {
    fn eq(&self, other: &T) -> bool {
        &self.wrap == other
    }
}

// ----------------------------------------------------------------------
// Entity field types
// ----------------------------------------------------------------------

/// Stores an arbitrary Rust data type as serialized JSON in a string field.
#[derive(Clone)]
pub struct Serialized<T: serde::Serialize + serde::de::DeserializeOwned + Clone> {
    wrapped: T,
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + Clone> Serialized<T> {
    /// Returns the object stored inside this representational wrapper.
    pub fn wrapped(self) -> T {
        self.wrapped
    }
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + Default + Clone> Default
    for Serialized<T>
{
    fn default() -> Self {
        Self {
            wrapped: T::default(),
        }
    }
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone> std::fmt::Debug
    for Serialized<T>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <T as std::fmt::Debug>::fmt(&self.wrapped, f)
    }
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + Clone> From<T> for Serialized<T> {
    fn from(value: T) -> Self {
        Self { wrapped: value }
    }
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + Clone> AsRef<T> for Serialized<T> {
    fn as_ref(&self) -> &T {
        &self.wrapped
    }
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + Clone> AsMut<T> for Serialized<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.wrapped
    }
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + Clone> std::ops::Deref for Serialized<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.wrapped
    }
}

impl<T: serde::Serialize + serde::de::DeserializeOwned + Clone> std::ops::DerefMut
    for Serialized<T>
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.wrapped
    }
}

impl<T: 'static + serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone> Datum
    for Serialized<T>
{
    fn sql_type() -> &'static str {
        "text"
    }

    fn bind_to(&self, stmt: &mut StatementContext, index: i32) -> DBResult<()> {
        let json = std::pin::Pin::new(
            serde_json::to_string(&self.wrapped).expect("couldn't serialize object into JSON"),
        );

        let r = <&str as Datum>::bind_to(&&*json.as_ref(), stmt, index);

        // transfer ownership so that the data is still around for later
        stmt.transfer(json);

        r
    }

    fn build_from(
        rdata: relation::RelationData,
        stmt: &mut StatementRow,
        index: &mut i32,
    ) -> DBResult<Self>
    where
        Self: Sized,
    {
        let s = <&str as Datum>::build_from(rdata, stmt, index)?;

        let d = serde_json::from_str::<T>(s).map_err(Error::JSON)?;

        Ok(Self { wrapped: d })
    }

    fn accept_discriminator(d: &mut impl DatumDiscriminator)
    where
        Self: Sized,
    {
        d.visit_serialized::<T>();
    }

    fn accept_discriminator_ref(&self, d: &mut impl DatumDiscriminatorRef)
    where
        Self: Sized,
    {
        d.visit_serialized::<T>(&self.wrapped);
    }
}

impl<T: 'static + serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone>
    OwnedDatum for Serialized<T>
{
    type RefData<'a> = &'a Self;
    fn as_ref(&self) -> Self::RefData<'_> {
        self
    }
}

/// Helper trait to make working with [`Serialized`] fields a little bit nicer.
pub trait Serializable:
    serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone
{
    /// Wrap an eligible object into a [`Serialized`] version of itself.
    fn into_serialized(self) -> Serialized<Self>
    where
        Self: Sized;
}

impl<T: 'static + serde::Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone>
    Serializable for T
{
    fn into_serialized(self) -> Serialized<Self>
    where
        Self: Sized,
    {
        Serialized { wrapped: self }
    }
}

// ----------------------------------------------------------------------
// Database specification types
// ----------------------------------------------------------------------

/// Table with EntityID-based lookup.
pub struct IDMap<T: Entity> {
    _ghost: std::marker::PhantomData<T>,
}

impl<T: Entity> Clone for IDMap<T> {
    fn clone(&self) -> Self {
        Self {
            _ghost: Default::default(),
        }
    }
}

impl<E: Entity> DatabaseItem for IDMap<E> {
    fn accept_item_visitor(visitor: &mut impl DatabaseItemVisitor) {
        visitor.visit_idmap::<E>();
    }

    fn build(_: BuildSeal) -> Self
    where
        Self: Sized,
    {
        Self {
            _ghost: std::marker::PhantomData,
        }
    }

    type Subitems = ();
}

#[derive(Clone, Copy)]
pub(crate) struct Sealed;

/// Sealing type for [`DatabaseItem::build`]. Not constructible outside of `microrm`.
#[derive(Clone, Copy)]
pub struct BuildSeal(Sealed);
impl BuildSeal {
    pub(crate) fn new() -> Self {
        Self(Sealed)
    }
}

/// Represents a logical item in a database schema, be it an index, table, or logical grouping.
pub trait DatabaseItem {
    /// Accept an entity visitor for (local) entity discovery.
    fn accept_item_visitor(visitor: &mut impl DatabaseItemVisitor);

    /// Build an instance of this DatabaseItem.
    fn build(_: BuildSeal) -> Self
    where
        Self: Sized;

    /// Ordered list of DatabaseItems that are direct children of this item.
    type Subitems: DatabaseItemList;
}

/// A special sentinel DatabaseItem for DatabaseItemList.
#[derive(Default, Debug, Clone, Copy)]
pub struct SentinelDatabaseItem;
impl DatabaseItem for SentinelDatabaseItem {
    fn accept_item_visitor(_visitor: &mut impl DatabaseItemVisitor) {}

    fn build(_: BuildSeal) -> Self
    where
        Self: Sized,
    {
        Self
    }

    type Subitems = ();
}

/// Representation of a list of DatabaseItems.
pub trait DatabaseItemList {
    /// Head of the list.
    type Head: DatabaseItem;
    /// The rest of the list.
    type Tail: DatabaseItemList;
    /// Whether this is an empty list or not.
    const EMPTY: bool = false;
}

impl DatabaseItemList for () {
    type Head = SentinelDatabaseItem;
    type Tail = ();
    const EMPTY: bool = true;
}

impl<DI0: DatabaseItem> DatabaseItemList for (DI0,) {
    type Head = DI0;
    type Tail = ();
}

/// Visitor trait for iterating across the types in a [`Schema`] tree.
pub trait DatabaseItemVisitor {
    /// Visit an `IDMap<T>` type.
    fn visit_idmap<T: Entity>(&mut self)
    where
        Self: Sized;
    /// Visit an `Index<bool, T, PL>` type.
    fn visit_index<const UNIQUE: bool, T: Entity, PL: EntityPartList<Entity = T>>(&mut self)
    where
        Self: Sized;
}

/// A root structure for the database specification graph.
pub trait Schema: 'static + DatabaseItem {
    /// Install this schema into a database
    fn install(&self, txn: &mut Transaction) -> DBResult<()>
    where
        Self: Sized,
    {
        let schema = build::generate_from_schema::<Self>();
        match schema.check(txn) {
            // schema checks out
            Some(true) => {
                log::trace!("Schema signature match!");
                check::check_schema::<Self>(txn)
            },
            // schema doesn't match
            Some(false) => Err(Error::IncompatibleSchema),
            // no schema found
            None => {
                log::trace!("No schema found. Initializing schema...");
                schema.create(txn)
            },
        }
    }

    /// Create a clone of the current schema object.
    ///
    /// More generally, [`DatabaseItem`] is not Clone, but [`Schema`] must be, so the typical
    /// implementation does not work here. But since `build` is a sealed method, the implementation
    /// must be in the `microrm` crate; since `Clone` is a foreign trait it cannot be implemented
    /// on all `Schema` using Rust's current type system.
    fn clone_schema(&self) -> Self
    where
        Self: Sized,
    {
        Self::build(BuildSeal::new())
    }

    /// The printed name used to represent this schema if it is ever mentioned in e.g. logs.
    const NAME: Option<&'static str> = None;
}

impl crate::ConnectionPool {
    /// Open a SQLite connection to a given URI, using a given schema.
    pub fn open<S: Schema>(
        config: impl Into<crate::db::ConnectionPoolConfig>,
    ) -> DBResult<(Self, S)> {
        let pool = Self::new(config)?;
        let schema = S::build(BuildSeal::new());

        let mut txn = pool.start()?;
        schema.install(&mut txn)?;
        txn.commit()?;

        Ok((pool, schema))
    }
}