Chapter 1 · Session 5
Plan the tables in plain English
Your intent page already names the tables, and your naming standard already names their contents. Claude Code turns the two into a table plan you can read without knowing any SQL; you check it with the person who makes the decision, before a single table exists.
30 min2 stepsNo SQL yet
By the end of this chapter you can
- Say why the tables come before any screen, and what it costs to get them wrong.
- Have Claude Code draft a table plan from docs/INTENT.md and docs/naming-standard.md.
- Check the plan: every table sorted into reference, people, things that move, events and decisions.
Why the schema comes first
A screen is a view of data. If the data is shaped wrongly, every screen, report, access rule and integration built on it carries the mistake, and fixing it later means rebuilding all of them. The tables are the cheapest place to get it right. They also give Claude Code fixed ground: it can draft a screen in minutes, but it must never invent a new place to keep data each time it does [1].
Every table is one of five kinds
Read your intent and underline three kinds of words. Nouns you keep a list of (presses, parts, lots) become reference tables. Moments that happen many times (a first-piece result, an hourly reading) become event tables, one row per moment. The decision itself (hold or release) becomes its own table, so who decided, when and why is never lost.
| Kind | What it holds | Changes | Stamping plant tables |
|---|---|---|---|
| Reference | The plant's lists: sites, equipment, parts, limits | Rarely; by a manager | sites, equipment, parts, characteristics |
| People | Who belongs where, with which role | When people join, move or leave | memberships (sign-in accounts live in Supabase) |
| Things that move | Work flowing through the plant | Created every shift | lots |
| Events | What happened, when, recorded by whom | Never: new rows only | inspections |
| Decisions | What was decided, by whom, why | Never: new rows only | holds |
Name them in the language manufacturing already shares. ISA-95 (IEC 62264) gives the equipment levels (enterprise, site, area, work centre, work unit) and the things that move (material lots, personnel, equipment, results of work) [2]. Your naming standard from Session 4 already follows it, so the plan below asks Claude Code to use it.
Ask Claude Code for a table plan, not tables
10 minutesWhy
Asking for SQL straight away gets you a plausible schema you cannot check. Asking first for a plan in plain English gets you something you and the decision-maker can read in ten minutes and correct for free. Corrections now cost a sentence; corrections after screens exist cost days.
Do this
cd ~/code/acme-platform && git switch main && git pull && claudeRead docs/INTENT.md and docs/naming-standard.md. Do not write any SQL yet.
On a new branch schema/plan, write docs/SCHEMA-PLAN.md: the tables this intent needs, in plain English, for someone who does not write code. For each table give:
- its name (lower case, words joined by underscores, following the naming standard),
- its kind: reference, people, thing that moves, event, or decision,
- one sentence on what one row means ("one row is one first-piece result"),
- its columns, each with what it holds, its unit if it is a measurement, and whether it can be empty,
- which other tables it points to,
- the rule that must never be broken (for example "an upper limit is always above the lower limit").
Rules for the plan:
- Every table has a site so access rules can be one simple rule per table later.
- Events and decisions are never changed or deleted: a correction is a new row that points at the one it corrects and says why.
- Times include the time zone. Measurements are exact decimals with the unit in the column name (value_mm). Money is whole cents.
- Only tables the intent needs. List anything you were tempted to add under "Not now, and why".
- End with "Questions for the decision-maker": anything the intent does not settle.
Then open a pull request titled "Schema plan" and show me the link.You will see recreated screen
- It reads your documents before writing. If it does not, say: Read docs/INTENT.md and docs/naming-standard.md first.
- Each table in plain words: what one row means, and the rule it must keep.
- The questions are the most valuable part: answer them, do not skip them.
Check it worked
The pull request has one new file, docs/SCHEMA-PLAN.md. Every table has a kind, a one-row sentence and a rule. There is a Not now list and a Questions list.
If it goes wrong
Claude Code wrote SQL anyway
Say: Remove the SQL. I need the plan in plain English first, as asked. A plan you cannot read is not a plan you can check.
The plan has tables the intent never mentions (users, settings, audit_log, notifications)
Say: Move every table the intent does not need to Not now, with the reason. Sign-in accounts already exist in Supabase; the access rules in Session 8 add what is needed.
It says it cannot find docs/naming-standard.md
The naming session is not merged yet. Merge it first, or this plan will use names you change later, and every table built on them changes too.
Check the plan with the person who decides
20 minutesWhy
The person who makes the decision every day knows things the intent page left out: whether a lot can span two presses, whether a hold can be lifted by the same person. Each of those is a rule in a table. Finding it now costs a conversation; finding it after go-live costs a migration, a data fix and a retest.
Do this
Sit with the decision-maker and read docs/SCHEMA-PLAN.md on GitHub together. For each table, ask:
- Is this one row what you would call one thing? ("One row is one lot." Is it?)
- Is anything you write down today missing?
- Is the rule right? What happens on the day it is broken?
Answer the questions at the end. Then give Claude Code the answers, in their words:
The quality lead answered the questions in docs/SCHEMA-PLAN.md:
1. <paste their answer>
2. <paste their answer>
They also said: <paste anything else they changed>.
Update the plan to match, add a line "Checked with <their role> on <today's date>" at the top, and push to the same pull request.When the plan is right, owner two approves and the pull request merges.
You will see recreated screen
- The sign-off line: who checked it, and when.
- A rule that came from the conversation, not from the intent. This is what the step is for.
Check it worked
docs/SCHEMA-PLAN.md is merged on main, signed off with the decision-maker's role and the date, with no open questions.
Fastest path
If the decision-maker cannot meet, send them the link to the file on GitHub with the questions copied into the email. Do not write the tables until the answers are back: guessing here is the most expensive shortcut in the course.
If it goes wrong
The decision-maker wants screens, not tables
Show them one row in plain words: "One row is one hold: lot L-2041, held by you at 06:12 because the flange was 0.04 mm high." Ask if that is everything they would want to see later. That is a screen they can picture.
Knowledge check
In the intent 'the quality lead decides whether to hold a lot from first-piece results', what does 'first-piece results' become?
Knowledge check
Why ask Claude Code for a plain-English plan before any SQL?
References
- E. F. Codd, A relational model of data for large shared data banks, Communications of the ACM, 1970. https://dl.acm.org/doi/10.1145/362384.362685
- ISA: ISA-95 standard, Enterprise-Control System Integration. https://www.isa.org/standards-and-publications/isa-standards/isa-95-standard
- OPC Foundation: ISA-95 Common Object Model (OPC 10030). https://opcfoundation.org/markets-collaboration/isa-95/
Chapter 2 · Session 5
The tables, the rules they keep, and the tests that prove it
One prompt turns the signed-off plan into a migration (a file that builds the tables), the tests that prove the database refuses bad data, and the check that runs them on every change. You read Claude Code's plain-English explanation; GitHub runs the proof.
40 min3 stepsThe schema testing protocol
By the end of this chapter you can
- Have Claude Code write the migration, its tests and the CI check in one pull request.
- Read a migration through Claude Code's explanation, against seven questions.
- Know what the schema tests prove and why each one exists.
Rules the database keeps
A rule written in a screen protects one screen. A rule written in the table protects every screen, import and agent that will ever write to it, including the ones nobody has built yet. Postgres, the database inside Supabase, can refuse a bad row before it is stored [1]:
| Rule | In plain words | Stamping plant example |
|---|---|---|
| Type | The right kind of value | value_mm is an exact decimal to the thousandth of a millimetre; times carry their time zone |
| Not null | It must be there | Every inspection has a value, a lot and who recorded it |
| Check | In range, or from a list | action is hold or release; lower_mm is below upper_mm |
| Foreign key | It refers to something real | An inspection's lot must exist |
| Unique | No duplicates | One lot code per lot |
| Append-only trigger | Records of what happened are never changed | Updating or deleting an inspection is refused |
Times use timestamptz so a night shift across midnight or a clock change never scrambles the order [2]. Measurements use numeric, so 12.030 is stored as exactly 12.030 [3]. Records of what happened are append-only: the US FDA's rule for electronic records, 21 CFR Part 11, asks for audit trails that keep earlier values [4], and the simplest way to keep them is never to change a row at all.
The schema testing protocol
These are the tests every schema change in this course must pass, on a database built from nothing, before it can merge. Each one is there because we shipped without it once and paid for it:
| Test | What it proves | Why it is here |
|---|---|---|
| Rebuild from nothing | The migration files alone build the whole database | We merged a change that added ten columns and no migration. It worked on the developer's machine and failed everywhere else with "column does not exist". A database rebuilt from the files alone catches it before merge |
| Access rules on every table | No table is readable through the website's public key without a rule | A Supabase table without row-level security can be read by anyone who has the site's public key, which every browser has. In a prior build we found 376 of 449 server routes answering with no sign-in check, some for up to 87 days. This test makes the same mistake impossible for tables |
| Every table has a primary key | Every row can be found and referred to | Without one, duplicates creep in and corrections cannot point at the row they correct |
| Bad rows are refused | One test per rule: a wrong value, a missing value, a broken reference, a duplicate | A rule nobody tests is a rule an agent can quietly remove in a later change |
| History cannot change | An update or delete on an event or decision table fails | One edited record is enough to fail an audit |
| Names follow the standard | Every table and column name matches docs/naming-standard.md | Names are forever: renaming later breaks every screen and query that uses them |
One prompt: the migration, its tests and the check
15 minutesWhy
Writing the tables, the tests and the CI check in one pull request means the proof arrives with the change, and you never have a schema that nothing tests. One complete prompt also replaces the dozen back-and-forth messages it takes to add each rule as you think of it.
Do this
Read docs/SCHEMA-PLAN.md (signed off), docs/naming-standard.md and docs/INTENT.md.
On a new branch schema/first-tables:
1. If there is no supabase/ folder, run npx supabase init. Then run npx supabase migration new create_first_tables and write the tables from the plan into that file:
- every table in the public schema, with a primary key (bigint generated always as identity) and a site_id referencing sites;
- times as timestamptz, measurements as numeric with the unit in the column name, money as integer cents;
- not null, check, foreign key and unique constraints for every rule in the plan;
- for event and decision tables: corrects_id and correction_reason columns (both set or both empty), and a trigger that refuses update and delete, using one function public.append_only() with set search_path = '';
- views for current state (such as each lot's status) created with (security_invoker = true);
- row-level security turned on for every table, with no policies yet (access rules come in Session 8, so for now nothing is readable through the website's keys, which is what we want);
- every event table records two times: when it happened (recorded_at) and when it was typed in (created_at, default now()), so late entries can be seen;
- a tag_aliases table holding docs/names/aliases.csv (legacy name, standard path, unit, source system), with the standard path checked against the naming standard;
- insert the reference rows the plan names for site cle (Cleveland).
2. Write pgTAP tests in supabase/tests/schema.test.sql proving: every public table exists, has a primary key and has row-level security on; every table and column name matches the naming standard; and one test per rule that a bad row is refused (wrong value, missing value, reference to nothing, duplicate), plus update and delete refused on each event and decision table.
3. Add .github/workflows/schema.yml that, on every pull request, starts a fresh Supabase database in GitHub Actions with the Supabase CLI, applies every migration and runs supabase test db. Follow Supabase's guide for testing in GitHub Actions.
4. Do not connect to or change the live project.
Push, open a pull request titled "First tables", wait for the schema check to finish, and tell me the result in plain words. If it fails, fix it and try again before reporting.You will see recreated screen
- The migration file: its name starts with the date and time, so files always run in order.
- A decision table: every rule from the plan is in the table itself.
- The proof: tests that try to break the rules and must be refused.
Check it worked
Pull request First tables is green on GitHub, and Claude Code's summary says how many tests ran and how many tried bad data.
Fastest path
"Wait for the check and fix it before reporting" in the prompt saves a whole round trip: Claude Code reads the failure and fixes it while you do something else.
If it goes wrong
CI fails with: relation "auth.users" does not exist
The workflow started a plain Postgres, which has no Supabase sign-in tables. Say: Start the database in CI with the Supabase CLI (supabase db start), not a plain postgres service, so auth.users exists.
Claude Code turned on row-level security and also added policies that let everyone read
Say: Remove every policy. Access rules come from the role matrix (Session 7) in Session 8. Until then, no policies. A policy written before the matrix is a guess about who may see the plant's data.
Claude Code tries to run supabase db push or link the live project
The deny rule from Session 1 stops it. Say: Do not touch the live project. I apply migrations myself after merge.
It reports success but the check on GitHub is red
Say: The schema check on the pull request is red. Run gh pr checks, read the failed log, fix the cause and wait for green before you report. Then check the pull request yourself. We learned to trust the check on GitHub, never the summary.
Read the migration through Claude Code's eyes
15 minutesWhy
You do not need to read SQL to review a schema. You need to know whether it does what the plan says and nothing more. Asking Claude Code to explain it table by table, against seven fixed questions, turns a page of code into yes-or-no answers you can check against the plan, and catches the plausible mistakes agents make.
Do this
Explain the migration in pull request "First tables" to me table by table, in plain English, as if to the quality lead. Then answer each question below with Yes or No, the line number that shows it, and anything I should worry about:
1. Does every table come from docs/SCHEMA-PLAN.md, and is nothing added that the plan does not have?
2. Does every table have a primary key, and every reference a foreign key?
3. Are times timestamptz, measurements numeric with the unit in the name, and money whole cents?
4. Does every value chosen from a list have a check?
5. Are event and decision tables append-only, with the trigger, and do corrections have to say why?
6. Is row-level security on for every table, with no policies yet?
7. Does any statement drop, rename or rewrite something that could already hold data?
Do not change anything. If any answer is No, say what you would change and wait.You will see recreated screen
- Seven answers with line numbers: each one can be checked in the Files changed tab.
- The notes are where the real findings are. This one is a question for the decision-maker, not a bug.
Check it worked
All seven answers are Yes (question 7: nothing dropped or renamed). Any note has been answered or turned into a change.
If it goes wrong
An answer is No
Say: Make the change you described, push it, wait for the check to be green, then answer the seven questions again.
Question 7 lists a drop or rename on a later migration
Stop. Data could be lost. Ask: What data is in that table on the live project today, and how does this change keep it? If the answer is not clear, do not merge: ask in office hours.
Knowledge check
Where should 'a hold must have a reason' be enforced so it holds for every writer?
Knowledge check
Why does the migration turn on row-level security with no policies yet?
References
- PostgreSQL Documentation: Constraints. https://www.postgresql.org/docs/current/ddl-constraints.html
- PostgreSQL Documentation: Date/Time Types. https://www.postgresql.org/docs/current/datatype-datetime.html
- PostgreSQL Documentation: Numeric Types. https://www.postgresql.org/docs/current/datatype-numeric.html
- eCFR: 21 CFR Part 11, Electronic Records; Electronic Signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
- Supabase Docs: Testing your database (pgTAP and GitHub Actions). https://supabase.com/docs/guides/database/testing
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
Chapter 3 · Session 5
Apply it, see it, and change it safely
A person, not an agent, applies the merged migration to the live database. Then you see the tables in Supabase, ask Supabase's own advisor to check them, and learn the one way a table is ever changed again.
35 min3 stepsEnds with a gate
By the end of this chapter you can
- Apply a merged migration to the live project from your own computer, typing the password yourself.
- Check the result in the Table Editor and the Security Advisor.
- Change an applied table the only safe way: a new migration.
Merge, then apply it to the live database yourself
10 minutesWhy
The live database holds the plant's records. Changing it is the one action this course keeps for a person: the settings from Session 1 forbid Claude Code to do it, and the password comes from the password manager, typed by you. Applying only after merge means the live database always matches what main says it should be.
Do this
Owner two approves pull request First tables; merge it. Then, in a terminal (not inside Claude Code):
cd ~/code/acme-platform && git switch main && git pullnpx supabase loginnpx supabase link --project-ref abcdefghijklmnopqrstIt asks for the database password: copy it from the password manager entry Supabase: acme-platform-prod database password. Nothing shows as you paste; press Enter. Then see what will be applied, and apply it:
npx supabase migration listnpx supabase db pushYou will see recreated screen
- Local only: on main, not yet live. This is what will be applied.
- It lists every file it will apply. If it lists one you do not expect, answer n and ask why.
Check it worked
Run npx supabase migration list again: the file now has the same time under Local and Remote.
If it goes wrong
Remote migration versions not found in local migrations directory
Someone changed the live database outside the files, or an applied migration file was renamed or deleted. Do not force anything. In Claude Code: supabase db push says remote migration versions are not in the local directory. Explain in plain words which versions differ and what each one did, without changing the live project. Then decide with owner two.
password authentication failed
Copy the password again from the password manager (no spaces at either end). If it still fails, reset it in Supabase (Project Settings, Database) and save the new one in the password manager. Nothing else uses it.
A page works in the preview but fails on the live site with "column does not exist"
The migration was merged but never applied to the live project. Run npx supabase migration list: anything under Local but not Remote is missing. Apply it with npx supabase db push. Our live database once fell nine migrations behind main, the oldest seven weeks old; Session 11 makes the deploy apply them automatically and adds a daily check.
failed to connect to the database, or a network error
Try again on a different network (company networks sometimes block the database port). If it still fails, ask IT whether outbound connections to Supabase are allowed: Session 21's IT package lists what is needed.
See the tables, and let Supabase check them
10 minutesWhy
Seeing the tables in the dashboard confirms the live database is what the files say. Supabase's Security Advisor is an independent check: it looks for the mistakes that expose data, such as a table without row-level security or a view that ignores it, which is exactly what the tests are meant to prevent. Two checks that agree are worth more than one.
Do this
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/editor
The Table Editor: your tables, each marked with row-level security on.
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/advisors/security
The Security Advisor: choose Rerun linter.
And one question in the SQL editor, which must return no rows:
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/sql/new
Open a new query, paste the text below, and press Run.
-- Tables in the public schema without row-level security. Must return no rows.
select tablename from pg_tables
where schemaname = 'public' and rowsecurity = false;You will see recreated screen
| id | site_id | lot_id | action | reason | decided_by | decided_at |
|---|
- Expected until Session 8: on, with no policies.
- Empty: test data comes in Session 6.
You will see recreated screen
- No errors. An error here (RLS disabled, security definer view) means stop and fix before anything else.
- This note is expected now and goes away in Session 8.
Check it worked
Every table you planned is in the Table Editor; the Security Advisor shows no errors; the SQL query returns no rows.
If it goes wrong
The Advisor warns: Function Search Path Mutable
A function was created without a fixed search path, which a later change could exploit. In Claude Code: The Security Advisor says function search path mutable for
The Advisor shows Security Definer View
A view is running with its owner's rights and ignoring access rules. In Claude Code: Write a new migration that recreates view
My screens show no data
Correct for now: row-level security is on with no policies, so nothing is readable through the website. Session 8 adds the access rules.
Practise a change: a new rule as a new migration
15 minutesWhy
Tables change: a new column, a new rule from the decision-maker. Doing one small change now, the right way, sets the habit before there is data to lose. It also shows the safety net working: the tests from Step 3 run again, so a change that breaks an old rule is caught before it merges.
Do this
The quality lead says: a lot cannot be released by the same person who held it.
On a new branch schema/release-by-other, write this as a NEW migration (npx supabase migration new release_by_other); do not edit any existing migration. Add tests in supabase/tests/ that prove a release by the holder is refused and a release by someone else is accepted. Update docs/SCHEMA-PLAN.md to record the rule. Push, open a pull request titled "Release by another person", wait for the schema check, and tell me the result.Review it with the seven questions (Step 4), merge, and apply it as in Step 5.
You will see recreated screen
- A new file with a later time. The first migration is untouched.
- The old tests passing is the point: the change did not break an earlier rule.
Check it worked
npx supabase migration list shows two migrations, both under Local and Remote.
If it goes wrong
Claude Code edited the first migration instead
Say: Revert the change to the applied migration. Every change to a live table is a new migration. If it was merged, write a new migration that makes the change, and never apply the edited file.
Two branches each added a migration and CI fails after merging both
Migrations run in time order. When two agents or people add migrations in parallel, the later-merged one may need a newer time. Say: Rename the migration on this branch with a new timestamp after the latest on main, re-run the tests, and push. Only do this for migrations not yet applied to the live project.
After merging main into your branch, a column or test you added has gone
Someone undid a batch of changes on main and the undo took yours with it; no conflict is reported. Say: I just merged main. List every schema change and test this branch added and confirm each is still there. If any disappeared, find the commit that removed it and tell me before changing anything. A test for every rule you care about turns this silent loss into a red check.
A table was created by clicking in the dashboard
The files no longer rebuild the live database. Say: The live project has a table
Knowledge check
A column in an applied migration needs a new check. What do you do?
Knowledge check
Who runs supabase db push on the live project, and when?
References
- Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations
- Supabase CLI reference: supabase db push. https://supabase.com/docs/reference/cli/supabase-db-push
- Supabase Docs: Database advisors. https://supabase.com/docs/guides/database/database-advisors
Chapter 4 · 12 questions · 80% passes
Final assessment
Twelve questions across the element. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.
15 min12 questions≈ 15 minutesRetake allowed
Your result
CivOps AI Academy
Schema First: the Data Your Plant Runs On, as Tables
Element F03 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.