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
// IP: in-progress

use std::marker::PhantomData;

use crate::prelude::*;
use crate::query::Insertable;
use crate::schema::{
    self,
    build::{generate_from_schema, generate_single_entity_table, GeneratedSchema},
    datum::Datum,
    entity::{Entity, EntityID},
    relation::{RelationDomain, RelationExt, RelationMap, RelationRange},
    BuildSeal, DatabaseItem, Schema, SentinelDatabaseItem,
};
use crate::{DBResult, Error, IDMap, Transaction};

mod ip;
use ip::*;

/// Trait to mark types that can be automatically migrated.
///
/// `migrate_datum` is generally equivalent to cloning the datum.
pub trait MigratableDatum<From: Datum>: Datum {
    /// Create a copy of a datum.
    fn migrate_datum(from: &From) -> DBResult<Self>
    where
        Self: Sized;
}

macro_rules! migrate_datum_impl_clone {
    ($($ty:path),+) => {
        $(
        impl MigratableDatum<$ty> for $ty {
            fn migrate_datum(from: &$ty) -> DBResult<Self> where Self: Sized {
                Ok(from.clone())
            }
        }
        )*
    }
}

macro_rules! migrate_datum_impl_copy {
    ($($ty:path),+) => {
        $(
        impl MigratableDatum<$ty> for $ty {
            fn migrate_datum(from: &$ty) -> DBResult<Self> where Self: Sized {
                Ok(*from)
            }
        }
        )*
    }
}

migrate_datum_impl_clone!(String, Vec<u8>);
migrate_datum_impl_copy!(bool, isize, usize, f32, f64, u64, i64);

impl<T: MigratableDatum<T>> MigratableDatum<Option<T>> for Option<T> {
    fn migrate_datum(from: &Option<T>) -> DBResult<Self>
    where
        Self: Sized,
    {
        from.as_ref().map(T::migrate_datum).transpose()
    }
}

#[cfg(feature = "time")]
const _: () = {
    use crate::DBResult;
    migrate_datum_impl_copy!(time::OffsetDateTime);
};

impl<R0: Relation, R1: Relation> MigratableDatum<RelationDomain<R0>> for RelationDomain<R1> {
    fn migrate_datum(_from: &RelationDomain<R0>) -> DBResult<Self>
    where
        Self: Sized,
    {
        R0::try_coerce::<R1>()?;
        Ok(RelationDomain::<R1>::default())
    }
}

impl<R0: Relation, R1: Relation> MigratableDatum<RelationRange<R0>> for RelationRange<R1> {
    fn migrate_datum(_from: &RelationRange<R0>) -> DBResult<Self>
    where
        Self: Sized,
    {
        R0::try_coerce::<R1>()?;
        Ok(RelationRange::<R1>::default())
    }
}

impl<E0: Entity, E1: Entity> MigratableDatum<RelationMap<E0>> for RelationMap<E1> {
    fn migrate_datum(_from: &RelationMap<E0>) -> DBResult<Self>
    where
        Self: Sized,
    {
        if E0::entity_name() == E1::entity_name() {
            Ok(RelationMap::default())
        } else {
            panic!(
                "Cannot coerce a migration of a map between {} and {}",
                std::any::type_name::<E0>(),
                std::any::type_name::<E1>()
            );
        }
    }
}

/// Trait describing a simple entity-to-entity transformation, to better make use of the
/// scaffolding in [`MigrationContext::migrate_entity`].
pub trait MigratableEntity<From: Entity>: 'static + Entity {
    /// Perform migration.
    fn migrate(from: &From) -> DBResult<Option<Self>>
    where
        Self: Sized;
}

impl<T: 'static + Entity + Clone> MigratableEntity<T> for T {
    fn migrate(from: &T) -> DBResult<Option<Self>>
    where
        Self: Sized,
    {
        Ok(Some(from.clone()))
    }
}

/// Context for the migration of a `DatabaseItem`.
pub struct MigrationContext<'a> {
    txn: &'a mut Transaction,
    from_gen: GeneratedSchema,
    into_gen: GeneratedSchema,
    in_progress: Vec<(&'static str, &'static str)>,
}

