Rzemiosło · The Craft
What is The CraftLevelsGet startedChapters Search Download PLEN
Rules of chapter 04
Level 2 · Technical Chapter deep-dive

In the core the rules are short and hard. Here is what stands behind them: the why, examples and stories from real projects. Rule quotes come straight from the core.

04 — Scripts and databases

Chapter 04 covers the places where a mistake doesn’t break how the site looks but breaks the data — and data, unlike code, has no “undo” button in git. That’s why the chapter’s two commandments sound like caution but in practice are mechanisms: Dry-run — A “dry” run — the script shows what it WOULD do but changes nothing. You see the effects before executing; a data change happens only after deliberate confirmation. more in the glossary → is the default, and a Backup — A copy of your data saved earlier, which you return to when something goes wrong. It’s the only way to undo a change to data — code comes back from git, data only from a backup. more in the glossary → is how you Rollback — Reverting a change to the previous, working state — “Ctrl+Z” for a deployment. When a new version breaks production, a rollback restores the previous one in seconds instead of fixing in a panic. more in the glossary →. Below is what stands behind the rules.

The plan first, then the write

Dry-run by default. ↗

Every script that changes data by default only shows the plan: what it will do, how many rows it will touch, where. Writing is switched on deliberately with a flag:

python -m scripts.x.do_thing            # dry-run: prints the plan
python -m scripts.x.do_thing --execute  # only now does it write

In the reference project this habit saved the data more than once: you see “4 OK, 0 skipped” — or “4,000 to delete” where you expected four — before anything is written. Inverting the default (safe mode without a flag, risky mode with one) means a mistyped command ends in a printout, not a loss.

Two runs, the same state

Idempotency — A property of an operation you can run many times with the same result — no duplication. Key for scripts and events: a re-run doesn’t break data. Like an “ON” switch. more in the glossary →. ↗

A script run twice should give the same result, not duplicated rows. It sounds theoretical, but in practice scripts get re-run all the time: the connection dropped, someone wasn’t sure it went through, the Deploy — Releasing a new version of the app “live”, where real people use it. It’s the moment a change reaches real people — which is why it happens only on an explicit “deploy”. more in the glossary → repeats a step. Writes like UPSERT — An “insert or update” write: if the record exists it’s updated, if not it’s added. It means a script run twice doesn’t create duplicates. more in the glossary → / UPSERT make a re-run safe. In the reference project the content loaders from an external database are explicitly idempotent — and that’s a condition for using them in a deploy.

A third rule from the same family: a script that cuts its scope (only the first N, a sample, skipped rows) says so. Silence reads as “I covered everything” — and you didn’t.

Automation doesn’t merge the catalog

Catalog-mutating operations stay out of automatic Pipeline — A chain of processing steps run in order, e.g. fetch → clean → enrich → check. When each step runs on its own and repeats safely, a failure halfway doesn’t mean starting from zero. more in the glossary → ↗

It’s good to group scripts by stage (setup, normalisation, enrichment, validation, deduplication) and chain them into pipelines run with one command. But operations that Merge — Combining the changes from one branch into another. A merge brings in every commit from the source branch — other people’s too — so first you check what exactly comes in. more in the glossary → or delete records in the catalog — deduplication, merges — stay out of the automation. They’re run by hand: dry-run → review the result → --execute. A nightly job has nobody to ask “are these two products really the same?”, and a wrong merge spreads into everything that depends on those records.

The environment in writing

The environment is written in CLAUDE.md ↗

Which interpreter, which virtual environment, which variables (e.g. PYTHONIOENCODING=utf-8 on Windows, without which non-ASCII characters crash the script). The assistant doesn’t guess the path to Python — A popular, readable programming language — The Craft’s default for scripts, data and the back end. A proven default: lots of ready tools and libraries, easy to drive with AI. more in the glossary → — it reads it from the constitution. Guessing ends with the script running in the wrong environment, with different library versions (01).

The same path, three different files

Absolute paths when a value crosses tools. ↗

This is one of the sneakiest traps of working with an assistant on Windows. Git Bash expands /tmp to its own temp directory; Python on Windows expands the same /tmp to <drive>:\tmp; PowerShell — somewhere else again. Pass a relative path from one tool to another and each reads and writes a different file: the Migration (database) — A controlled change to the database layout — adding a column, a table or moving data — step by step. Like a renovation to plan: rebuilding data in a set order so nothing “collapses”. more in the glossary → script quietly processes an empty database while your real copy sits untouched in another directory — and everything “passed”.

