Four Ways to Seed a Postgres Database, and What Each Does When the Schema Moves

https://hackernoon.imgix.net/images/TPXPOQE1qBYc3ttNXigtSRtWznk1-7d13ag7.png

Add a mandatory column to a table that already holds rows, give it no default, and Postgres declines the migration outright.

ALTER TABLE users ADD COLUMN role text NOT NULL;ERROR: column "role" of relation "users" contains null values

Failing there is the good outcome, because it lands in the migration rather than in your seed data, with whoever ran the DDL standing right next to it when it happens.

Trouble starts with the version of that change somebody makes ten seconds later, having read the error and done the sensible thing.

ALTER TABLE users ADD COLUMN role text NOT NULL DEFAULT 'member';

Since Postgres 11 that form does not even rewrite the table, the default living in the catalogue rather than being stamped onto every existing row, so the migration goes green and the seed script runs afterwards none the wiser. If the script lists its columns by name without...

Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE

Read more