impl MigrationContext<'_> {
    /// Mark the given entity as in-progress, scheduling the entity with the same name for
    /// deletion.
    pub fn in_progress<E: Entity>(&mut self) -> DBResult<MigrateMap<E>> {
        // check that this is part of the new schema
        let Some(_query) = self.into_gen.table_queries().get(E::entity_name()) else {
            return Err(Error::LogicError(
                "tried to create in-progress table for entity that not in new schema",
            ));
        };

        let table_sql = generate_single_entity_table::<IPEntity<E>>();

        self.txn.lease().execute_raw_sql(table_sql.as_str())?;

        self.in_progress
            .push((E::entity_name(), IPEntity::<E>::entity_name()));

        Ok(MigrateMap::<E> {
            ..Default::default()
        })
    }

    /// Migrate an entity between two forms via [`MigratableEntity`].
    pub fn migrate_entity<E0: Entity, E1: MigratableEntity<E0>>(
        &mut self,
    ) -> DBResult<MigrateMap<E1>> {
        log::trace!("migrating entity via MigratableEntity");
        let mm = self.in_progress::<E1>()?;

        for e0 in IDMap::<E0>::build(BuildSeal::new()).get(self.txn)? {
            log::trace!("\tprocessing entity with ID {:?}", e0.id());
            let Some(e1) = <E1 as MigratableEntity<E0>>::migrate(e0.as_ref())? else {
                continue;
            };
            mm.insert_matching(self.txn, e1, e0)?;
        }

        Ok(mm)
    }

    /// Retrieve the Transaction.
    pub fn txn(&mut self) -> &mut Transaction {
        self.txn
    }

    fn finish(self) -> DBResult<()> {
        log::trace!("in progress: {:?}", self.in_progress);

        // handle each in-progress table
        for (basename, ipname) in self.in_progress {
            // first drop the old one
            self.txn
                .lease()
                .execute_raw_sql(format!("DROP TABLE {basename};"))?;
            // then put the new one in place
            self.txn
                .lease()
                .execute_raw_sql(format!("ALTER TABLE `{ipname}` RENAME TO `{basename}`"))?;
            // recreate any relevant indices
            let Some(indices) = self.into_gen.related_indices().get(basename) else {
                continue;
            };
            for iname in indices {
                self.txn
                    .lease()
                    .execute_raw_sql(&self.into_gen.index_queries()[iname])?;
            }
        }

        log::trace!("looking for new indices!");
        log::trace!("from_gen indices: {:?}", self.from_gen.index_queries());
        log::trace!("into_gen indices: {:?}", self.into_gen.index_queries());

        // create any new indices that the migration added
        for (iname, sql) in self.into_gen.index_queries().iter() {
            if self.from_gen.index_queries().contains_key(iname) {
                continue;
            }

            self.txn.lease().execute_raw_sql(sql)?;
        }

        Ok(())
    }
}

/// Describes a database item (entity, index, etc) transformation between two schemata.
pub trait MigratableItem<From: DatabaseItem>: 'static + DatabaseItem {
    /// Run the migration logic.
    fn run_migration(from: &From, ctx: &mut MigrationContext) -> DBResult<()>
    where
        Self: Sized;
}

impl<T: 'static + DatabaseItem> MigratableItem<super::SentinelDatabaseItem> for T {
    fn run_migration(_: &super::SentinelDatabaseItem, _ctx: &mut MigrationContext) -> DBResult<()>
    where
        Self: Sized,
    {
        unreachable!()
    }
}

/// [`IDMap`] equivalent for in-progress migrations.
pub struct MigrateMap<OE: Entity>(PhantomData<OE>);

impl<OE: Entity> Default for MigrateMap<OE> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

impl<OE: Entity> Insertable<OE> for MigrateMap<OE> {
    fn insert(&self, txn: &mut Transaction, value: OE) -> DBResult<OE::ID> {
        let id =
            IDMap::<IPEntity<OE>>::insert(&IDMap::build(BuildSeal::new()), txn, IPEntity(value))?;
        Ok(<OE::ID>::from_raw(id.0))
    }
    fn insert_ref(&self, txn: &mut Transaction, value: OE::ERef<'_>) -> DBResult<OE::ID> {
        let id = IDMap::<IPEntity<OE>>::insert_ref(
            &IDMap::build(BuildSeal::new()),
            txn,
            IPERef::new(value),
        )?;
        Ok(<OE::ID>::from_raw(id.0))
    }
    fn insert_and_return(&self, txn: &mut Transaction, value: OE) -> DBResult<crate::Stored<OE>> {
        use crate::IDMap;
        let rval = IDMap::<IPEntity<OE>>::insert_and_return(
            &IDMap::build(BuildSeal::new()),
            txn,
            IPEntity(value),
        )?;
        let id = rval.id();
        Ok(crate::Stored::new(
            <OE::ID>::from_raw(id.into_raw()),
            rval.wrapped().0,
        ))
    }
}

