dovecote-sqlx-sqlite 0.2.0

SQLite SQLx adapter for Dovecote
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
//! SQLite schema verification.

use crate::{
    error::SchemaError,
    migration::{current_migration, migration_is_usable},
};
use sqlx::{FromRow, Row, SqliteConnection, SqlitePool, query, query_as, query_scalar};

#[derive(Debug, FromRow)]
struct SchemaMarker {
    schema_version: i64,
    minimum_crate_major: i64,
    minimum_crate_minor: i64,
    minimum_crate_patch: i64,
    rolling_compatible: i64,
}

/// Verifies the exact v2 table shape, constraints, indexes, and foreign key of
/// the installed schema. It never applies a migration.
pub async fn check_schema(pool: &SqlitePool) -> Result<(), SchemaError> {
    let mut connection = pool
        .acquire()
        .await
        .map_err(|source| SchemaError::sql("acquire schema-check connection", source))?;
    check_schema_connection(&mut connection).await
}

/// Performs the complete schema check on an already-owned connection.
pub(crate) async fn check_schema_connection(
    connection: &mut SqliteConnection,
) -> Result<(), SchemaError> {
    let enabled: i64 = query_scalar("PRAGMA foreign_keys")
        .fetch_one(&mut *connection)
        .await
        .map_err(|source| SchemaError::sql("check foreign-key enforcement", source))?;
    if enabled != 1 {
        return Err(mismatch("foreign-key enforcement is disabled"));
    }

    let migration = current_migration().map_err(mismatch)?;
    migration_is_usable(migration).map_err(mismatch)?;
    check_schema_marker(connection, migration).await?;

    check_columns(
        connection,
        "dovecote_events",
        &[
            ColumnSpec::required("row_id", "INTEGER", true),
            ColumnSpec::required("tenant_id", "TEXT", false),
            ColumnSpec::required("stream", "TEXT", false),
            ColumnSpec::required("specversion", "TEXT", false),
            ColumnSpec::required("event_id", "TEXT", false),
            ColumnSpec::required("source", "TEXT", false),
            ColumnSpec::required("event_type", "TEXT", false),
            ColumnSpec::optional("subject", "TEXT", false),
            ColumnSpec::optional("occurred_at", "TEXT", false),
            ColumnSpec::optional("datacontenttype", "TEXT", false),
            ColumnSpec::optional("dataschema", "TEXT", false),
            ColumnSpec::optional("partitionkey", "TEXT", false),
            ColumnSpec::required("extensions", "TEXT", false),
            ColumnSpec::optional("data_kind", "TEXT", false),
            ColumnSpec::optional("data", "BLOB", false),
            ColumnSpec::required("enqueued_at", "TEXT", false),
        ],
    )
    .await?;
    check_columns(
        connection,
        "dovecote_deliveries",
        &[
            ColumnSpec::required("event_row_id", "INTEGER", true),
            ColumnSpec::required("tenant_id", "TEXT", false),
            ColumnSpec::required("state", "TEXT", false),
            ColumnSpec::required("available_at", "TEXT", false),
            ColumnSpec::required("attempts", "INTEGER", false),
            ColumnSpec::optional("claim_token", "BLOB", false),
            ColumnSpec::optional("claimed_by", "TEXT", false),
            ColumnSpec::optional("claim_expires_at", "TEXT", false),
            ColumnSpec::optional("last_failure_code", "TEXT", false),
            ColumnSpec::optional("last_failure_detail", "TEXT", false),
            ColumnSpec::optional("delivered_at", "TEXT", false),
            ColumnSpec::optional("quarantined_at", "TEXT", false),
            ColumnSpec::optional("quarantine_reason", "TEXT", false),
        ],
    )
    .await?;

    let sources = query_as::<_, TableSource>(
        "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name IN ('dovecote_schema', 'dovecote_events', 'dovecote_deliveries')",
    ).fetch_all(&mut *connection).await
        .map_err(|source| SchemaError::sql("read schema definitions", source))?;
    for name in ["dovecote_schema", "dovecote_events", "dovecote_deliveries"] {
        if !sources.iter().any(|source| source.name == name) {
            return Err(mismatch(format!("required table {name} is missing")));
        }
    }

    for name in ["dovecote_schema", "dovecote_events", "dovecote_deliveries"] {
        let source = sources
            .iter()
            .find(|source| source.name == name)
            .expect("checked above");
        let expected = expected_table_source(migration.sql(), name).map_err(mismatch)?;
        if normalize_sql(&source.sql) != normalize_sql(&expected) {
            return Err(mismatch(format!(
                "table {name} definition is incompatible with schema version {}",
                migration.version()
            )));
        }
    }

    // TEMP triggers and indexes can target a main-schema table, so inspect
    // both catalogs.  Leaving sqlite_temp_master out would allow a caller to
    // add an unreviewed trigger that changes durable invariants for this
    // connection while the main schema still appears exact.
    let extra_objects: Vec<SchemaObject> = query_as(
        "SELECT type, name, COALESCE(tbl_name, '') AS tbl_name FROM sqlite_master WHERE (name LIKE 'dovecote_%' OR tbl_name IN ('dovecote_events', 'dovecote_deliveries')) AND NOT (type = 'table' AND name IN ('dovecote_schema', 'dovecote_events', 'dovecote_deliveries')) AND NOT (type = 'index' AND name IN ('dovecote_events_tenant_source_event_id', 'dovecote_events_tenant_row', 'dovecote_deliveries_claimable', 'dovecote_deliveries_expired_claims', 'sqlite_autoindex_dovecote_events_1')) UNION ALL SELECT type, name, COALESCE(tbl_name, '') AS tbl_name FROM sqlite_temp_master WHERE name LIKE 'dovecote_%' OR tbl_name IN ('dovecote_events', 'dovecote_deliveries')",
    )
    .fetch_all(&mut *connection)
    .await
    .map_err(|source| SchemaError::sql("check schema object isolation", source))?;
    if let Some(object) = extra_objects.first() {
        return Err(mismatch(format!(
            "unsupported SQLite schema object {} {} on {}",
            object.object_type, object.name, object.table_name
        )));
    }

    check_index(
        connection,
        "dovecote_events",
        "dovecote_events_tenant_source_event_id",
        true,
        &["tenant_id", "source", "event_id"],
        migration.sql(),
    )
    .await?;
    check_index(
        connection,
        "dovecote_events",
        "dovecote_events_tenant_row",
        false,
        &["tenant_id", "row_id"],
        migration.sql(),
    )
    .await?;
    check_index(
        connection,
        "dovecote_deliveries",
        "dovecote_deliveries_claimable",
        false,
        &["tenant_id", "state", "available_at", "event_row_id"],
        migration.sql(),
    )
    .await?;
    check_index(
        connection,
        "dovecote_deliveries",
        "dovecote_deliveries_expired_claims",
        false,
        &["tenant_id", "state", "claim_expires_at", "event_row_id"],
        migration.sql(),
    )
    .await?;
    check_foreign_key(connection).await?;
    let violations = query("PRAGMA foreign_key_check")
        .fetch_all(&mut *connection)
        .await
        .map_err(|source| SchemaError::sql("check foreign-key integrity", source))?;
    if !violations.is_empty() {
        return Err(mismatch("installed schema contains foreign-key violations"));
    }
    Ok(())
}

