day-persistence 0.4.1

SQLite persistence for the Day observable model.
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
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! The real driver, on real files: rows survive a reopen, hand-made tables coexist, backups
//! open clean, and lightweight migration closes column gaps without losing data.

use day_model::Op;
use day_persistence::{Model, ModelContainer, Sqlite, schema};
use day_reactive::Binding;

#[derive(Model, Clone, Default, PartialEq, Debug)]
#[model(table = "notes")]
struct Note {
    #[model(id)]
    id: u32,
    title: String,
    pinned: bool,
}

/// A fresh path under the OS temp dir; the test owns it for its lifetime.
fn temp_db(name: &str) -> std::path::PathBuf {
    let path = std::env::temp_dir().join(format!(
        "day-persistence-{}-{}.db",
        std::process::id(),
        name
    ));
    let _ = std::fs::remove_file(&path);
    let _ = std::fs::remove_file(path.with_extension("sqlite-wal"));
    let _ = std::fs::remove_file(path.with_extension("sqlite-shm"));
    path
}

#[test]
fn rows_survive_a_reopen() {
    let path = temp_db("reopen");
    {
        let container = ModelContainer::open(Sqlite::at(&path), schema![Note]).expect("open");
        let store = container.cache::<Note>();
        store.restructure("add", Op::Insert, 1, |v| {
            v.push(Note {
                id: 1,
                title: "first".into(),
                pinned: false,
            });
        });
        store.restructure("add", Op::Insert, 2, |v| {
            v.push(Note {
                id: 2,
                title: "second".into(),
                pinned: true,
            });
        });
        store.elem(1).title().write("first, edited".into());
        store.restructure("remove", Op::Delete, 2, |v| {
            v.remove(2);
        });
        container.save().expect("save");
    }
    {
        let container = ModelContainer::open(Sqlite::at(&path), schema![Note]).expect("reopen");
        let survivors = container.query::<Note>().live();
        assert_eq!(survivors.ids(), [1]);
        assert_eq!(
            container.get::<Note>(1u32).expect("faults").title().peek(),
            "first, edited"
        );
    }
    let _ = std::fs::remove_file(&path);
}

#[test]
fn hand_made_tables_coexist_with_days() {
    let path = temp_db("coexist");
    {
        let conn = rusqlite::Connection::open(&path).expect("raw open");
        conn.execute_batch(
            "CREATE TABLE app_journal (entry TEXT); INSERT INTO app_journal VALUES ('mine');",
        )
        .expect("hand-made table");
    }
    {
        let container = ModelContainer::open(Sqlite::at(&path), schema![Note]).expect("open");
        let store = container.cache::<Note>();
        store.restructure("add", Op::Insert, 1, |v| {
            v.push(Note {
                id: 1,
                title: "days".into(),
                pinned: false,
            });
        });
        container.save().expect("save");
        container.checkpoint().expect("checkpoint");
    }
    {
        let conn = rusqlite::Connection::open(&path).expect("raw reopen");
        let entry: String = conn
            .query_row("SELECT entry FROM app_journal", [], |r| r.get(0))
            .expect("hand-made row untouched");
        assert_eq!(entry, "mine");
        let title: String = conn
            .query_row("SELECT title FROM notes WHERE id = 1", [], |r| r.get(0))
            .expect("day row present");
        assert_eq!(title, "days");
    }
    let _ = std::fs::remove_file(&path);
}

#[test]
fn a_backup_taken_mid_write_opens_clean() {
    let path = temp_db("backup-src");
    let backup = temp_db("backup-dst");
    let container = ModelContainer::open(Sqlite::at(&path), schema![Note]).expect("open");
    let store = container.cache::<Note>();
    store.restructure("add", Op::Insert, 1, |v| {
        v.push(Note {
            id: 1,
            title: "saved".into(),
            pinned: false,
        });
    });
    container.save().expect("save");
    // Edits still pending when the backup is asked for: backup_to flushes them first, so the
    // snapshot is transactionally consistent and complete.
    container.set_autosave(false);
    store.elem(1).title().write("saved, then edited".into());
    container.backup_to(&backup).expect("backup");

    let restored = ModelContainer::open(Sqlite::at(&backup), schema![Note]).expect("open backup");
    assert_eq!(
        restored.get::<Note>(1u32).expect("faults").title().peek(),
        "saved, then edited"
    );
    assert_eq!(
        restored.integrity_check().expect("check"),
        Vec::<String>::new()
    );
    let _ = std::fs::remove_file(&path);
    let _ = std::fs::remove_file(&backup);
}

