15 min read
Database migrations without losing data
In one sentence: A migration is a numbered file with one change to your tables, applied only once and in order. The database records the applied ones in a table, and each one goes in whole or not at all: the data that was already there stays.
What you will learn
- Explain why dropping the tables and creating them again stops working once there is real data.
- Write a migration runner of about 35 lines, with a table that records the applied ones and one transaction per migration.
- Add a NOT NULL column to a table with rows, in three steps, and plan a rename with expand and contract.
- Explain why an applied migration is never edited.
Before you start, read: 05-node-and-postgresql.md
The problem
Section titled “The problem”Ana wants the API to say how many units of each product are left: a new column, stock, in products. In lesson 4 and lesson 5, to change a table you edited db/schema.sql and ran npm run db:create, which drops the tables and creates them again.
Look at what that script does to a real order. With the API running, create one. Then stop the server with Ctrl + C, run db:create, start it again and ask for the order:
An order, before and after db:create
curl -s -w '\n' --json '{"productId":2,"quantity":1}' localhost:3000/v2/ordersnpm run db:createcurl -s -w '\n' localhost:3000/v2/orders/26What you will see:
{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T23:47:16.201Z"}
> shop-api@1.0.0 db:create> node --env-file-if-exists=.env scripts/create-db.ts
Tables created: 4 products, 3 categories and 25 orders{"type":"about:blank","title":"Not Found","status":404,"detail":"No such order"}Order 26 no longer exists: db:create leaves the shop as it was on day one.
With sample data it didn’t matter. With customers’ orders, you can’t delete them to add a column. And there’s another question: your database, the tests’ database and the production one need the same change. How does each one know which changes it’s missing?
The analogy
Section titled “The analogy”The analogy
Imagine renovating a house with the family living in it. Nobody tears it down to add an outlet. Each job goes on a numbered sheet: “1. Put up the walls,” “2. An outlet in the kitchen.” On the fridge, a list of the jobs already done.
The contractor looks at the list, does the missing jobs in order and writes each one down when it’s finished. If a job that was done turns out wrong, its sheet isn’t rewritten: another one is added, “3. Move the outlet.”
Where the analogy breaks down
- A job can be left half-done. A migration in your runner can’t: if it fails, nothing of it is left.
- In a house you can see whether the outlet is there. In a database you can’t: that’s why the list of what’s done lives inside it, in a table.
How it really works
Section titled “How it really works”A migration is a change, not the whole schema
Section titled “A migration is a change, not the whole schema”db/schema.sql goes away. In its place, a folder with two files:
Directorydb/
Directorymigrations/
- 001-shop.sql the tables from lessons 4 and 5
- 002-stock.sql the stock column
- seed.sql
Each file is a MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition: one change to your tables, in SQLSQL stands for Structured Query Language.The language for asking a database to read, add, change or delete the data in its tables. It reads almost like an English sentence, such as SELECT name FROM products, and it says what data you want, not how to find it.Go to definition. 001 is your schema.sql with IF NOT EXISTS after each CREATE TABLE:
CREATE TABLE IF NOT EXISTS products ( -- The primary key: the number that identifies each row. PostgreSQL sets it (1, 2, 3…) and it never repeats. id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- NOT NULL: it can't be missing. name text NOT NULL, -- CHECK: a condition every row has to meet. A price of 0 or less doesn't get in. price_cents integer NOT NULL CHECK (price_cents > 0));In an empty database, it creates the table. In yours, which already has it, it does nothing, and your data stays. From here on, tables only change with new migrations: 002, 003…
Only forward, and a table that records it
Section titled “Only forward, and a table that records it”A program, the migration runner, applies the missing ones. To know which, it keeps a table in the database itself, migrations, with one row for each one applied:
name | applied_at---------------+------------------------------- 001-shop.sql | 2026-10-13 23:47:47.898577+00 002-stock.sql | 2026-10-13 23:47:47.902611+00(2 rows)Three rules make it work:
- The number decides the order. 002 adds a column to a table that 001 creates: the other way around wouldn’t work.
- Each one is applied only once. If its name is in the table, it’s skipped.
- Only forward. To undo a change, you write another migration. The history of your tables is the list of files, and it travels in Git with the code (Phase 1).
Why 001 and not 1? The runner sorts the names as text, character by character, and that way 10-… comes before 2-…. With three digits, 002 comes before 010.
Each migration, all or nothing
Section titled “Each migration, all or nothing”A migration with several commands can fail halfway. If the first one had already changed the table, your database would be left in a state that isn’t in any file. That’s why the runner puts each migration in a TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition: a group of commands that PostgreSQL saves all together or not at all.
BEGINopens the transaction.COMMITsaves everything done since theBEGIN.ROLLBACKundoes all of it, as if it had never happened.
In PostgreSQL, even an ALTER TABLE is undone with ROLLBACK; in MySQL, it isn’t: it’s saved on the spot. You’ll see transactions in depth in lesson 8.
The runner, piece by piece
Section titled “The runner, piece by piece”The runner is scripts/migrate.ts, and you write it yourself, without libraries, to see there’s no magic: like node:http before Hono in Phase 3. The beginning:
import { readdir, readFile } from 'node:fs/promises';import { join } from 'node:path';import { pool } from '../src/db.ts';
// The folder can be changed (the tests do it): npm run db:migrate -- another/folderconst folder = process.argv[2] ?? join(import.meta.dirname, '..', 'db', 'migrations');poolis the Connection poolA few connections to the database that a server keeps open and reuses. Each query takes a free one and gives it back when it’s done. Opening a connection costs much more than using it, and the database only accepts a limited number at a time.Go to definition fromsrc/db.ts, the one from lesson 5.process.argv[2]is whatever you write after the script’s name. If you write nothing, it’sundefined, and??uses what’s on its right: thedb/migrationsfolder.joinjoins the pieces of the path starting fromimport.meta.dirname, this file’s folder.
Next, what’s left to apply:
await pool.query(` CREATE TABLE IF NOT EXISTS migrations ( name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now() )`);const { rows } = await pool.query<{ name: string }>('SELECT name FROM migrations');const applied = new Set(rows.map((row) => row.name));// sort() sorts them by name: the number at the start decides the order.const files = (await readdir(folder)).filter((file) => file.endsWith('.sql')).sort();const pending = files.filter((file) => !applied.has(file));CREATE TABLE IF NOT EXISTS migrationscreates the record table the first time.nameis the Primary keyThe column, or group of columns, that identifies each row of a table. Its value can’t repeat or be missing, like an order number.Go to definition, so it doesn’t repeat, andapplied_atfills itself in with the time (DEFAULT now()).SELECT name FROM migrationsreads the applied ones, andnew Set(…)keeps them in a set: a list you can ask “is this one here?” with.has().readdirreads the names of the files in the folder.filterkeeps the.sqlones,sort()sorts them by name, and the secondfilterkeeps the ones that aren’t in the set (filterandmap, in Phase 3).
And applying them, each one in its own transaction:
// A transaction goes entirely through the same connection: one is borrowed from the pool and// given back at the end.const client = await pool.connect();try { for (const name of pending) { await client.query('BEGIN'); try { await client.query(await readFile(join(folder, name), 'utf8')); await client.query('INSERT INTO migrations (name) VALUES ($1)', [name]); await client.query('COMMIT'); // the migration and its record, together console.log(`Applied: ${name}`); } catch (error) { // ROLLBACK undoes everything this migration did: nothing is left half-done. await client.query('ROLLBACK'); console.error(`${name} was not applied: ${(error as Error).message}`); process.exitCode = 1; break; // the next ones may depend on this one: they stop here } } if (pending.length === 0) { console.log('No new migrations: the database is up to date'); }} finally { client.release(); await pool.end();}pool.connect()asks the pool for a connection and keeps it: a transaction lives on a single connection.- Inside the
for, it reads each file, sends it whole to PostgreSQL and writes its name down inmigrations, with a parameter ($1), as in lesson 5. - The change and its record go in the same transaction: both stay, or neither does.
- If something fails, the
catchdoes aROLLBACK, writes the error, leaves an Exit codeThe number a program leaves when it finishes. 0 means it went well, and any other, from 1 to 255, that something failed. The shell keeps it in $?, and scripts check it to decide whether to go on.Go to definition of 1 and stops withbreak: the next one may depend on the one that failed. finallyruns no matter what: it gives the connection back (release) and closes the pool, so the program ends.tryandcatchare the ones from lesson 8 of Phase 3.
About 35 lines, without the comments. In package.json, db:create makes way for "db:migrate": "node --env-file-if-exists=.env scripts/migrate.ts".
Adding stock to a table that already has rows
Section titled “Adding stock to a table that already has rows”The first thing anyone thinks of is a single command: the stock column, a whole number (integer) that can’t be missing (NOT NULL). Try it: since it fails, it changes nothing:
A NOT NULL column, all at once
ALTER TABLE products ADD COLUMN stock integer NOT NULL;What you will see:
ERROR: column "stock" of relation "products" contains null valuesInside psql -d shop, as in the introduction. The stock column of the table (“relation”) products would have NULL values.
A new column reaches the four products with no value, NULL, and NOT NULL forbids it. The treacherous part: on an empty table, like your tests’ one, the same command works. It fails where there’s data, which is usually production.
The safe way is three steps, in 002-stock.sql. First, the column without the rule:
-- 1. The column, still without NOT NULL: the rows already there get it empty (NULL). With NOT NULL-- and no value, PostgreSQL wouldn't add it, because those rows would break the rule from the start.ALTER TABLE products ADD COLUMN stock integer;ALTER TABLE products (“change the products table”) and ADD COLUMN stock integer (“add the stock column, a whole number”). The rows already there get it empty, and for now that’s allowed.
Second, a value for each row that was already there:
-- 2. A value for each row that was already there: a starting stock, until Ana counts the warehouse.UPDATE products SET stock = 10 WHERE stock IS NULL;The UPDATE from lesson 1, only on the rows without a value. Ten is a starting stock, until Ana counts her warehouse.
Third, now that no row is empty, the rules:
-- 3. Now that no row is empty, the rules: the stock can't be missing or negative, and a new product-- starts with 0 unless told otherwise (DEFAULT).ALTER TABLE products ALTER COLUMN stock SET DEFAULT 0, ALTER COLUMN stock SET NOT NULL, ADD CONSTRAINT stock_not_negative CHECK (stock >= 0);Word by word:
ALTER COLUMN stock SET DEFAULT 0: a new product starts with 0 unless someone says otherwise.ALTER COLUMN stock SET NOT NULL: from now on it can’t be missing. PostgreSQL checks it on every row, and it passes: step 2 filled them in.ADD CONSTRAINT stock_not_negative CHECK (stock >= 0): a ConstraintA rule the database checks on every change, such as the price being greater than zero or no two categories having the same name. Data that breaks it doesn’t get in, wherever it comes from.Go to definition with a name: the stock is never negative.- All three go in one command, separated by commas.
What about ADD COLUMN stock integer NOT NULL DEFAULT 10, in one go? In PostgreSQL it works, but new products would also start with 10. The three steps always work, even if each row’s value is calculated from other columns.
A new database: migrate and load the data
Section titled “A new database: migrate and load the data”A colleague clones your project, with her database empty. She migrates, and another script, db:seed, loads the sample data:
An empty database, up to date
npm run db:migratenpm run db:seedWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 001-shop.sqlApplied: 002-stock.sql
> shop-api@1.0.0 db:seed> node --env-file-if-exists=.env scripts/seed.ts
Sample data loadedHere 002 has no rows to fill in: the products go in with their stock from db/seed.sql, 40 T-shirts, 60 mugs, 25 hoodies and 15 caps.
db:seed is scripts/seed.ts:
// Loads the sample data (db/seed.sql) into a freshly migrated database, still empty. In one that// already has data, it would repeat it: then it refuses. Run it with: npm run db:seedimport { readFile } from 'node:fs/promises';import { join } from 'node:path';import { pool } from '../src/db.ts';
try { // count(*) is a bigint, and pg returns it as text: ::int turns it into a normal number. const { rows } = await pool.query('SELECT count(*)::int AS products FROM products'); if (rows[0].products > 0) { console.error('The database already has products: npm run db:seed is only for an empty one'); process.exitCode = 1; } else { await pool.query(await readFile(join(import.meta.dirname, '..', 'db', 'seed.sql'), 'utf8')); console.log('Sample data loaded'); }} finally { await pool.end();}If there are products already, it refuses, because it would repeat them: unlike db:create, it never deletes anything. On your database, it answers The database already has products: npm run db:seed is only for an empty one.
The API shows the stock, only in version 2
Section titled “The API shows the stock, only in version 2”In src/data.ts, stock goes into the Product type (stock: number;) and into the columns requested for each product:
// The columns, with the name they have in the API: price_cents AS "priceCents". The quotes make// PostgreSQL keep the capital letter (without them, it would make it lowercase). That way, each// row is already a product just as it appears in the JSON. It's our own fixed text: nothing the// client sends is ever pasted into a query.const PRODUCT = 'id, name, price_cents AS "priceCents", stock';const ORDER = 'id, product_id AS "productId", quantity, status, created_at AS "createdAt"';
// pg turns each timestamptz into a JavaScript Date. The API gives it as text: toISOString()// writes it in ISO 8601 and always in UTC, whatever the server's time zone.type OrderRow = Omit<Order, 'createdAt'> & { createdAt: Date };const toOrder = (row: OrderRow): Order => ({ ...row, createdAt: row.createdAt.toISOString() });And in src/schemas.ts, the version 2 contract documents it:
export const productSchema = z .object({ id: z.number().int().openapi({ example: 2 }), name: z.string().openapi({ example: 'Mug' }), priceCents: z.number().int().openapi({ example: 850 }), // A new field: adding it doesn't break anyone (Phase 4, lesson 4). Only in version 2. stock: z.number().int().min(0).openapi({ example: 12, description: 'How many units are left' }), }) .openapi('Product');Version 1 doesn’t change: its adapter, productV1 in src/v1.ts, copies only id, name and the price in euros. In version 2, a new field doesn’t break anyone: it’s changing by adding.
Renaming without breaking: expand and contract
Section titled “Renaming without breaking: expand and contract”Renaming a column is something else: ALTER TABLE products RENAME COLUMN name TO title takes an instant, but the running server keeps asking for name, and fails until the new code arrives. With two servers that are updated one after the other, the old code and the new code live side by side for a while.
The solution is expand and contract: first you widen, then you trim, and each step is a different migration or DeploymentPutting a new version of a program to work on the servers, where users use it. Also called a deploy.Go to definition:
| Step | What changes | Who works |
|---|---|---|
| 1. Expand | A migration adds title and copies each name into it |
The old code, which doesn’t see it |
| 2. New code | It reads title (if it’s empty, name) and writes to both columns |
The old and the new, at the same time |
| 3. Contract | With no old code running, a migration copies into title whatever the old code wrote only in name, and drops name |
The new code |
There’s never code asking for a column that doesn’t exist.
An applied migration is never edited
Section titled “An applied migration is never edited”Imagine that, after migrating, you change the DEFAULT 0 in 002-stock.sql to DEFAULT 5. Your database doesn’t notice: 002 is already recorded, and the runner skips it. Your colleague’s, freshly created, does apply it, with 5. Same files, different databases, and nothing warns you.
That’s why a migration that has left your computer is never touched: if it was wrong, you write another one, 003.
What the tools add
Section titled “What the tools add”Migration tools do the same as your runner, and a bit more:
- Generating the SQL. drizzle-kit compares your tables, described in TypeScript, with their previous version and writes the migration. You’ll see it in lesson 9, with your runner applying it.
- Detecting edits. Flyway, widely used with Java, keeps a fingerprint of each applied migration and refuses to go on if a file has changed.
- Undoing and waiting their turn. node-pg-migrate, for Node, lets you write how to undo each migration, and uses a lock so that two servers starting at the same time don’t apply the same one.
Try it
Section titled “Try it”The goal: add the stock to your shop without losing your orders, and check that a migration that fails leaves nothing half-done.
Before changing anything
Section titled “Before changing anything”1. products, without stock
psql -d shop -c '\d products'What you will see:
Table "public.products" Column | Type | Collation | Nullable | Default-------------+---------+-----------+----------+------------------------------id | integer | | not null | generated always as identityname | text | | not null |price_cents | integer | | not null |Indexes: "products_pkey" PRIMARY KEY, btree (id)Check constraints: "products_price_cents_check" CHECK (price_cents > 0)Referenced by: TABLE "orders" CONSTRAINT "orders_product_id_fkey" FOREIGN KEY (product_id) REFERENCES products(id) TABLE "product_categories" CONSTRAINT "product_categories_product_id_fkey" FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE\d (for “describe”) is a psql command that shows what a table looks like: each column with its type, whether it allows NULL (Nullable) and its default value; below, its keys and constraints. None of the columns is stock.
With the server from lesson 5 running, create an order with the POST from the beginning and write down its number: it’s the data you don’t want to lose. Do it now, because the new code asks for a column that doesn’t exist yet.
Prepare the project
Section titled “Prepare the project”You’re still in ~/backend-course/phase-3/shop-api, with the code from lesson 5. Write the changes:
- Create the
db/migrations/folder and movedb/schema.sqlinto it as001-shop.sql. AddIF NOT EXISTSafter eachCREATE TABLE. - Create
db/migrations/002-stock.sql,scripts/migrate.tsandscripts/seed.tswith the blocks you’ve seen. - Delete
scripts/create-db.ts. Inpackage.json, replacedb:createwithdb:migrateand add"db:seed": "node --env-file-if-exists=.env scripts/seed.ts". - In
db/seed.sql, addstockto the products: 40, 60, 25 and 15. - Add
stockinsrc/data.tsand insrc/schemas.ts, as above.
The tests now prepare their database with the migrations. They come in this lesson’s folder:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/20-migrations.tar.gztar -xzf 20-migrations.tar.gzcd shop-apicp ../20-migrations/test/*.ts test/If you get stuck, compare your code with 20-migrations.
Migrate, twice
Section titled “Migrate, twice”2. The missing migrations
npm run db:migrateWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 001-shop.sqlApplied: 002-stock.sqlWith no migrations table, both were missing as far as the runner knew. 001 did nothing, because your tables already existed; 002 added the column. If you get an SQL error, compare with the download. The outputs are from PostgreSQL 18.6 and Node 26.11.1; your dates will be different.
3. Again
npm run db:migrateWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
No new migrations: the database is up to dateBoth are recorded: nothing to do. That’s why it can go in every deployment, before starting the server.
Look at the table afterward
Section titled “Look at the table afterward”4. products, with stock
psql -d shop -c '\d products'psql -d shop -c 'SELECT id, name, stock FROM products;'What you will see:
Table "public.products" Column | Type | Collation | Nullable | Default-------------+---------+-----------+----------+------------------------------id | integer | | not null | generated always as identityname | text | | not null |price_cents | integer | | not null |stock | integer | | not null | 0Indexes: "products_pkey" PRIMARY KEY, btree (id)Check constraints: "products_price_cents_check" CHECK (price_cents > 0) "stock_not_negative" CHECK (stock >= 0)Referenced by: TABLE "orders" CONSTRAINT "orders_product_id_fkey" FOREIGN KEY (product_id) REFERENCES products(id) TABLE "product_categories" CONSTRAINT "product_categories_product_id_fkey" FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
id | name | stock----+---------+-------1 | T-shirt | 102 | Mug | 103 | Hoodie | 104 | Cap | 10(4 rows)Notice stock, not null and 0 by default, and stock_not_negative. The products have 10, the starting stock from step 2: they already existed, so they didn’t go through seed.sql.
In psql -d shop, try to leave the mug in negative:
5. A negative stock
UPDATE products SET stock = -1 WHERE id = 2;What you will see:
ERROR: new row for relation "products" violates check constraint "stock_not_negative"DETAIL: Failing row contains (2, Mug, 850, -1).The resulting row (the “failing row”) would have -1, and stock_not_negative doesn’t let it in.
The API, with and without stock
Section titled “The API, with and without stock”Start the server and ask for the products in both versions, and for your order:
6. /v2 and /v1
curl -s -w '\n' localhost:3000/v2/productscurl -s -w '\n' localhost:3000/v1/productscurl -s -w '\n' localhost:3000/v2/orders/26What you will see:
[{"id":1,"name":"T-shirt","priceCents":2000,"stock":10},{"id":2,"name":"Mug","priceCents":850,"stock":10},{"id":3,"name":"Hoodie","priceCents":3500,"stock":10},{"id":4,"name":"Cap","priceCents":1500,"stock":10}][{"id":1,"name":"T-shirt","price":20},{"id":2,"name":"Mug","price":8.5},{"id":3,"name":"Hoodie","price":35},{"id":4,"name":"Cap","price":15}]{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-13T23:47:46.437Z"}Version 2 brings stock; version 1, the usual. And your order is still there (replace 26 with your number). If /v2 doesn’t bring stock, it’s missing from the columns in src/data.ts.
Make a migration fail
Section titled “Make a migration fail”Create db/migrations/003-color.sql with two commands. The first would work; the second has a typo, product without the s:
ALTER TABLE products ADD COLUMN color text;UPDATE product SET color = 'black' WHERE id = 1;7. A migration that fails
npm run db:migratepsql -d shop -c 'SELECT color FROM products;'What you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
003-color.sql was not applied: relation "product" does not existERROR: column "color" does not existLINE 1: SELECT color FROM products; ^The UPDATE failed, and the ROLLBACK also took away the ALTER TABLE that worked: color doesn’t exist. It isn’t recorded either: migrations still has two rows. Delete 003-color.sql: it was an experiment.
The tests
Section titled “The tests”8. The migration tests
npm test -- test/migrations.test.tsWhat you will see:
> shop-api@1.0.0 test> node --env-file=test/.env --test --test-concurrency=1 test/migrations.test.ts
✔ on an empty database they are all applied, in order, and recorded (107.716094ms)✔ migrating again applies nothing: the database is already up to date (76.402778ms)✔ a migration that fails leaves nothing half-done, and is not recorded (86.048603ms)✔ 002 on a table that already has rows: the ones there get the starting stock (173.188346ms)✔ db:seed only loads the data into an empty database (83.117211ms)✔ v2 shows the stock of each product, and documents it; v1 stays the same (15.414086ms)ℹ tests 6ℹ suites 0ℹ pass 6ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 776.271161They use shop_test, never your database: they empty it and migrate it every time. If you get Can't use the tests' database, PostgreSQL isn’t running. Your times will be different.
You have already seen it
Section titled “You have already seen it”- The apps on your phone keep your data in a small database inside the phone. If an update changes their tables, it brings migrations, and your notes are still there.
- WordPress, after updating, sometimes asks you to press a button to update the database: those are its migrations.
- Rails, Django or Laravel, frameworks for other languages, have their migrations folder and a command to apply them.
Common mistakes
Section titled “Common mistakes”- Editing a migration that’s already applied. The databases that already had it don’t change: write another one.
- Adding a
NOT NULLcolumn without a value to a table with rows. It works on your empty table and fails in production: three steps. - Renaming or dropping a column at the same time the new code arrives. The old code, still running, asks for it: expand and contract.
- Changing the tables by hand with
psqlin production. That change isn’t in any file: no other database will have it. - Numbering
1,2…10. Sorted as text,10comes before2: use three digits.
Summary
Section titled “Summary”- Dropping the tables and creating them again only works when there’s no data to keep.
- A migration is a numbered file with one change. The runner applies the missing ones, in order, and records them in a table in the database itself.
- Each migration goes in a transaction, together with its record: if something fails,
ROLLBACK, and nothing is left half-done. - A
NOT NULLcolumn on a table with rows takes three steps: the column, a value for each row and the rules. A rename, expand and contract. - An applied migration is never edited: you write another one.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- ALTER TABLE (PostgreSQL): everything you can change about a table.
- Modifying Tables (PostgreSQL): columns and constraints, with examples.
- Evolutionary Database Design (Martin Fowler and Pramod Sadalage): small migrations, next to the code.
- Parallel Change (Martin Fowler): expand and contract, step by step.
- node-pg-migrate: a migration runner for Node and PostgreSQL.