async fn check_schema_marker(
    connection: &mut SqliteConnection,
    migration: crate::migration::Migration,
) -> Result<(), SchemaError> {
    let markers = query_as::<_, SchemaMarker>(
        "SELECT schema_version, minimum_crate_major, minimum_crate_minor, minimum_crate_patch, rolling_compatible FROM dovecote_schema",
    )
    .fetch_all(&mut *connection)
    .await
    .map_err(|source| SchemaError::sql("check schema marker", source))?;
    if markers.len() != 1 {
        return Err(mismatch(format!(
            "expected exactly one schema marker row, found {}",
            markers.len()
        )));
    }

    let marker = &markers[0];
    let minimum = migration.compatibility().minimum();
    if marker.schema_version != i64::from(migration.version())
        || marker.minimum_crate_major != i64::from(minimum.major())
        || marker.minimum_crate_minor != i64::from(minimum.minor())
        || marker.minimum_crate_patch != i64::from(minimum.patch())
        || marker.rolling_compatible != if migration.rolling_compatible() { 1 } else { 0 }
    {
        return Err(mismatch("schema marker is incompatible with this adapter"));
    }
    Ok(())
}

fn mismatch(detail: impl Into<String>) -> SchemaError {
    SchemaError::MigrationMismatch {
        detail: detail.into(),
    }
}

