Skip to main content

Module schema_diff

Module schema_diff 

Source
Expand description

Schema diff engine — EXPLAIN ALTER FOR runtime.

Computes the set of ALTER TABLE operations that would close the gap between an existing CollectionContract and the column shape of a new CreateTableQuery. Used by the EXPLAIN ALTER FOR SQL command exposed at the parser / executor boundary.

Pure logic — zero side effects, no DB access. The executor loads the current contract, calls compute_column_diff, and formats the result via format_as_sql / format_as_json.

§Design highlights

  • Equivalence check matches apply_alter_operations_to_contract’s semantics so the round-trip property holds: applying the diff to a clone of current produces a contract byte-equal to the target.
  • sql_type is Option<SqlTypeName> in the live contract (legacy tables don’t carry it). When the current side has None, we fall back to comparing the legacy data_type string instead of declaring everything a TypeChange.
  • Rename detection is consultative. Even when the heuristic is high-confidence, the SQL output still emits DROP + ADD plus a -- hint: comment. Only a human (or a client with more context) confirms.
  • Three confidence tiers explicit:
    • Highsql_type + every constraint + default match
    • Mediumsql_type + every constraint match
    • Low → only sql_type matches (constraints differ) Lower than Low produces no candidate.

§Out of scope (v1)

  • Indexes (CREATE INDEX) — not in CollectionContract.
  • Constraint-only changes (e.g. NOT NULL added with the same type) — folded into TypeChange for now.
  • default_ttl_ms, context_index_fields, timestamps from CreateTableQuery — ignored. Reserved for v2 once the corresponding AlterOperation variants exist.
  • Constraint normalisation (e.g. 'foo' vs foo) — best- effort string compare with leading/trailing-quote strip.

Structs§

DiffSummary
Per-category counters for the diff. Useful for dashboards and CI guardrails (“fail the build if a migration would drop more than N columns”).
RenameCandidate
Heuristic match between an unpaired DropColumn and an unpaired AddColumn. Always advisory — clients decide.
SchemaDiff
Aggregate result of a column-level schema diff.

Enums§

DiffOp
One operation in a schema diff.
RenameConfidence

Functions§

column_equivalent
Returns true when a live current column and a target CreateColumnDef describe the same column shape.
compute_column_diff
Compute the column-level diff between a live current contract and a target list of CreateColumnDefs parsed from the embedded CREATE TABLE statement.
format_as_json
Format a SchemaDiff as a structured JSON string. Hand- rolled emitter so this module stays free of serde_json — reddb’s existing crate::serde_json module provides the tiny JSON writer the rest of the codebase uses, but here we just produce text directly because the schema is small and stable.
format_as_sql
Format a SchemaDiff as a copy-paste-friendly SQL string.