uqa-storage-sqlite 0.3.8

SQLite catalog, indexes, compressed storage, graph and key/value providers
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Catalog version 17 relation-namespace migration.

use super::super::super::{
    drop_fts_aux_tables_for_table, params, quote_sql_identifier, table_exists,
    update_btree_table_name_rows_if_exists, update_table_name_rows_if_exists, Catalog,
    OptionalExtension, RelationIdentity, RelationKind, Result, SQLiteError,
    LEGACY_SEQUENCES_METADATA_KEY, LEGACY_VIEWS_METADATA_KEY,
};

#[derive(serde::Deserialize)]
struct LegacySequenceState {
    start: i64,
    increment: i64,
    current: i64,
}

pub(in crate::catalog::migration) fn migration_relation(value: &str) -> Result<RelationIdentity> {
    RelationIdentity::from_legacy_name(value).map_err(SQLiteError::StorageBackend)
}

fn register_migration_relation(
    seen: &mut std::collections::BTreeMap<RelationIdentity, (RelationKind, String)>,
    relation: &RelationIdentity,
    kind: RelationKind,
    source: String,
) -> Result<()> {
    if let Some((existing_kind, existing_source)) = seen.get(relation) {
        return Err(SQLiteError::StorageBackend(format!(
            "relation namespace migration collision for `{}`: {} `{}` and {} `{}`",
            relation.qualified_name(),
            existing_kind.as_str(),
            existing_source,
            kind.as_str(),
            source
        )));
    }
    seen.insert(relation.clone(), (kind, source));
    Ok(())
}

type SqliteSeenRelations = std::collections::BTreeMap<RelationIdentity, (RelationKind, String)>;

struct SqliteTableMigration {
    old_name: String,
    relation: RelationIdentity,
    analyzer: String,
    fts: String,
    vectors: String,
    columns: Option<String>,
    constraints: String,
}

struct SqliteSequenceMigration {
    relation: RelationIdentity,
    start: i64,
    increment: i64,
    current: i64,
}

struct SqliteForeignMigration {
    relation: RelationIdentity,
    server: String,
    columns: String,
    options: String,
}

struct SqliteRelationMigrations {
    seen: SqliteSeenRelations,
    tables: Vec<SqliteTableMigration>,
    sequences: Vec<SqliteSequenceMigration>,
    foreign_tables: Vec<SqliteForeignMigration>,
    views: Vec<(RelationIdentity, String)>,
}

fn load_legacy_tables(tx: &rusqlite::Connection) -> Result<Vec<SqliteTableMigration>> {
    let mut stmt = tx.prepare(
        "SELECT name, analyzer, fts_fields, vector_fields, columns, constraints
           FROM _tables ORDER BY name",
    )?;
    let rows = stmt.query_map([], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
            row.get::<_, Option<String>>(4)?,
            row.get::<_, String>(5)?,
        ))
    })?;
    let mut tables = Vec::new();
    for row in rows {
        let (old_name, analyzer, fts, vectors, columns, constraints) = row?;
        tables.push(SqliteTableMigration {
            relation: migration_relation(&old_name)?,
            old_name,
            analyzer,
            fts,
            vectors,
            columns,
            constraints,
        });
    }
    Ok(tables)
}

fn load_legacy_sequences(
    tx: &rusqlite::Connection,
) -> Result<Vec<(String, SqliteSequenceMigration)>> {
    let mut stmt =
        tx.prepare("SELECT name, start, increment, current FROM _sequences ORDER BY name")?;
    let rows = stmt.query_map([], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, i64>(1)?,
            row.get::<_, i64>(2)?,
            row.get::<_, i64>(3)?,
        ))
    })?;
    let mut sequences = Vec::new();
    for row in rows {
        let (name, start, increment, current) = row?;
        sequences.push((
            name.clone(),
            SqliteSequenceMigration {
                relation: migration_relation(&name)?,
                start,
                increment,
                current,
            },
        ));
    }
    Ok(sequences)
}

