tea-session-sqlite 0.1.0

Durable SQLite session store for tea-rs
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
//! Initial `SQLite` schema installation and validation.

use rusqlite::{Connection, OptionalExtension as _, TransactionBehavior};

/// The schema version written by this crate.
pub const CURRENT_SCHEMA_VERSION: u32 = 1;

const SCHEMA_VERSION_TABLE: TableSpec = TableSpec {
    name: "schema_version",
    columns: &[ColumnSpec::primary_key("version", "INTEGER", 1)],
};

const REQUIRED_TABLES: &[TableSpec] = &[
    SCHEMA_VERSION_TABLE,
    TableSpec {
        name: "records",
        columns: &[
            ColumnSpec::not_null_primary_key("session_id", "TEXT", 1),
            ColumnSpec::not_null_primary_key("sequence", "INTEGER", 2),
            ColumnSpec::not_null("record_id", "TEXT"),
            ColumnSpec::not_null("envelope", "TEXT"),
        ],
    },
    TableSpec {
        name: "approval_artifacts",
        columns: &[
            ColumnSpec::not_null_primary_key("session_id", "TEXT", 1),
            ColumnSpec::not_null_primary_key("record_id", "TEXT", 2),
            ColumnSpec::not_null("envelope", "TEXT"),
        ],
    },
    TableSpec {
        name: "grant_journal",
        columns: &[
            ColumnSpec::not_null_primary_key("session_id", "TEXT", 1),
            ColumnSpec::not_null_primary_key("seq", "INTEGER", 2),
            ColumnSpec::not_null("grant_id", "TEXT"),
            ColumnSpec::not_null("envelope", "TEXT"),
        ],
    },
    TableSpec {
        name: "active_grants",
        columns: &[
            ColumnSpec::primary_key("grant_id", "TEXT", 1),
            ColumnSpec::not_null("session_id", "TEXT"),
            ColumnSpec::not_null("actor_id", "TEXT"),
            ColumnSpec::not_null("grant_json", "TEXT"),
            ColumnSpec::not_null("revoked", "INTEGER"),
        ],
    },
    TableSpec {
        name: "session_catalog",
        columns: &[
            ColumnSpec::primary_key("session_id", "TEXT", 1),
            ColumnSpec::nullable("display_name", "TEXT"),
        ],
    },
];

const REQUIRED_INDEXES: &[IndexSpec] = &[
    IndexSpec {
        name: "idx_records_record_id",
        table: "records",
        unique: true,
        columns: &["session_id", "record_id"],
    },
    IndexSpec {
        name: "idx_grant_journal_grant_id",
        table: "grant_journal",
        unique: false,
        columns: &["grant_id"],
    },
    IndexSpec {
        name: "idx_active_grants_actor_revoked",
        table: "active_grants",
        unique: false,
        columns: &["actor_id", "revoked", "grant_id"],
    },
];

/// Installs the complete initial schema or verifies an existing published layout.
///
/// Pre-0.1 development schemas are intentionally not migrated. Since some of
/// them also used version 1, both the version row and the complete layout must
/// match before the database is accepted.
pub(crate) fn ensure_schema(conn: &mut Connection) -> Result<(), rusqlite::Error> {
    let transaction = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
    if !schema_object_exists(&transaction, "table", "schema_version", "schema_version")? {
        if has_user_schema_objects(&transaction)? {
            return Err(schema_error(
                "incompatible SQLite schema: schema_version is missing from a non-empty database",
            ));
        }
        create_schema(&transaction)?;
    }
    validate_schema(&transaction)?;
    transaction.commit()
}

fn create_schema(conn: &Connection) -> Result<(), rusqlite::Error> {
    conn.execute_batch(
        "CREATE TABLE schema_version (
            version INTEGER PRIMARY KEY
        );
        CREATE TABLE records (
            session_id TEXT NOT NULL,
            sequence INTEGER NOT NULL,
            record_id TEXT NOT NULL,
            envelope TEXT NOT NULL,
            PRIMARY KEY (session_id, sequence)
        );
        CREATE UNIQUE INDEX idx_records_record_id
            ON records (session_id, record_id);
        CREATE TABLE approval_artifacts (
            session_id TEXT NOT NULL,
            record_id TEXT NOT NULL,
            envelope TEXT NOT NULL,
            PRIMARY KEY (session_id, record_id)
        );
        CREATE TABLE grant_journal (
            session_id TEXT NOT NULL,
            seq INTEGER NOT NULL,
            grant_id TEXT NOT NULL,
            envelope TEXT NOT NULL,
            PRIMARY KEY (session_id, seq)
        );
        CREATE INDEX idx_grant_journal_grant_id
            ON grant_journal (grant_id);
        CREATE TABLE active_grants (
            grant_id TEXT PRIMARY KEY,
            session_id TEXT NOT NULL,
            actor_id TEXT NOT NULL,
            grant_json TEXT NOT NULL,
            revoked INTEGER NOT NULL CHECK (revoked IN (0, 1))
        );
        CREATE INDEX idx_active_grants_actor_revoked
            ON active_grants (actor_id, revoked, grant_id);
        CREATE TABLE session_catalog (
            session_id TEXT PRIMARY KEY,
            display_name TEXT
        );",
    )?;
    conn.execute(
        "INSERT INTO schema_version (version) VALUES (?)",
        [CURRENT_SCHEMA_VERSION],
    )?;
    Ok(())
}

