Blog
Ghostrow Labs

How Ghostrow keeps every constraint

Parents before children, retries for unique and CHECK rules, sums and products by construction, and a separate validator that re-checks every row before anything is written.

Generated data that breaks a foreign key is worse than no data: the load fails, or it succeeds and your tests pass for the wrong reasons. This post walks through how ghostrow seed makes rows that satisfy a schema, and how it checks that it did. Everything below comes from the CLI source and from runs we did for this post on the Free plan.

The setup

We used the shop schema from our test fixtures, without its sixth table so that it fits Free's five-table limit:

ghostrow --schema shop5.sql seed --rows 200 --seed 7 --out out
ghostrow seed · shop5.sql · seed 7 · Free
  products                            67 rows
  tenants                              8 rows
  customers                           23 rows
  orders                              67 rows
  order_lines                        200 rows
  wrote 5 CSV files to out
  wrote 365 rows, 0 violations · 4 foreign keys, 7 unique, 5 check, 3 cross-column rules verified

Two things in that output need explaining: why the row counts differ, and what "verified" means.

Parents before children

Generation order comes from the foreign keys in the rules. A table is ready when every table it references is done, and we take ready tables in alphabetical order so the order is stable between runs. Self-references are ignored for ordering, because a row can point at an earlier row of its own table.

Cycles are the interesting case. If every remaining table is waiting on another, the generator looks for a foreign key whose columns are all nullable, picks the one with the alphabetically first rule id, and marks it deferred. That column is then left empty. We tried it with two tables that point at each other through nullable keys:

==> a.csv <==
id,b_id
1,

==> b.csv <==
id,a_id
1,1
2,1

If the cycle has no nullable edge there is no valid insert order, and we say so instead of guessing:

ghostrow: Tables a, b reference each other through NOT NULL foreign keys, so no insert order exists.
  Make one of those foreign keys nullable or deferrable, or disable one fk rule in ghostrow.rules.yaml.

That run exits with code 2, the code we use for "these constraints cannot be satisfied". Nothing is written.

Row counts follow the shape of the schema

--rows is the row count for the largest table, and the other tables scale from it. For each table we compute its height: the length of the longest chain of tables that reference it, directly or through other tables, with tables that nothing references at zero. A table at height h gets ceil(rows / 3^h) rows. In the shop schema order_lines is a leaf, orders and products sit one level up, customers two, and tenants three. With --rows 200 that gives 200, 67, 67, 23 and 8, which matches the output above.

The factor of three is a constant in the source, not something measured from your data. --table name=n and a rows entry in ghostrow.rules.yaml override it per table. Without --rows the default is 500. One more adjustment: if a foreign key is also unique, which makes the relation one-to-one, the child table is capped at the parent's row count.

Every parent gets a child

When child rows pick a parent, the first rows go to the parents in order. With at least as many children as parents, every parent is used once before any parent is used twice. After that, the choice is skewed toward earlier parents (a uniform random number raised to the power 1.5), so some parents end up with many children and some with few. We checked the files from the run above: all 8 tenants have a customer, all 23 customers have an order, all 67 orders have a line, and all 67 products appear on a line.

There is a caveat. If the foreign key column is nullable, a row can get NULL instead of a parent, so "every parent gets a child" is exact for required references and only likely for optional ones. For composite keys the whole tuple comes from one parent row, never from columns of different rows.

Retries for unique and CHECK rules

Each cell is a pure function of the seed, the table, the column, the row number and the attempt number. That is why one seed gives one set of files: we generated the shop data twice with seed 7 and compared the five CSV files byte for byte.

A candidate row is accepted only if it reuses no unique value and passes every CHECK expression we could parse. If it fails, we try again with the next attempt number, up to 30 times. From the third attempt on, a unique text value gets a suffix made from the row number, and an email gets it before the @. If a row still cannot be made, we stop and name the cause. Here is a column that must be unique but whose CHECK allows three values, asked for five rows:

ghostrow: Could not generate row 4 of t: no unused value left for unique status.
  Lower --rows or --table t=…, or relax the rule in ghostrow.rules.yaml.

That is exit code 2 again, and it is the right answer: the schema cannot hold five rows. When you insert into a database that already has data, existing values of unique columns are read first and counted as used, and ids continue after the current maximum.

Rules between columns

Some constraints are not in the schema at all. The dry run lists what Ghostrow inferred for the shop tables:

order_lines: unit_price = products.price of the referenced row
order_lines: amount = quantity × unit_price
orders: orders.total = sum of order_lines.amount
orders: shipped_at is not before placed_at

Each kind is satisfied in its own way:

  • Copy. A value is taken from the referenced row. A line's unit_price is its product's price.
  • Product. amount is quantity × unit_price, rounded to the column's scale.
  • Order. If the later column came out earlier than the other, we move the later one forward by a random amount. CHECKs that compare two columns, like ends_at > starts_at, use the same mechanism.
  • Sum. A parent's total is written after every table exists, as the sum of its child rows. We add in integer units of the column's scale, up to six decimals, so floating point drift cannot leave a total off by a cent.

Totals are last because a parent's children do not exist yet when the parent row is made. We confirmed on the files above that each order's total equals the sum of its lines, every line's price equals its product's price, and no order ships before it is placed.

A second pair of eyes

All of that is generation. The part we trust most is what happens next. Before any file or database write, validate() in gen/validate.ts walks the finished rows without looking at how they were made. It checks NOT NULL, maximum lengths and enum membership for every column. Then it checks every enabled rule: uniqueness, foreign keys against the parent rows, each CHECK expression, orderings, products (within the column's precision), copies, and sums (within half a cent). It never repairs anything.

If it finds a violation, the run stops and nothing is written. The error says how many generated rows would break a rule, lists the first eight with their table, row number and rule, and points you to ghostrow.rules.yaml. The exit code is 2, the same as an unsatisfiable schema. We did not trigger this path in the runs for this post, because the generator satisfies the rules by construction; the validator is there for the day it does not.

On the clean path, the counts at the end of the output are what the validator checked: 4 foreign keys, 7 unique, 5 check and 3 cross-column rules. The checker is separate from the generator on purpose. A bug in how we build a row should show up as a failed check, not as a quietly invalid file. Haunt and Twin run the same validator over their own output.

If you edit ghostrow.rules.yaml, for example to add total >= 0 as a CHECK, the generator and the validator both pick it up, because they read the same rules.

All posts