rust: graph_copy reads each table's columns from the schema at copy time
GRAPH_TABLE_COLUMNS re-listed every column of nine tables, and a test
existed only to catch it drifting (provenance was once silently dropped
from reseeded stores that way). The copy now asks pragma_table_info for the
destination's columns and names them in both the INSERT and the SELECT, so
only the table list is kept and the drift test goes with the class of bug.
Store::db_path returns the PathBuf instead of a String built through
expect("store path is valid UTF-8"), and the ATTACH, which does need text,
reports a non-UTF-8 path as StoreError::NonUtf8Path rather than panicking
(B6, twice).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9d1bfe848f
commit
52f16c5d28
2 files changed
+54
-100
No files matched your search
@@ -4,48 +4,34 @@
|
||||
//! Here rather than in `reseed` because the knowledge it needs is the
|
||||
//! schema's: which tables exist, which columns each has, and which of them
|
||||
//! carry a user's documents rather than a node's peer-swarm state. `reseed`
|
||||
//! is the only caller and has no other business with SQL — keeping the list
|
||||
//! next to the `CREATE TABLE` statements it mirrors is what gives the two a
|
||||
//! chance of being changed together.
|
||||
|
||||
use std::path::Path;
|
||||
//! is the only caller and has no other business with SQL.
|
||||
|
||||
use rusqlite::{Connection, params};
|
||||
|
||||
use super::{Store, StoreError};
|
||||
|
||||
/// Explicit `(table, columns)` list for the tables copied verbatim from the
|
||||
/// source store. Explicit columns (not `SELECT *`) so a future schema change
|
||||
/// can't silently misalign source and destination.
|
||||
/// The tables copied verbatim from the source store. Each is copied with the
|
||||
/// columns the destination's schema has, read from `pragma_table_info` at copy
|
||||
/// time rather than listed here: a hand-kept column list is one a new column
|
||||
/// can be left off, and the copy then succeeds with that column silently at
|
||||
/// its default — `provenance` (ADR 0038) went missing from reseeded stores
|
||||
/// that way, turning every anchor, derived and machinery document into a
|
||||
/// `user` one. Naming the columns (not `SELECT *`) still keeps source and
|
||||
/// destination aligned; a source missing one of them fails the copy loudly.
|
||||
///
|
||||
/// What it cannot catch is a column *added* to a table and not added here: the
|
||||
/// copy still succeeds and the new column silently takes its default in the
|
||||
/// reseeded store. `provenance` (ADR 0038) was missing for exactly that reason
|
||||
/// until `parent_modified_at` arrived and made the omission loud — a reseed had
|
||||
/// been quietly turning every anchor, derived and machinery document into a
|
||||
/// `user` one. **Adding a column to any table below means adding it here**, and
|
||||
/// [`every_copied_table_lists_every_one_of_its_columns`] fails if you don't.
|
||||
const GRAPH_TABLE_COLUMNS: &[(&str, &str)] = &[
|
||||
(
|
||||
"documents",
|
||||
"id, doc_type, provenance, parent_id, parent_modified_at, vault_id, created_at, \
|
||||
modified_at, origin_node",
|
||||
),
|
||||
("properties", "id, document_id, kind, value, modified_at, origin_node"),
|
||||
("edges", "id, from_id, to_id, kind, created_at, origin_node"),
|
||||
("edge_tombstones", "id, from_id, deleted_at, origin_node"),
|
||||
("document_tombstones", "id, deleted_at, origin_node"),
|
||||
("property_history", "id, document_id, kind, value, modified_at, origin_node"),
|
||||
// Copied with the *old* blob_hash values (both the serialized blob-backed
|
||||
// values and the denormalized blob_hash column); the caller re-encrypts and
|
||||
// rewrites them afterward.
|
||||
(
|
||||
"artifacts",
|
||||
"id, document_id, kind, value, modified_at, origin_node, singleton, blob_hash, \
|
||||
blob_size_bytes",
|
||||
),
|
||||
("artifact_stubs", "id, document_id, kind, size_bytes, modified_at, origin_node, singleton"),
|
||||
("artifact_tombstones", "id, document_id, kind, deleted_at, origin_node"),
|
||||
/// `artifacts` is copied with the *old* blob_hash values (both the serialized
|
||||
/// blob-backed values and the denormalized column); the caller re-encrypts and
|
||||
/// rewrites them afterward.
|
||||
const GRAPH_TABLES: &[&str] = &[
|
||||
"documents",
|
||||
"properties",
|
||||
"edges",
|
||||
"edge_tombstones",
|
||||
"document_tombstones",
|
||||
"property_history",
|
||||
"artifacts",
|
||||
"artifact_stubs",
|
||||
"artifact_tombstones",
|
||||
];
|
||||
|
||||
impl Store {
|
||||
@@ -63,69 +49,35 @@ impl Store {
|
||||
/// Expects this store to be otherwise empty. Nothing enforces that — the
|
||||
/// inserts would simply collide on the primary keys.
|
||||
pub fn copy_graph_tables_from(&self, source: &Store) -> Result<(), StoreError> {
|
||||
copy_graph_tables(Path::new(&source.db_path()), Path::new(&self.db_path()))
|
||||
}
|
||||
}
|
||||
let source_db = source.db_path();
|
||||
let source_db_str =
|
||||
source_db.to_str().ok_or_else(|| StoreError::NonUtf8Path(source_db.clone()))?;
|
||||
|
||||
fn copy_graph_tables(source_db: &Path, dest_db: &Path) -> Result<(), StoreError> {
|
||||
let source_db_str = source_db.to_str().expect("store db path is valid UTF-8");
|
||||
let mut conn = Connection::open(self.db_path())?;
|
||||
// Must be set before the transaction starts; allows the self-referential
|
||||
// `documents.parent_id` FK (and friends) to be satisfied by the bulk
|
||||
// insert regardless of row order within a table.
|
||||
conn.execute("PRAGMA foreign_keys = OFF", [])?;
|
||||
conn.execute("ATTACH DATABASE ?1 AS source_db", params![source_db_str])?;
|
||||
|
||||
let mut conn = Connection::open(dest_db)?;
|
||||
// Must be set before the transaction starts; allows the self-referential
|
||||
// `documents.parent_id` FK (and friends) to be satisfied by the bulk
|
||||
// insert regardless of row order within a table.
|
||||
conn.execute("PRAGMA foreign_keys = OFF", [])?;
|
||||
conn.execute("ATTACH DATABASE ?1 AS source_db", params![source_db_str])?;
|
||||
|
||||
let tx = conn.transaction()?;
|
||||
for (table, columns) in GRAPH_TABLE_COLUMNS {
|
||||
// sql-literal-ok: `table` and `columns` are this module's own
|
||||
// `&'static str`s naming schema objects. SQLite will not bind an
|
||||
// identifier, and nothing outside this file can reach either.
|
||||
tx.execute(
|
||||
&format!("INSERT INTO {table} ({columns}) SELECT {columns} FROM source_db.{table}"),
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
|
||||
conn.execute("DETACH DATABASE source_db", [])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{TestStore, store};
|
||||
use rstest::rstest;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// The comment on [`GRAPH_TABLE_COLUMNS`] made into a check.
|
||||
///
|
||||
/// A column added to one of these tables and not added there is not a
|
||||
/// compile error and not a copy failure — the reseeded row simply takes the
|
||||
/// column's default. `provenance` went missing that way and was only caught
|
||||
/// when a later column happened to have no usable default. This compares the
|
||||
/// list against the live schema so the next one is caught by a test instead.
|
||||
#[rstest]
|
||||
fn every_copied_table_lists_every_one_of_its_columns(store: TestStore) {
|
||||
let conn = Connection::open(store.path.join("store.db")).unwrap();
|
||||
for (table, columns) in GRAPH_TABLE_COLUMNS {
|
||||
let listed: HashSet<&str> = columns.split(',').map(str::trim).collect();
|
||||
let mut stmt = conn.prepare("SELECT name FROM pragma_table_info(?1)").unwrap();
|
||||
let actual: Vec<String> = stmt
|
||||
.query_map(params![table], |row| row.get::<_, String>(0))
|
||||
.unwrap()
|
||||
.collect::<Result<_, _>>()
|
||||
.unwrap();
|
||||
|
||||
assert!(!actual.is_empty(), "{table} has no columns — wrong table name?");
|
||||
for column in &actual {
|
||||
assert!(
|
||||
listed.contains(column.as_str()),
|
||||
"{table}.{column} exists but GRAPH_TABLE_COLUMNS does not copy it"
|
||||
);
|
||||
}
|
||||
let tx = conn.transaction()?;
|
||||
for table in GRAPH_TABLES {
|
||||
let columns = tx
|
||||
.prepare("SELECT name FROM pragma_table_info(?1, 'main')")?
|
||||
.query_map(params![table], |row| row.get::<_, String>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
.join(", ");
|
||||
// sql-literal-ok: `table` is one of this module's own `&'static str`s
|
||||
// and `columns` are the schema's own column names; SQLite will not
|
||||
// bind an identifier, and nothing outside this file reaches either.
|
||||
tx.execute(
|
||||
&format!("INSERT INTO {table} ({columns}) SELECT {columns} FROM source_db.{table}"),
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
|
||||
conn.execute("DETACH DATABASE source_db", [])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,8 @@ pub enum StoreError {
|
||||
ExistsNotDirectory(PathBuf),
|
||||
#[error("a store already exists at '{0}'; use `syn` to open it")]
|
||||
AlreadyExists(PathBuf),
|
||||
#[error("store path '{0}' is not valid UTF-8")]
|
||||
NonUtf8Path(PathBuf),
|
||||
#[error("failed to create store directory: {0}")]
|
||||
CreateDir(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
@@ -354,8 +356,8 @@ pub struct Store {
|
||||
|
||||
impl Store {
|
||||
/// Path to the SQLite database file within this store directory.
|
||||
pub fn db_path(&self) -> String {
|
||||
self.path.join("store.db").to_str().expect("store path is valid UTF-8").to_string()
|
||||
pub fn db_path(&self) -> PathBuf {
|
||||
self.path.join("store.db")
|
||||
}
|
||||
|
||||
/// Run `f` against a single transaction, shared by every sub-store method
|
||||
@@ -395,7 +397,7 @@ impl Store {
|
||||
where
|
||||
E: From<rusqlite::Error>,
|
||||
{
|
||||
let result = batch_on(&self.path.join("store.db"), f);
|
||||
let result = batch_on(&self.db_path(), f);
|
||||
// The commit is where a change becomes true, so it is also where it is
|
||||
// announced — see `DocumentStore`'s `pending`. Both batch entry points
|
||||
// do this, because either one may be the transaction the write
|
||||
|
||||
Reference in new issue
Block a user