impl<OE: Entity> MigrateMap<OE> {
    /// Insert an entity into the migration map that possesses the same ID as an 'old' entity.
    pub fn insert_matching<ME: Entity>(
        &self,
        txn: &mut Transaction,
        value: OE,
        old_value: crate::Stored<ME>,
    ) -> DBResult<()> {
        let id = old_value.id().into_raw();
        crate::query::base_queries::insert_exact(txn, &IPEntity(value), IPEntityID::from_raw(id))?;
        Ok(())
    }
}

impl Schema for super::SentinelDatabaseItem {}

/// Represents a list of [`Schema`] types.
pub trait SchemaList {
    /// Head element of the list.
    type Head: Schema + MigratableItem<<Self::Tail as SchemaList>::Head>;
    /// Tail of the list.
    type Tail: SchemaList;
    /// If this is an empty list or not, used for termination.
    const EMPTY: bool = false;
}

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

impl<S0: Schema> SchemaList for (S0,)
where
    S0: MigratableItem<SentinelDatabaseItem>,
{
    type Head = S0;
    type Tail = ();
}

fn migration_helper<A: SchemaList>(txn: &mut Transaction) -> DBResult<()> {
    if A::EMPTY {
        return Err(Error::IncompatibleSchema);
    }

    let built = generate_from_schema::<A::Head>();
    log::trace!(
        "checking if head schema ({}) is present",
        A::Head::NAME.unwrap_or("<anonymous>")
    );
    match built.check(txn) {
        Some(true) => {
            log::trace!("head schema present, nothing to do");
            Ok(())
        },
        Some(false) => {
            migration_helper::<A::Tail>(txn)?;

            // migrate from (A::Tail::Head) to A::Head
            type MigrateTo<A> = <A as SchemaList>::Head;
            type MigrateFrom<A> = <<A as SchemaList>::Tail as SchemaList>::Head;

            log::trace!(
                "running migration: {} -> {}",
                std::any::type_name::<MigrateFrom<A>>(),
                std::any::type_name::<MigrateTo<A>>(),
            );

            // check schema beforehand for consistency
            schema::check::check_schema::<MigrateFrom<A>>(txn)?;

            log::trace!("schema check succeeded");

            let mut context = MigrationContext {
                txn,
                into_gen: built.clone(),
                from_gen: generate_from_schema::<MigrateFrom<A>>(),
                in_progress: vec![],
            };

            let prev_schema = MigrateFrom::<A>::build(BuildSeal::new());

            <MigrateTo<A> as MigratableItem<MigrateFrom<A>>>::run_migration(
                &prev_schema,
                &mut context,
            )?;

            context.finish()?;

            // update metadata to match new schema
            built.update_metadata(txn)?;

            // check schema afterwards for consistency
            schema::check::check_schema::<A::Head>(txn)?;

            Ok(())
        },
        None => Err(Error::EmptyDatabase),
    }
}

/// Run a series of migrations as needed to migrate a connection to the most recent schema.
///
/// The schemata should be given as a `(Oldest, Old, New)` tuple.
pub fn run_migration<A: SchemaList>(pool: &crate::ConnectionPool) -> DBResult<A::Head> {
    // this PRAGMA has no effect during a transaction, so we need a *lease* for it.
    let mut lease = pool.acquire()?;
    lease.execute_raw_sql("PRAGMA foreign_keys=OFF")?;
    drop(lease);

    // find the earliest matching schema, and then run each migration in sequence if needed
    let mut txn = pool.start()?;
    migration_helper::<A>(&mut txn)?;

    // check that foreign keys are still satisfied
    let r = txn.lease().check_foreign_keys()?;

    if !r.is_empty() {
        return Err(Error::ConsistencyError(format!(
            "foreign key constraints not satisfied after migration: {}",
            r.join(",")
        )));
    }

    txn.commit()?;

    let mut lease = pool.acquire()?;
    lease.execute_raw_sql("PRAGMA foreign_keys=ON")?;
    drop(lease);

    // return the new schema
    Ok(A::Head::build(BuildSeal::new()))
}