fn load_legacy_foreign_tables(
    tx: &rusqlite::Connection,
) -> Result<Vec<(String, SqliteForeignMigration)>> {
    let mut stmt = tx.prepare(
        "SELECT name, server_name, columns_json, options
           FROM _foreign_tables ORDER BY name",
    )?;
    let rows = stmt.query_map([], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
        ))
    })?;
    let mut foreign_tables = Vec::new();
    for row in rows {
        let (name, server, columns, options) = row?;
        foreign_tables.push((
            name.clone(),
            SqliteForeignMigration {
                relation: migration_relation(&name)?,
                server,
                columns,
                options,
            },
        ));
    }
    Ok(foreign_tables)
}

fn load_legacy_metadata<T>(tx: &rusqlite::Connection, key: &str) -> Result<T>
where
    T: serde::de::DeserializeOwned + Default,
{
    tx.query_row(
        "SELECT value FROM _metadata WHERE key = ?1",
        params![key],
        |row| row.get::<_, String>(0),
    )
    .optional()?
    .map(|json| serde_json::from_str::<T>(&json))
    .transpose()
    .map(Option::unwrap_or_default)
    .map_err(SQLiteError::from)
}

fn collect_sqlite_relation_migrations(
    tx: &rusqlite::Connection,
) -> Result<SqliteRelationMigrations> {
    let tables = load_legacy_tables(tx)?;
    let mut sequences = load_legacy_sequences(tx)?;
    let foreign_tables = load_legacy_foreign_tables(tx)?;
    let legacy_views = load_legacy_metadata::<serde_json::Map<String, serde_json::Value>>(
        tx,
        LEGACY_VIEWS_METADATA_KEY,
    )?;
    let legacy_sequences = load_legacy_metadata::<
        std::collections::BTreeMap<String, LegacySequenceState>,
    >(tx, LEGACY_SEQUENCES_METADATA_KEY)?;
    let mut seen = SqliteSeenRelations::new();
    for table in &tables {
        register_migration_relation(
            &mut seen,
            &table.relation,
            RelationKind::Table,
            table.old_name.clone(),
        )?;
    }
    for (source, sequence) in &sequences {
        register_migration_relation(
            &mut seen,
            &sequence.relation,
            RelationKind::Sequence,
            source.clone(),
        )?;
    }
    for (source, foreign) in &foreign_tables {
        register_migration_relation(
            &mut seen,
            &foreign.relation,
            RelationKind::ForeignTable,
            source.clone(),
        )?;
    }
    let mut views = Vec::new();
    for (name, definition) in legacy_views {
        let relation = migration_relation(&name)?;
        register_migration_relation(
            &mut seen,
            &relation,
            RelationKind::View,
            format!("legacy metadata `{name}`"),
        )?;
        views.push((relation, serde_json::to_string(&definition)?));
    }
    for (name, state) in legacy_sequences {
        let relation = migration_relation(&name)?;
        register_migration_relation(
            &mut seen,
            &relation,
            RelationKind::Sequence,
            format!("legacy metadata `{name}`"),
        )?;
        sequences.push((
            name,
            SqliteSequenceMigration {
                relation,
                start: state.start,
                increment: state.increment,
                current: state.current,
            },
        ));
    }
    Ok(SqliteRelationMigrations {
        seen,
        tables,
        sequences: sequences.into_iter().map(|(_, row)| row).collect(),
        foreign_tables: foreign_tables.into_iter().map(|(_, row)| row).collect(),
        views,
    })
}

