Database Backups and Security · Lesson 63 of 112

Database Migrations

What you will learn

  • Why a database's structure changes after launch
  • What a migration is
  • How to track the version and apply steps once, in order
  • Safe habits for changing a live database

1. Structure changes

A database is rarely finished. New features need new tables and columns, indexes are added, names are fixed. The data of real users is already there, so you cannot just delete everything and start again. A migration is a small, numbered change to the structure (and sometimes the data) that moves the database from one version to the next.

Writing migrations as files, instead of typing changes by hand, gives you a record, the same result on every machine (your laptop, a test server, the live server), and a way to repeat the process.

2. A version number in the database

The database needs to know which migrations it already has. SQLite has a spare integer for this, PRAGMA user_version, which starts at 0. Other products usually use a small table that lists applied migrations.

import sqlite3

con = sqlite3.connect(":memory:")
print("start", con.execute("PRAGMA user_version").fetchone()[0])
start 0

A list of migrations, in order, and a function that applies only the ones missing:

MIGRATIONS = [
    "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
    "ALTER TABLE customers ADD COLUMN phone TEXT",
    "CREATE INDEX idx_customers_name ON customers(name)",
]

def migrate(con):
    v = con.execute("PRAGMA user_version").fetchone()[0]
    for i in range(v, len(MIGRATIONS)):
        con.execute(MIGRATIONS[i])
        con.execute(f"PRAGMA user_version = {i+1}")
        print("applied migration", i+1)
    con.commit()

migrate(con)
migrate(con)
applied migration 1
applied migration 2
applied migration 3

The first call applied all three. The second call printed nothing, because the version was already 3. That is the key property: running migrations is safe to repeat.

con.execute("INSERT INTO customers (name,phone) VALUES ('Rina','017')")
print(con.execute("PRAGMA table_info(customers)").fetchall())
print(con.execute("PRAGMA user_version").fetchone()[0])
[(0, 'id', 'INTEGER', 0, None, 1), (1, 'name', 'TEXT', 1, None, 0), (2, 'phone', 'TEXT', 0, None, 0)]
3

Each tuple describes a column: position, name, type, NOT NULL flag, default, and primary key flag. Web frameworks and migration tools do the same job with more features; the idea is identical.

The same migrations as SQL cells. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A cell cannot run a loop, so you play the migration tool yourself: run each numbered step, then record it in user_version. The members table is a small one of its own; Reset data removes it and sets the version back.

PRAGMA user_version;
user_version
------------
           0
(1 row)

Migration 1, then record it:

CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
PRAGMA user_version = 1;
(done)

Migrations 2 and 3:

ALTER TABLE members ADD COLUMN phone TEXT;
PRAGMA user_version = 2;
CREATE INDEX idx_members_name ON members (name);
PRAGMA user_version = 3;
(done)
INSERT INTO members (name, phone) VALUES ('Rina', '017');
SELECT name, type, "notnull", pk FROM pragma_table_info('members');
PRAGMA user_version;
name   type     notnull  pk
-----  -------  -------  --
id     INTEGER        0   1
name   TEXT           1   0
phone  TEXT           0   0
(3 rows)

user_version
------------
           3
(1 row)
PRAGMA user_version;
user_version
------------
           0
(1 row)

Migration 1, then record it:

CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
PRAGMA user_version = 1;
(done)

Migrations 2 and 3:

ALTER TABLE members ADD COLUMN phone TEXT;
PRAGMA user_version = 2;
CREATE INDEX idx_members_name ON members (name);
PRAGMA user_version = 3;
(done)
INSERT INTO members (name, phone) VALUES ('Rina', '017');
SELECT name, type, "notnull", pk FROM pragma_table_info('members');
PRAGMA user_version;
name   type     notnull  pk
-----  -------  -------  --
id     INTEGER        0   1
name   TEXT           1   0
phone  TEXT           0   0
(3 rows)

user_version
------------
           3
(1 row)
PRAGMA user_version;
user_version
------------
           0
(1 row)

Migration 1, then record it:

CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
PRAGMA user_version = 1;
(done)

Migrations 2 and 3:

ALTER TABLE members ADD COLUMN phone TEXT;
PRAGMA user_version = 2;
CREATE INDEX idx_members_name ON members (name);
PRAGMA user_version = 3;
(done)
INSERT INTO members (name, phone) VALUES ('Rina', '017');
SELECT name, type, "notnull", pk FROM pragma_table_info('members');
PRAGMA user_version;
name   type     notnull  pk
-----  -------  -------  --
id     INTEGER        0   1
name   TEXT           1   0
phone  TEXT           0   0
(3 rows)

