smartyfy.mrindigi.com

Databases & SQL Master Course — 069. Migration Tests and Backfills

Lesson 069 Migration Tests and Backfills

Prerequisites and objectives

You can inspect schemas and rehearse ALTER operations. You will now test a migration against historical edge cases, distinguish a truthful display placeholder from an invented fact, verify row preservation, and rebuild a dependent index. The complete table replacement happens only inside a disposable transaction that is rolled back.

Create the practice fixture

The legacy inventory contains four items: a normal title, a NULL title, a space-only title, and a padded title. Units total nine. The target policy requires nonblank display titles and nonnegative integer units. In this fictional application, Untitled item followed by the identifier is an explicitly approved display placeholder, not a claim about the item’s real name.

CREATE TABLE legacy_inventory (
 item_id INTEGER PRIMARY KEY,
 title TEXT,
 units INTEGER NOT NULL
);
CREATE INDEX idx_legacy_title ON legacy_inventory(title);
INSERT INTO legacy_inventory VALUES
 (1,'Notebook',4),(2,NULL,0),(3,'   ',2),(4,' Atlas ',3);

Inventory the historical cases

A migration that works on one clean row may fail on the data actually stored. Profile the source before copying it. Count missing and blank titles, inspect unusual storage types, and identify invalid quantities. Keep the source unchanged while deciding how each category should map to the new contract.

SELECT item_id FROM legacy_inventory WHERE title IS NULL OR length(trim(title))=0 ORDER BY item_id;
SELECT COUNT(*),SUM(units) FROM legacy_inventory;

Items two and three need the declared placeholder policy. Item four can have surrounding ordinary spaces removed. This transformation is intentionally about display text. It would be inappropriate to invent unknown measurements, legal names, or historical prices with a similar fallback merely to satisfy a constraint.

Rows 1–4 retain quantities 4, 0, 2, 3. Notebook stays Notebook; NULL becomes Untitled item 2; three spaces become Untitled item 3; padded Atlas becomes Atlas. Both sides contain four identical IDs and total nine units. Placeholders are labelled as an explicit display policy, not recovered names.
A backfill is a declared mapping, not just a successful copy. Check identities, transformed values, totals, constraints and dependent objects. Open full-size diagram

Rehearse replacement and backfill

Create the target table with its complete intended constraints, then copy explicitly named columns through the mapping. The target constraints validate the resulting rows. Compare identifiers and values before replacing the old table. This fixture has no foreign-key dependents or views, and one explicitly known index, so its reconstruction plan is deliberately small.

BEGIN;
CREATE TABLE replacement_inventory (
 item_id INTEGER PRIMARY KEY,
 title TEXT NOT NULL CHECK(length(trim(title))>0),
 units INTEGER NOT NULL CHECK(units>=0)
) STRICT;
INSERT INTO replacement_inventory(item_id,title,units)
SELECT item_id,
       COALESCE(NULLIF(trim(title),''),'Untitled item '||item_id),
       units
FROM legacy_inventory;
SELECT * FROM replacement_inventory ORDER BY item_id;
SELECT COUNT(*),SUM(units) FROM replacement_inventory;
DROP TABLE legacy_inventory;
ALTER TABLE replacement_inventory RENAME TO legacy_inventory;
CREATE INDEX idx_legacy_title ON legacy_inventory(title);
SELECT name FROM pragma_index_info('idx_legacy_title');
ROLLBACK;

The target has all four identifiers and the same nine units. The old table is removed only after the copy checks in this rehearsal; the replacement takes its name and the index is recreated. Rollback restores the original schema, index, and data. This is not a general production migration script for tables with unknown dependencies.

Verify more than counts

Equal row counts can hide one missing identifier and one unexpected identifier. Equal quantity totals can hide compensating mistakes. Use both-direction key comparisons, inspect representative transformed values, and retain row-level reconciliation where the stakes require it. A strong migration test checks identity, meaning, constraints, and dependent objects separately.

Also test future writes against the new schema. A successful historical copy proves only that those copied rows were accepted. The destination must reject new blank titles and negative stock if those remain forbidden. Testing the rule after migration catches accidentally omitted constraints in the replacement CREATE statement.

Choose a repeat and failure policy

A migration runner should know whether the migration has already been applied. Running a structural change twice is not automatically harmless. An existing replacement table, a partially completed manual attempt, or a different starting schema should trigger inspection rather than a broad IF NOT EXISTS that hides the mismatch.

For a larger database, plan batching, locks, disk space, backups, and application compatibility separately. This in-memory exercise proves logical behavior on a tiny fixture, not production throughput or crash recovery. Preserve an auditable record of the mapping and the original data when the transformation removes information such as surrounding spaces.

Four worked exercises

Exercise 1

Try copying the raw titles directly into the constrained target.

Worked solution
BEGIN;
CREATE TABLE replacement_inventory (
 item_id INTEGER PRIMARY KEY,
 title TEXT NOT NULL CHECK(length(trim(title))>0),
 units INTEGER NOT NULL CHECK(units>=0)
) STRICT;
INSERT INTO replacement_inventory SELECT item_id,title,units FROM legacy_inventory;
SELECT COUNT(*) FROM replacement_inventory;
ROLLBACK;