fn create_structural_relation_tables(tx: &rusqlite::Connection) -> Result<()> {
    tx.execute_batch(
        "CREATE TABLE _relations (
            schema_name   TEXT NOT NULL,
            relation_name TEXT NOT NULL,
            kind          TEXT NOT NULL CHECK (
                kind IN ('table', 'view', 'sequence', 'foreign_table')
            ),
            PRIMARY KEY (schema_name, relation_name),
            UNIQUE (schema_name, relation_name, kind),
            FOREIGN KEY (schema_name) REFERENCES _schemas(name) ON DELETE RESTRICT
        );
        CREATE TABLE _tables_v17 (
            schema_name   TEXT NOT NULL,
            relation_name TEXT NOT NULL,
            kind          TEXT NOT NULL DEFAULT 'table' CHECK (kind = 'table'),
            analyzer      TEXT NOT NULL,
            fts_fields    TEXT NOT NULL,
            vector_fields TEXT NOT NULL,
            columns       TEXT,
            constraints   TEXT NOT NULL DEFAULT '',
            PRIMARY KEY (schema_name, relation_name),
            FOREIGN KEY (schema_name, relation_name, kind)
                REFERENCES _relations(schema_name, relation_name, kind)
                ON DELETE CASCADE
        );
        CREATE TABLE _sequences_v17 (
            schema_name   TEXT NOT NULL,
            relation_name TEXT NOT NULL,
            kind          TEXT NOT NULL DEFAULT 'sequence' CHECK (kind = 'sequence'),
            start         INTEGER NOT NULL,
            increment     INTEGER NOT NULL,
            current       INTEGER NOT NULL,
            PRIMARY KEY (schema_name, relation_name),
            FOREIGN KEY (schema_name, relation_name, kind)
                REFERENCES _relations(schema_name, relation_name, kind)
                ON DELETE CASCADE
        );
        CREATE TABLE _foreign_tables_v17 (
            schema_name   TEXT NOT NULL,
            relation_name TEXT NOT NULL,
            kind          TEXT NOT NULL DEFAULT 'foreign_table' CHECK (kind = 'foreign_table'),
            server_name   TEXT NOT NULL,
            columns_json  TEXT NOT NULL,
            options       TEXT NOT NULL,
            PRIMARY KEY (schema_name, relation_name),
            FOREIGN KEY (schema_name, relation_name, kind)
                REFERENCES _relations(schema_name, relation_name, kind)
                ON DELETE CASCADE
        );
        CREATE TABLE _views (
            schema_name     TEXT NOT NULL,
            relation_name   TEXT NOT NULL,
            kind            TEXT NOT NULL DEFAULT 'view' CHECK (kind = 'view'),
            definition_json TEXT NOT NULL,
            PRIMARY KEY (schema_name, relation_name),
            FOREIGN KEY (schema_name, relation_name, kind)
                REFERENCES _relations(schema_name, relation_name, kind)
                ON DELETE CASCADE
        );",
    )?;
    Ok(())
}

fn insert_relation_parents(tx: &rusqlite::Connection, seen: &SqliteSeenRelations) -> Result<()> {
    for (relation, (kind, _)) in seen {
        tx.execute(
            "INSERT OR IGNORE INTO _schemas(name) VALUES (?1)",
            params![relation.schema],
        )?;
        tx.execute(
            "INSERT INTO _relations(schema_name, relation_name, kind) VALUES (?1, ?2, ?3)",
            params![relation.schema, relation.name, kind.as_str()],
        )?;
    }
    Ok(())
}

fn migrate_sqlite_table_name(
    tx: &rusqlite::Connection,
    table: &SqliteTableMigration,
) -> Result<()> {
    let canonical = table.relation.qualified_name();
    if table.old_name == canonical {
        return Ok(());
    }
    for owner_table in [
        "_documents",
        "_document_blobs",
        "_postings",
        "_doc_lengths",
        "_field_stats",
        "_vectors",
        "_ivf_indexes",
        "_ivf_centroids",
        "_ivf_assignments",
        "_hnsw_indexes",
        "_hnsw_nodes",
        "_hnsw_edges",
        "_column_stats",
        "_table_field_analyzers",
        "_catalog_indexes",
    ] {
        if table_exists(tx, owner_table)? {
            let target_rows: i64 = tx.query_row(
                &format!(
                    "SELECT COUNT(*) FROM {} WHERE table_name = ?1",
                    quote_sql_identifier(owner_table)
                ),
                params![canonical],
                |row| row.get(0),
            )?;
            if target_rows != 0 {
                return Err(SQLiteError::StorageBackend(format!(
                    "relation namespace migration for `{canonical}` would overwrite existing rows in `{owner_table}`"
                )));
            }
        }
        update_table_name_rows_if_exists(tx, owner_table, &table.old_name, &canonical)?;
    }
    // `_btree_index_entries` is a child of `_btree_indexes`. Check both
    // destinations before moving either, then update parent-first. The helper
    // also moves children explicitly when an externally supplied SQLite
    // connection has foreign-key enforcement disabled.
    for owner_table in ["_btree_indexes", "_btree_index_entries"] {
        if table_exists(tx, owner_table)? {
            let target_rows: i64 = tx.query_row(
                &format!(
                    "SELECT COUNT(*) FROM {} WHERE table_name = ?1",
                    quote_sql_identifier(owner_table)
                ),
                params![canonical],
                |row| row.get(0),
            )?;
            if target_rows != 0 {
                return Err(SQLiteError::StorageBackend(format!(
                    "relation namespace migration for `{canonical}` would overwrite existing rows in `{owner_table}`"
                )));
            }
        }
    }
    update_btree_table_name_rows_if_exists(tx, &table.old_name, &canonical)?;
    drop_fts_aux_tables_for_table(tx, &table.old_name)
}