#[derive(Clone, Copy)]
struct ColumnSpec {
    name: &'static str,
    kind: &'static str,
    primary_key: bool,
    not_null: bool,
}
impl ColumnSpec {
    const fn required(name: &'static str, kind: &'static str, primary_key: bool) -> Self {
        Self {
            name,
            kind,
            primary_key,
            not_null: !primary_key,
        }
    }
    const fn optional(name: &'static str, kind: &'static str, primary_key: bool) -> Self {
        Self {
            name,
            kind,
            primary_key,
            not_null: false,
        }
    }
}

#[derive(Debug, FromRow)]
struct TableSource {
    name: String,
    sql: String,
}

#[derive(Debug, FromRow)]
struct SchemaObject {
    #[sqlx(rename = "type")]
    object_type: String,
    name: String,
    #[sqlx(rename = "tbl_name")]
    table_name: String,
}

async fn check_columns(
    connection: &mut SqliteConnection,
    table: &str,
    expected: &[ColumnSpec],
) -> Result<(), SchemaError> {
    let sql = sqlx::AssertSqlSafe(format!("PRAGMA table_info({table})"));
    let rows = query(sql)
        .fetch_all(&mut *connection)
        .await
        .map_err(|source| SchemaError::sql("check table columns", source))?;
    for spec in expected {
        let Some(row) = rows
            .iter()
            .find(|row| row.try_get::<String, _>("name").ok().as_deref() == Some(spec.name))
        else {
            return Err(mismatch(format!(
                "required column {table}.{} is missing",
                spec.name
            )));
        };

        let kind = row
            .try_get::<String, _>("type")
            .map_err(|_| mismatch(format!("column {table}.{} has no type", spec.name)))?;
        if !kind.eq_ignore_ascii_case(spec.kind) {
            return Err(mismatch(format!(
                "column {table}.{} has type {kind}, expected {}",
                spec.name, spec.kind
            )));
        }

        let pk = row.try_get::<i64, _>("pk").unwrap_or_default();
        if spec.primary_key && pk != 1 {
            return Err(mismatch(format!(
                "column {table}.{} is not the primary key",
                spec.name
            )));
        }

        let not_null = row.try_get::<i64, _>("notnull").unwrap_or_default() != 0;
        if spec.not_null && !not_null {
            return Err(mismatch(format!(
                "column {table}.{} must be NOT NULL",
                spec.name
            )));
        }
    }

    Ok(())
}

async fn check_index(
    connection: &mut SqliteConnection,
    table: &str,
    expected_name: &str,
    unique: bool,
    columns: &[&str],
    migration: &str,
) -> Result<(), SchemaError> {
    let sql = sqlx::AssertSqlSafe(format!("PRAGMA index_list({table})"));
    let indexes = query(sql)
        .fetch_all(&mut *connection)
        .await
        .map_err(|source| SchemaError::sql("check schema indexes", source))?;
    let Some(index) = indexes
        .iter()
        .find(|row| row.try_get::<String, _>("name").ok().as_deref() == Some(expected_name))
    else {
        return Err(mismatch(format!(
            "required index {expected_name} is missing"
        )));
    };

    let actual_unique = index.try_get::<i64, _>("unique").unwrap_or_default() != 0;
    if actual_unique != unique {
        return Err(mismatch(format!(
            "index {expected_name} uniqueness is incompatible"
        )));
    }

    let source: Option<String> =
        query_scalar("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?")
            .bind(expected_name)
            .fetch_optional(&mut *connection)
            .await
            .map_err(|source| SchemaError::sql("read schema index definition", source))?;
    let Some(source) = source else {
        return Err(mismatch(format!("index {expected_name} has no definition")));
    };

    let expected = expected_index_source(migration, expected_name).map_err(mismatch)?;
    if normalize_sql(&source) != normalize_sql(&expected) {
        return Err(mismatch(format!(
            "index {expected_name} definition is incompatible"
        )));
    }

    let info_sql = sqlx::AssertSqlSafe(format!("PRAGMA index_info({expected_name})"));
    let info = query(info_sql)
        .fetch_all(&mut *connection)
        .await
        .map_err(|source| SchemaError::sql("read schema index columns", source))?;
    let actual = info
        .iter()
        .filter_map(|row| row.try_get::<String, _>("name").ok())
        .collect::<Vec<_>>();
    if actual
        != columns
            .iter()
            .map(|column| (*column).to_owned())
            .collect::<Vec<_>>()
    {
        return Err(mismatch(format!(
            "index {expected_name} columns are incompatible"
        )));
    }

    if expected_name == "dovecote_events_tenant_source_event_id" {
        let xinfo_sql = sqlx::AssertSqlSafe(format!("PRAGMA index_xinfo({expected_name})"));
        let xinfo = query(xinfo_sql)
            .fetch_all(&mut *connection)
            .await
            .map_err(|source| SchemaError::sql("read identity index collation", source))?;
        let collations = xinfo
            .iter()
            .filter_map(|row| row.try_get::<i64, _>("key").ok().filter(|key| *key != 0))
            .zip(
                xinfo
                    .iter()
                    .filter_map(|row| row.try_get::<String, _>("coll").ok()),
            )
            .map(|(_, collation)| collation)
            .collect::<Vec<_>>();
        if collations
            != [
                "BINARY".to_owned(),
                "BINARY".to_owned(),
                "BINARY".to_owned(),
            ]
        {
            return Err(mismatch("identity index collation is not BINARY"));
        }
    }

    Ok(())
}