The fix: when a path (or any value) goes shell → interpreter → application, pass it as a full path (Z:/work/x.db, not /tmp/x.db), or expand it once and pass the expanded form. When a “did nothing” result surprises you, print os.path.abspath(p) / pwd -W in both tools and compare — it’s usually two tools disagreeing about where the path points.

Migrations only go forward

Forward-only migrations. ↗

There are no “down” migrations. One numbered file is one step forward. Reverse migrations look like a safety net, but they’re code almost nobody tests — and it runs at the worst possible moment, in the middle of an incident. Nor can they bring back data the “up” migration removed. So rolling back a schema means restoring a backup — a proven one, because you make it every time.

The backup is the undo button

Back up before every schema/data change on Environment (dev / prod) — Separate places where the app runs: “dev” for safe tests, “prod” for real users. Dev is a playground, prod is where real users are — the rules for each are completely different. more in the glossary → ↗

It isn’t caution but the rollback mechanism — without it, a migration “rollback” doesn’t exist. Backups are named clearly by reason (pre-deploy-*, pre-swap-*, replaced-prod-*), with a timestamp, and kept with a retention period (e.g. 14 days) so the directory doesn’t grow forever. The excuse “but this migration is only additive” doesn’t skip the backup: additive doesn’t protect against a bug in the data the migration fills in along the way.

Snapshot — A saved state of data from a specific moment — e.g. a database copy or a file of computed statistics. It speeds things up and keeps them safe, but is stale from the moment it’s taken — you need to know where fresh data comes from. more in the glossary → with .backup / VACUUM INTO, never cp/scp of a live database ↗

SQLite — The simplest database — the whole thing lives in one file, with no separate server. A great default to start: zero configuration, easy backup (you copy the file). As you grow, you migrate up. more in the glossary → in WAL — Write-Ahead Log: a database mode where changes go to a journal first, then to the data. Gives safety (recovery after a crash) and better read/write concurrency. more in the glossary → mode keeps the freshest changes in a separate file next to the main one. Copying just the .db file (cp, scp) while the server is running gives an inconsistent copy — the latest writes are missing, and sometimes it won’t even open. .backup is safe on a running database, and VACUUM INTO also gives you a defragmented copy. It’s one of the lessons that went into the reference project’s Runbook — A written step-by-step guide for production operations, with numbered lessons from incidents. The memory of outages can’t live in someone’s head — the next deploy starts by reading the runbook. more in the glossary → after a real incident (05).

Add first, remove later

Additive before destructive. ↗

ADD COLUMN is backward-compatible — old code that doesn’t know about the new column keeps working. A DROP or RENAME of a column that running code reads breaks it the moment the migration runs. And during a deploy there’s a brief moment when both versions of the code run, or old code runs on the new schema. So a destructive change is split across two deploys: first the code stops reading the column, and only in a later deploy does the column go.

Check what’s left after the operation

Check integrity after every data operation: ↗

PRAGMA integrity_check, PRAGMA foreign_key_check and the row counts of key tables — before and after. What matters is telling pre-existing noise (e.g. orphaned rows that were there before the operation and are still there after) from a regression (violations that weren’t there before). In the reference project the merged database had fewer violations than the local one — a sign the migration cleaned up rather than broke things. Without a “before” comparison you can’t tell.

A good pattern for data with history is the “active row” model: instead of overwriting a price, the old row is expired (expired_at) and a new one inserted; a partial unique Index (database) — A lookup in the database that makes searching instant instead of scanning everything in order. The first move for slow queries — like an index at the back of a book instead of reading 400 pages. more in the glossary → ensures one active row per key. History stays, and auditing comes for free (11).

A rehearsal on a copy, not just a plan

Rehearse a bulk or irreversible mutation on a fresh prod copy ↗

A dry-run shows the plan but doesn’t prove the result — and doesn’t reveal conflicts that only exist in real data. Examples from practice: a merge tool that wrongly reads an expired row as a conflict and deletes the wrong, active record; or a plan written against a snapshot whose identifiers have since drifted from production.

So before a bulk merge, deduplication or update in production: a copy of production via .backup → a run on the copy → check the counts, the integrity and hand-review the tricky cases → only then production. A copy with the same identifiers lets you rehearse exactly that run — far cheaper than a rollback. It’s the sibling of the release rehearsal on Preprod (staging) — A faithful copy of production with no real users, where you rehearse a deploy. A migration that fails on preprod is an ordinary Tuesday; in production it’s an incident. more in the glossary → (18).

The same discipline applies to processing sensitive data (e.g. anonymisation): a separate, idempotent script with a dry-run, a clear contract — “raw data in, data without personal information out” — and a test that checks it (09).