fn validate_schema(conn: &Connection) -> Result<(), rusqlite::Error> {
    validate_table(conn, &SCHEMA_VERSION_TABLE)?;
    let installed = read_single_schema_version(conn)?;
    if installed != i64::from(CURRENT_SCHEMA_VERSION) {
        return Err(schema_error(format!(
            "unsupported SQLite schema version {installed}; expected {CURRENT_SCHEMA_VERSION}"
        )));
    }
    for table in &REQUIRED_TABLES[1..] {
        validate_table(conn, table)?;
    }
    for index in REQUIRED_INDEXES {
        validate_index(conn, index)?;
    }
    Ok(())
}

fn validate_table(conn: &Connection, expected: &TableSpec) -> Result<(), rusqlite::Error> {
    if !schema_object_exists(conn, "table", expected.name, expected.name)? {
        return Err(schema_error(format!(
            "incompatible SQLite schema version 1: required table `{}` is missing",
            expected.name
        )));
    }
    let mut statement = conn.prepare(
        "SELECT cid, name, type, \"notnull\", dflt_value, pk, hidden
         FROM pragma_table_xinfo(?1, 'main') ORDER BY cid",
    )?;
    let columns = statement
        .query_map([expected.name], |row| {
            Ok(ColumnMetadata {
                position: row.get(0)?,
                name: row.get(1)?,
                data_type: row.get(2)?,
                not_null: row.get(3)?,
                default_value: row.get(4)?,
                primary_key_position: row.get(5)?,
                hidden: row.get(6)?,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;
    if columns.len() != expected.columns.len()
        || columns
            .iter()
            .zip(expected.columns)
            .enumerate()
            .any(|(position, (actual, expected))| !actual.matches(position, expected))
    {
        return Err(malformed_table(expected.name));
    }
    Ok(())
}

fn validate_index(conn: &Connection, expected: &IndexSpec) -> Result<(), rusqlite::Error> {
    if !schema_object_exists(conn, "index", expected.name, expected.table)? {
        return Err(schema_error(format!(
            "incompatible SQLite schema version 1: required index `{}` is missing",
            expected.name
        )));
    }
    let metadata = conn
        .query_row(
            "SELECT \"unique\", origin, partial
             FROM pragma_index_list(?1, 'main') WHERE name = ?2",
            [expected.table, expected.name],
            |row| {
                Ok(IndexMetadata {
                    unique: row.get(0)?,
                    origin: row.get(1)?,
                    partial: row.get(2)?,
                })
            },
        )
        .optional()?
        .ok_or_else(|| malformed_index(expected.name))?;
    if metadata.unique != expected.unique || metadata.origin != "c" || metadata.partial {
        return Err(malformed_index(expected.name));
    }

    let mut statement = conn.prepare(
        "SELECT name, desc, coll
         FROM pragma_index_xinfo(?1, 'main') WHERE \"key\" = 1 ORDER BY seqno",
    )?;
    let columns = statement
        .query_map([expected.name], |row| {
            Ok(IndexColumnMetadata {
                name: row.get(0)?,
                descending: row.get(1)?,
                collation: row.get(2)?,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;
    if columns.len() != expected.columns.len()
        || columns
            .iter()
            .zip(expected.columns)
            .any(|(actual, expected)| {
                actual.name != *expected || actual.descending || actual.collation != "BINARY"
            })
    {
        return Err(malformed_index(expected.name));
    }
    Ok(())
}

fn read_single_schema_version(conn: &Connection) -> Result<i64, rusqlite::Error> {
    let mut statement =
        conn.prepare("SELECT version, typeof(version) FROM schema_version ORDER BY rowid")?;
    let mut rows = statement.query([])?;
    let Some(row) = rows.next()? else {
        return Err(malformed_version_row());
    };
    let value_type: String = row.get(1)?;
    if value_type != "integer" {
        return Err(malformed_version_row());
    }
    let version = row.get(0)?;
    if rows.next()?.is_some() {
        return Err(malformed_version_row());
    }
    Ok(version)
}

fn schema_object_exists(
    conn: &Connection,
    object_type: &str,
    name: &str,
    table: &str,
) -> Result<bool, rusqlite::Error> {
    conn.query_row(
        "SELECT EXISTS(
            SELECT 1 FROM main.sqlite_schema
            WHERE type = ?1 AND name = ?2 AND tbl_name = ?3
        )",
        [object_type, name, table],
        |row| row.get(0),
    )
}

fn has_user_schema_objects(conn: &Connection) -> Result<bool, rusqlite::Error> {
    conn.query_row(
        "SELECT EXISTS(
            SELECT 1 FROM main.sqlite_schema WHERE name NOT GLOB 'sqlite_*'
        )",
        [],
        |row| row.get(0),
    )
}

fn malformed_table(name: &str) -> rusqlite::Error {
    schema_error(format!(
        "incompatible SQLite schema version 1: table `{name}` has an unexpected layout"
    ))
}

fn malformed_index(name: &str) -> rusqlite::Error {
    schema_error(format!(
        "incompatible SQLite schema version 1: index `{name}` has an unexpected layout"
    ))
}

fn malformed_version_row() -> rusqlite::Error {
    schema_error("incompatible SQLite schema: schema_version must contain exactly one integer row")
}

fn schema_error(message: impl Into<String>) -> rusqlite::Error {
    rusqlite::Error::SqliteFailure(
        rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_SCHEMA),
        Some(message.into()),
    )
}

#[derive(Clone, Copy)]
struct TableSpec {
    name: &'static str,
    columns: &'static [ColumnSpec],
}

#[derive(Clone, Copy)]
struct ColumnSpec {
    name: &'static str,
    data_type: &'static str,
    not_null: bool,
    primary_key_position: u32,
}

impl ColumnSpec {
    const fn nullable(name: &'static str, data_type: &'static str) -> Self {
        Self {
            name,
            data_type,
            not_null: false,
            primary_key_position: 0,
        }
    }

    const fn not_null(name: &'static str, data_type: &'static str) -> Self {
        Self {
            name,
            data_type,
            not_null: true,
            primary_key_position: 0,
        }
    }

    const fn primary_key(
        name: &'static str,
        data_type: &'static str,
        primary_key_position: u32,
    ) -> Self {
        Self {
            name,
            data_type,
            not_null: false,
            primary_key_position,
        }
    }

    const fn not_null_primary_key(
        name: &'static str,
        data_type: &'static str,
        primary_key_position: u32,
    ) -> Self {
        Self {
            name,
            data_type,
            not_null: true,
            primary_key_position,
        }
    }
}

struct ColumnMetadata {
    position: u32,
    name: String,
    data_type: String,
    not_null: bool,
    default_value: Option<String>,
    primary_key_position: u32,
    hidden: u32,
}

impl ColumnMetadata {
    fn matches(&self, position: usize, expected: &ColumnSpec) -> bool {
        usize::try_from(self.position).ok() == Some(position)
            && self.name == expected.name
            && self.data_type == expected.data_type
            && self.not_null == expected.not_null
            && self.default_value.is_none()
            && self.primary_key_position == expected.primary_key_position
            && self.hidden == 0
    }
}

struct IndexSpec {
    name: &'static str,
    table: &'static str,
    unique: bool,
    columns: &'static [&'static str],
}

struct IndexMetadata {
    unique: bool,
    origin: String,
    partial: bool,
}

struct IndexColumnMetadata {
    name: String,
    descending: bool,
    collation: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn incompatible_layout_uses_sqlite_schema_error_code() {
        let mut connection = Connection::open_in_memory().unwrap();
        connection
            .execute_batch(
                "CREATE TABLE schema_version (version INTEGER PRIMARY KEY);
                 INSERT INTO schema_version (version) VALUES (1);",
            )
            .unwrap();

        let error = ensure_schema(&mut connection).unwrap_err();
        match error {
            rusqlite::Error::SqliteFailure(error, Some(message)) => {
                assert_eq!(error.extended_code, rusqlite::ffi::SQLITE_SCHEMA);
                assert!(message.contains("required table `records` is missing"));
            }
            other => panic!("unexpected error: {other}"),
        }
    }
}