fn insert_table_migration(tx: &rusqlite::Connection, table: &SqliteTableMigration) -> Result<()> {
    migrate_sqlite_table_name(tx, table)?;
    tx.execute(
        "INSERT INTO _tables_v17
            (schema_name, relation_name, kind, analyzer, fts_fields,
             vector_fields, columns, constraints)
         VALUES (?1, ?2, 'table', ?3, ?4, ?5, ?6, ?7)",
        params![
            table.relation.schema,
            table.relation.name,
            table.analyzer,
            table.fts,
            table.vectors,
            table.columns,
            table.constraints
        ],
    )?;
    Ok(())
}

fn insert_relation_children(
    tx: &rusqlite::Connection,
    migrations: &SqliteRelationMigrations,
) -> Result<()> {
    for table in &migrations.tables {
        insert_table_migration(tx, table)?;
    }
    for sequence in &migrations.sequences {
        tx.execute(
            "INSERT INTO _sequences_v17
                (schema_name, relation_name, kind, start, increment, current)
             VALUES (?1, ?2, 'sequence', ?3, ?4, ?5)",
            params![
                sequence.relation.schema,
                sequence.relation.name,
                sequence.start,
                sequence.increment,
                sequence.current
            ],
        )?;
    }
    for foreign in &migrations.foreign_tables {
        tx.execute(
            "INSERT INTO _foreign_tables_v17
                (schema_name, relation_name, kind, server_name, columns_json, options)
             VALUES (?1, ?2, 'foreign_table', ?3, ?4, ?5)",
            params![
                foreign.relation.schema,
                foreign.relation.name,
                foreign.server,
                foreign.columns,
                foreign.options
            ],
        )?;
    }
    for (relation, definition_json) in &migrations.views {
        tx.execute(
            "INSERT INTO _views
                (schema_name, relation_name, kind, definition_json)
             VALUES (?1, ?2, 'view', ?3)",
            params![relation.schema, relation.name, definition_json],
        )?;
    }
    Ok(())
}

fn finish_sqlite_relation_migration(tx: &rusqlite::Connection) -> Result<()> {
    tx.execute_batch(
        "DROP TABLE _tables;
         ALTER TABLE _tables_v17 RENAME TO _tables;
         DROP TABLE _sequences;
         ALTER TABLE _sequences_v17 RENAME TO _sequences;
         DROP TABLE _foreign_tables;
         ALTER TABLE _foreign_tables_v17 RENAME TO _foreign_tables;",
    )?;
    for key in [LEGACY_VIEWS_METADATA_KEY, LEGACY_SEQUENCES_METADATA_KEY] {
        tx.execute(
            "INSERT OR REPLACE INTO _metadata(key, value) VALUES (?1, '{}')",
            params![key],
        )?;
    }
    Ok(())
}

pub(super) fn migrate(tx: &rusqlite::Connection) -> Result<()> {
    let relation_namespace_already_present = Catalog::table_columns(tx, "_tables")?
        .is_some_and(|columns| columns.contains_key("schema_name"))
        && Catalog::table_columns(tx, "_relations")?.is_some()
        && Catalog::table_columns(tx, "_views")?.is_some();
    if relation_namespace_already_present {
        return Ok(());
    }
    let migrations = collect_sqlite_relation_migrations(tx)?;
    create_structural_relation_tables(tx)?;
    insert_relation_parents(tx, &migrations.seen)?;
    insert_relation_children(tx, &migrations)?;
    finish_sqlite_relation_migration(tx)
}