#[test]
fn an_added_column_backfills_and_a_dropped_one_goes() {
    // The same table, declared twice: yesterday's shape and today's.
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "tasks")]
    struct TaskV1 {
        #[model(id)]
        id: u32,
        title: String,
        legacy: String,
    }
    #[derive(Model, Clone, Default, PartialEq, Debug)]
    #[model(table = "tasks")]
    struct TaskV2 {
        #[model(id)]
        id: u32,
        title: String,
        count: i64,
    }

    let path = temp_db("migrate");
    {
        let container = ModelContainer::open(Sqlite::at(&path), schema![TaskV1]).expect("v1");
        container
            .cache::<TaskV1>()
            .restructure("add", Op::Insert, 1, |v| {
                v.push(TaskV1 {
                    id: 1,
                    title: "carried".into(),
                    legacy: "gone tomorrow".into(),
                });
            });
        container.save().expect("save");
        container.checkpoint().expect("checkpoint");
    }
    {
        let container = ModelContainer::open(Sqlite::at(&path), schema![TaskV2]).expect("v2");
        let row = container.get::<TaskV2>(1u32).expect("faults");
        assert_eq!(row.title().peek(), "carried");
        assert_eq!(row.count().peek(), 0, "added column backfilled");
        container.checkpoint().expect("checkpoint");
    }
    {
        let conn = rusqlite::Connection::open(&path).expect("raw");
        let cols: Vec<String> = conn
            .prepare("PRAGMA table_info(tasks)")
            .unwrap()
            .query_map([], |r| r.get::<_, String>(1))
            .unwrap()
            .map(|c| c.unwrap())
            .collect();
        assert_eq!(
            cols,
            ["id", "title", "count"],
            "legacy dropped, count added"
        );
    }
    let _ = std::fs::remove_file(&path);
}

#[test]
fn the_created_table_is_strict_and_readable_by_any_tool() {
    let path = temp_db("ddl");
    {
        let _c = ModelContainer::open(Sqlite::at(&path), schema![Note]).expect("open");
    }
    let conn = rusqlite::Connection::open(&path).expect("raw");
    let ddl: String = conn
        .query_row(
            "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'notes'",
            [],
            |r| r.get(0),
        )
        .expect("schema row");
    assert!(ddl.ends_with("STRICT"), "{ddl}");
    let _ = std::fs::remove_file(&path);
}

#[test]
fn size_and_vacuum_report_something_sane() {
    let path = temp_db("size");
    let container = ModelContainer::open(Sqlite::at(&path), schema![Note]).expect("open");
    container
        .cache::<Note>()
        .restructure("add", Op::Insert, 1, |v| {
            v.push(Note {
                id: 1,
                title: "x".repeat(4096),
                pinned: false,
            });
        });
    container.save().expect("save");
    container.vacuum().expect("vacuum");
    assert!(container.size_bytes().expect("size") > 0);
    let _ = std::fs::remove_file(&path);
}

/// `trace_sql` rides the engine's own trace: migrations, the autosave fold's statements, and
/// query `SELECT`s all land in the sink, with bound parameters expanded by SQLite itself.
#[test]
fn trace_sql_logs_every_statement_the_engine_runs() {
    use std::cell::RefCell;
    use std::rc::Rc;

    #[derive(Model, Clone, Default, PartialEq)]
    #[model(table = "traced_notes")]
    struct TracedNote {
        #[model(id)]
        id: u32,
        body: String,
    }

    let seen: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
    let sink = seen.clone();
    let driver = Sqlite::memory().trace_sql(move |sql| sink.borrow_mut().push(sql.to_string()));
    let container = ModelContainer::open(driver, schema![TracedNote]).expect("open");
    let store = container.cache::<TracedNote>();
    store.update("seed", |k| {
        k.push(TracedNote {
            id: 1,
            body: "rain later".into(),
        });
    });
    container.save().expect("flush");

    let log = seen.borrow();
    assert!(
        log.iter()
            .any(|s| s.contains("CREATE TABLE") && s.contains("traced_notes")),
        "migration logged: {log:?}"
    );
    assert!(
        log.iter()
            .any(|s| s.contains("INSERT INTO \"traced_notes\"") && s.contains("'rain later'")),
        "flush logged with parameters expanded: {log:?}"
    );
}