user_version
------------
           3
(1 row)

The version number now says 3, so a migration tool would know that migrations 1 to 3 are done and start from number 4.

The worked example below (renaming phone to mobile in four small steps) can be tried here too:

ALTER TABLE members ADD COLUMN mobile TEXT;
PRAGMA user_version = 4;
UPDATE members SET mobile = phone;
PRAGMA user_version = 5;
SELECT name, phone, mobile FROM members;
name  phone  mobile
----  -----  ------
Rina  017    017
(1 row)

After the code has switched to mobile and a safe period has passed, the last step removes the old column:

ALTER TABLE members DROP COLUMN phone;
PRAGMA user_version = 6;
SELECT name, type FROM pragma_table_info('members');
PRAGMA user_version;
name    type
------  -------
id      INTEGER
name    TEXT
mobile  TEXT
(3 rows)

user_version
------------
           6
(1 row)
ALTER TABLE members ADD COLUMN mobile TEXT;
PRAGMA user_version = 4;
UPDATE members SET mobile = phone;
PRAGMA user_version = 5;
SELECT name, phone, mobile FROM members;
name  phone  mobile
----  -----  ------
Rina  017    017
(1 row)

After the code has switched to mobile and a safe period has passed, the last step removes the old column:

ALTER TABLE members DROP COLUMN phone;
PRAGMA user_version = 6;
SELECT name, type FROM pragma_table_info('members');
PRAGMA user_version;
name    type
------  -------
id      INTEGER
name    TEXT
mobile  TEXT
(3 rows)

user_version
------------
           6
(1 row)
ALTER TABLE members ADD COLUMN mobile TEXT;
PRAGMA user_version = 4;
UPDATE members SET mobile = phone;
PRAGMA user_version = 5;
SELECT name, phone, mobile FROM members;
name  phone  mobile
----  -----  ------
Rina  017    017
(1 row)

After the code has switched to mobile and a safe period has passed, the last step removes the old column:

ALTER TABLE members DROP COLUMN phone;
PRAGMA user_version = 6;
SELECT name, type FROM pragma_table_info('members');
PRAGMA user_version;
name    type
------  -------
id      INTEGER
name    TEXT
mobile  TEXT
(3 rows)

user_version
------------
           6
(1 row)

3. Safe habits

  • Never edit a migration that has already run anywhere important. Add a new one.
  • Back up first (lesson 8.2), and test the migration on a copy of real data.
  • Prefer small steps. For example, adding a column that allows NULL is easy; adding a NOT NULL column needs a default or a fill step.
  • Keep old and new code working together while a change rolls out: add the new column first, deploy code that uses it, remove the old one later.
  • Think about size. Some changes lock a large table or take a long time on millions of rows; how this behaves differs between products, so read the documentation of yours.
  • Write the rollback plan (or at least know that you restore from the backup).

Worked example: renaming a column safely

You want to rename phone to mobile in a live system (made up).

  1. Migration 4: add the new column mobile.
  2. Migration 5: copy the values from phone to mobile.
  3. Deploy code that reads and writes mobile.
  4. After a safe period, migration 6: drop phone.

Four small steps, each reversible from a backup, instead of one risky change during which the site might break.

Common mistakes

  • Changing the live database by hand, with no record.
  • Editing old migrations so machines no longer agree.
  • Skipping the test on realistic data.
  • No backup before the change.

Key takeaways

  • A migration is a numbered change to the structure; keep them in files.
  • Store the current version in the database and apply only missing steps.
  • Never edit a migration that has already run; add a new one.
  • Back up, test on a copy, and change in small steps.

Practice

1. What is a migration?

Show answer

A small, numbered change that moves a database's structure from one version to the next.

2. Why did the second call to migrate print nothing?

Show answer

user_version was already 3, so no migration was missing.

3. Why should you not edit a migration that has already run?

Show answer

Databases that already ran the old version would not get the change, so machines would differ.

4. How would you add a fourth migration to the list in the lesson?

Show answer

Append a new statement to the end of MIGRATIONS; migrate will apply it and set user_version to 4.

5. Why is back-up-first part of the habit?

Show answer

If the change goes wrong, the backup lets you return to how the database was.

6. Why is renaming a column done in several steps in a live system?

Show answer

Old and new code must work together during the rollout; small steps avoid a moment when the site breaks.