The raw copy fails on the NULL title. Under the ordinary statement behavior used here, the destination remains empty rather than keeping earlier rows from that failed INSERT. Profiling and an explicit mapping are necessary before attempting the full migration.

Exercise 2

Apply the approved title mapping and compare source and target identifiers in both directions.

Worked solution
BEGIN;
CREATE TABLE replacement_inventory (
 item_id INTEGER PRIMARY KEY,
 title TEXT NOT NULL CHECK(length(trim(title))>0),
 units INTEGER NOT NULL CHECK(units>=0)
) STRICT;
INSERT INTO replacement_inventory(item_id,title,units)
SELECT item_id,
       COALESCE(NULLIF(trim(title),''),'Untitled item '||item_id),
       units
FROM legacy_inventory;
SELECT item_id FROM legacy_inventory EXCEPT SELECT item_id FROM replacement_inventory;
SELECT item_id FROM replacement_inventory EXCEPT SELECT item_id FROM legacy_inventory;
ROLLBACK;

Both differences are empty, so no source identifier is missing and no unexpected target identifier appears. This is stronger than a count alone. The primary keys separately ensure that duplicate identifiers cannot conceal multiplicity differences.

Exercise 3

After a successful copy, test an invalid future negative quantity.

Worked solution
BEGIN;
CREATE TABLE replacement_inventory (
 item_id INTEGER PRIMARY KEY,
 title TEXT NOT NULL CHECK(length(trim(title))>0),
 units INTEGER NOT NULL CHECK(units>=0)
) STRICT;
INSERT INTO replacement_inventory(item_id,title,units)
SELECT item_id,
       COALESCE(NULLIF(trim(title),''),'Untitled item '||item_id),
       units
FROM legacy_inventory;
INSERT INTO replacement_inventory VALUES (5,'Marker',-1);
SELECT COUNT(*),SUM(units) FROM replacement_inventory;
ROLLBACK;

The target rejects the new invalid row and retains its four migrated items. This demonstrates ongoing enforcement rather than only historical acceptance. A migration should leave the destination ready to protect future data too.

Exercise 4

Prove that rollback restores the original padded and missing titles after the rehearsal mapping.

Worked solution
BEGIN;
CREATE TABLE replacement_inventory (
 item_id INTEGER PRIMARY KEY,
 title TEXT NOT NULL CHECK(length(trim(title))>0),
 units INTEGER NOT NULL CHECK(units>=0)
) STRICT;
INSERT INTO replacement_inventory(item_id,title,units)
SELECT item_id,
       COALESCE(NULLIF(trim(title),''),'Untitled item '||item_id),
       units
FROM legacy_inventory;
ROLLBACK;
SELECT item_id,title FROM legacy_inventory WHERE item_id IN (2,3,4) ORDER BY item_id;
SELECT COUNT(*) FROM sqlite_schema WHERE name='replacement_inventory';

The original source values remain, and the temporary replacement table is absent. This is a concrete recovery check for the active rehearsal transaction. It does not imply that the discarded original spellings can be reconstructed after a committed migration without retained evidence.

Knowledge check

Question 1

Why include NULL, blank, and padded titles in the fixture?

  1. They guarantee every possible production case is covered
  2. They exercise different historical mapping cases
  3. They remove the need for destination constraints
  4. They prove every title should be replaced
Answer and explanation

B. Representative edge cases expose gaps that a clean-only fixture misses.

Question 2

What makes Untitled item 2 acceptable here?

  1. It is an explicit display-placeholder policy
  2. It is guaranteed to be the item’s real name
  3. Any default is automatically truthful
  4. Its text contains a number
Answer and explanation

A. The lesson declares the meaning rather than pretending to recover unknown facts.

Question 3

Why compare identifiers in both directions?

  1. To verify that every mapped column has the correct value
  2. To replace all row-value checks
  3. To detect missing and unexpected identities
  4. To guarantee equal rows whenever the counts match
Answer and explanation

C. Counts alone can conceal substitutions between different identifiers.

Question 4

Why recreate the title index?

  1. Indexes automatically copy through INSERT SELECT
  2. Dropping its old table removes that dependent index
  3. The new primary key automatically replaces every secondary index
  4. Indexes are preserved whenever the replacement has the same columns
Answer and explanation

B. Schema dependencies need an explicit preservation or reconstruction plan.

Question 5

What does the tiny rehearsal fail to establish?

  1. The tested title mapping results
  2. The tested row and unit counts
  3. The tested negative-value rejection
  4. Production performance and complete operational recovery
Answer and explanation

D. Logical fixture tests are necessary but do not cover operational scale or every failure mode.

Pitfalls and summary

Do not hide dirty history with an unexplained default or trust counts alone. Profile first, define a truthful mapping, validate the constrained destination, preserve identities and dependencies, and test rollback. A migration is a change in both structure and meaning, so its evidence must cover both.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references