/// Work the engine does inside a statement (a trigger body, a foreign-key action) is
/// reported as a `-- …` comment, never as the firing statement again: an insert into a
/// text-indexed table is one statement line, and a parent's `DELETE` is one line however
/// many rows `ON DELETE CASCADE` takes with it.
#[test]
fn trace_sql_reports_engine_frames_as_comments() {
    use std::cell::RefCell;
    use std::rc::Rc;

    #[derive(Model, Clone, Default, PartialEq)]
    #[model(table = "traced_albums", fts("title"))]
    struct TracedAlbum {
        #[model(id)]
        id: u32,
        title: String,
        #[model(relation(target = TracedPhoto, inverse = "album", delete = "cascade"))]
        photos: day_persistence::Many<TracedPhoto>,
    }

    #[derive(Model, Clone, Default, PartialEq)]
    #[model(table = "traced_photos")]
    struct TracedPhoto {
        #[model(id)]
        id: u32,
        album: day_persistence::One<TracedAlbum>,
    }

    let seen: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
    let sink = seen.clone();
    let driver = Sqlite::memory().trace_sql(move |sql| sink.borrow_mut().push(sql.to_string()));
    let container = ModelContainer::open(driver, schema![TracedAlbum, TracedPhoto]).expect("open");
    container.set_autosave(false);
    seen.borrow_mut().clear();

    container.insert(TracedAlbum {
        id: 1,
        title: "kyoto".into(),
        ..Default::default()
    });
    container.save().expect("flush");
    {
        let log = seen.borrow();
        let inserts = log
            .iter()
            .filter(|s| s.starts_with("INSERT INTO \"traced_albums\""))
            .count();
        assert_eq!(
            inserts, 1,
            "one upsert for one row, not one per trigger: {log:?}"
        );
        assert!(
            log.iter()
                .any(|s| s.starts_with("-- TRIGGER traced_albums_fts_ai")),
            "the FTS insert trigger is reported as its comment: {log:?}"
        );
    }

    for id in 1..=3 {
        container.insert(TracedPhoto {
            id,
            album: day_persistence::One::to(1u32),
        });
    }
    container.save().expect("flush photos");
    // Delete through raw SQL so the engine alone cascades, with no in-process pipeline to
    // issue child deletes of its own.
    seen.borrow_mut().clear();
    container
        .try_with_connection(|conn| {
            conn.execute(
                "DELETE FROM \"traced_albums\" WHERE \"id\" = ?",
                &[day_persistence::Value::Int(1)],
            )
            .map(|_| ())
        })
        .expect("raw delete");
    let log = seen.borrow();
    let deletes = log
        .iter()
        .filter(|s| s.starts_with("DELETE FROM \"traced_albums\""))
        .count();
    assert_eq!(
        deletes, 1,
        "the parent DELETE once, not once per cascaded row: {log:?}"
    );
    // The engine runs one action program per parent row it deletes (that program takes all
    // three photos), so the cascade shows as a frame, never as the DELETE again.
    assert!(
        log.iter().any(|s| s == "-- foreign-key action"),
        "the cascade is reported as a foreign-key-action frame: {log:?}"
    );
    // The count below is traced too, so the sink must be free to take the lock.
    drop(log);
    // Statements prepared afresh (`query_named` does not cache) can reuse the address of the
    // one just finalized; each is still its own line, never mistaken for a frame of the last.
    seen.borrow_mut().clear();
    for n in 1..=3 {
        container
            .try_with_connection(|conn| {
                conn.query_named(&format!("SELECT {n} AS fixture"), &[], &mut |_, _| {})
            })
            .expect("fresh statement");
    }
    let fresh: Vec<String> = seen
        .borrow()
        .iter()
        .filter(|s| s.starts_with("SELECT"))
        .cloned()
        .collect();
    assert_eq!(
        fresh,
        [
            "SELECT 1 AS fixture",
            "SELECT 2 AS fixture",
            "SELECT 3 AS fixture"
        ],
        "{:?}",
        seen.borrow()
    );
    let mut left = -1;
    container
        .try_with_connection(|conn| {
            conn.query("SELECT COUNT(*) FROM \"traced_photos\"", &[], &mut |row| {
                left = row.get(0).as_int().unwrap_or(-1);
            })
        })
        .expect("count");
    assert_eq!(left, 0, "the engine did cascade");
}