async fn check_foreign_key(connection: &mut SqliteConnection) -> Result<(), SchemaError> {
    let rows = query("PRAGMA foreign_key_list(dovecote_deliveries)")
        .fetch_all(&mut *connection)
        .await
        .map_err(|source| SchemaError::sql("check delivery foreign key", source))?;
    let matching = rows
        .iter()
        .filter(|row| row.try_get::<String, _>("table").ok().as_deref() == Some("dovecote_events"))
        .collect::<Vec<_>>();
    if matching.len() != 2 {
        return Err(mismatch("delivery foreign key is missing"));
    }

    let columns = matching
        .iter()
        .map(|row| {
            (
                row.try_get::<String, _>("from").unwrap_or_default(),
                row.try_get::<String, _>("to").unwrap_or_default(),
            )
        })
        .collect::<Vec<_>>();
    if !columns.contains(&("tenant_id".to_owned(), "tenant_id".to_owned()))
        || !columns.contains(&("event_row_id".to_owned(), "row_id".to_owned()))
    {
        return Err(mismatch("delivery foreign key is incompatible"));
    }
    Ok(())
}

fn expected_table_source(migration: &str, table: &str) -> Result<String, String> {
    let needle = format!("CREATE TABLE {table}");
    let start = migration
        .find(&needle)
        .ok_or_else(|| format!("migration does not define {table}"))?;
    let mut depth = 0_u32;
    let mut quoted = false;
    for (offset, character) in migration[start..].char_indices() {
        match character {
            '\'' => quoted = !quoted,
            '(' if !quoted => depth = depth.saturating_add(1),
            ')' if !quoted => depth = depth.saturating_sub(1),
            ';' if !quoted && depth == 0 => return Ok(migration[start..start + offset].to_owned()),
            _ => {}
        }
    }
    Err(format!("migration statement for {table} is unterminated"))
}

fn expected_index_source(migration: &str, index: &str) -> Result<String, String> {
    let needle = if migration.contains(&format!("CREATE UNIQUE INDEX {index}")) {
        format!("CREATE UNIQUE INDEX {index}")
    } else {
        format!("CREATE INDEX {index}")
    };
    let start = migration
        .find(&needle)
        .ok_or_else(|| format!("migration does not define {index}"))?;
    let end = migration[start..]
        .find(';')
        .map(|offset| start + offset)
        .ok_or_else(|| format!("migration statement for {index} is unterminated"))?;
    Ok(migration[start..end].to_owned())
}

fn normalize_sql(value: &str) -> String {
    let mut normalized = String::with_capacity(value.len());
    let mut in_string = false;
    for character in value.chars() {
        match (character, in_string) {
            ('\'', _) => {
                in_string = !in_string;
                normalized.push(character);
            }
            ('"', false) => {
                // SQLite quotes a rebuilt table name after ALTER TABLE RENAME;
                // identifier quoting does not change the table contract.
            }
            (character, true) if !character.is_ascii_whitespace() => {
                normalized.push(character);
            }
            (character, false) if !character.is_ascii_whitespace() => {
                normalized.extend(character.to_lowercase());
            }
            _ => {}
        }
    }
    normalized
}