Database Operations · Lesson 94 of 112

Database Environments, Versions and Upgrades

What you will learn

  • Why you need separate environments
  • How to find out and record versions
  • How to track the schema version and apply numbered migrations
  • How to rehearse an upgrade on a copy
  • How to plan the way back (rollback) and upgrade the database software

1. Never experiment on production

Production is the real database that real users depend on. Changing it for the first time "to see what happens" is how data is lost. So teams keep several copies of the whole setup:

Environment Purpose Data
Development a developer's own place for trying things small, made-up
Testing / staging a copy of production's setup where changes are checked before release made-up or a safe copy
Production the real service real

A change travels in one direction: development, then testing, then production. Each stage should be built the same way as the next (same database product and version, same settings), because differences between environments are a famous cause of "but it worked on my machine".

Real customer data should not be copied into development or testing unless it is protected or made anonymous (lesson 8.6); developers rarely need it, and every extra copy is another place for a leak.

2. Know your versions

Three kinds of version matter:

  1. The database software. Different versions have different features and sometimes different behaviour. You can ask SQLite directly:
import sqlite3

print("SQLite library version:", sqlite3.sqlite_version)
con = sqlite3.connect(":memory:")
SQLite library version: 3.50.4

Your number may be different. Other products have their own commands to show their version; check the documentation.

  1. The schema (the tables, columns and indexes). Your program expects a certain shape. This version is your own number, and you must keep it up to date (next section).

  2. The application that talks to the database, which depends on 1 and 2.

When you read a tutorial, an answer on the web, or this course, check which version it was written for. Features appear, change and sometimes disappear.

3. Record the schema version

If a program expects a phone column and the database does not have it yet, the program fails in strange ways. The cure is to store a schema version number inside the database and compare. SQLite has a free integer for this, user_version. A new database starts with 0:

print("user_version of a new database:", con.execute("PRAGMA user_version").fetchone()[0])
user_version of a new database: 0

The version number in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The same number can be read and set from a SQL cell. The sample database starts at 0; the two steps below play a tiny migration runner. Reset data sets it back.

PRAGMA user_version;
user_version
------------
           0
(1 row)
CREATE TABLE settings (name TEXT PRIMARY KEY, value TEXT);
PRAGMA user_version = 1;
ALTER TABLE settings ADD COLUMN note TEXT;
PRAGMA user_version = 2;
PRAGMA user_version;
user_version
------------
           2
(1 row)
PRAGMA user_version;
user_version
------------
           0
(1 row)
CREATE TABLE settings (name TEXT PRIMARY KEY, value TEXT);
PRAGMA user_version = 1;
ALTER TABLE settings ADD COLUMN note TEXT;
PRAGMA user_version = 2;
PRAGMA user_version;
user_version
------------
           2
(1 row)
PRAGMA user_version;
user_version
------------
           0
(1 row)
CREATE TABLE settings (name TEXT PRIMARY KEY, value TEXT);
PRAGMA user_version = 1;
ALTER TABLE settings ADD COLUMN note TEXT;
PRAGMA user_version = 2;
PRAGMA user_version;
user_version
------------
           2
(1 row)

Other products usually use a small table of applied migrations for the same purpose (lesson 8.7).

4. Numbered migrations

A migration is one numbered step that moves the schema from version N−1 to N. Keep them in order in your code (and in version control). A small runner applies the ones that are missing:

MIGRATIONS = {
    1: "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
    2: "ALTER TABLE customers ADD COLUMN phone TEXT",
    3: "CREATE INDEX idx_customers_name ON customers(name)",
}
REQUIRED_VERSION = 3

def upgrade(con, target=REQUIRED_VERSION):
    current = con.execute("PRAGMA user_version").fetchone()[0]
    for version in sorted(MIGRATIONS):
        if current < version <= target:
            con.execute(MIGRATIONS[version])
            con.execute(f"PRAGMA user_version = {version}")
            con.commit()
            print("applied migration", version)
    return con.execute("PRAGMA user_version").fetchone()[0]

print("now at version", upgrade(con))
print("running upgrade again:", upgrade(con), "(nothing to do)")
applied migration 1
applied migration 2
applied migration 3
now at version 3
running upgrade again: 3 (nothing to do)

Notice the second call: running the upgrade again does nothing, because the database already knows its version. That is the property that makes upgrading safe to repeat.

The program can also refuse to start when the database is not at the version it needs, instead of failing later in confusing ways:

def check_ready(con):
    have = con.execute("PRAGMA user_version").fetchone()[0]
    if have != REQUIRED_VERSION:
        raise SystemExit(f"database is at version {have}, the program needs {REQUIRED_VERSION}")
    print("schema version", have, "matches the program")

check_ready(con)
con.execute("PRAGMA user_version = 2")
try:
    check_ready(con)
except SystemExit as e:
    print("refused to start:", e)
schema version 3 matches the program
refused to start: database is at version 2, the program needs 3

(We lied to the database by setting the version back to 2 only to show the check. Never edit the version by hand in real life: then it no longer matches the real schema, and running migration 3 again would fail with "index already exists".)

Sometimes checking a feature is better than checking a version number:

try:
    con.execute("SELECT json_extract('{\"a\": 1}', '$.a')").fetchone()
    print("JSON functions available")
except sqlite3.OperationalError:
    print("JSON functions missing")
JSON functions available

5. Rehearse, then upgrade, with a way back

The safe order for any risky change:

  1. Back up production (lesson 8.2) and confirm the backup can be restored (lesson 12.6).
  2. Copy the database to a test environment and run the upgrade there. Time it and check the application against it.
  3. Plan the way back: what do you do if step 4 fails? Usually "restore the backup", but only if you decided it in advance and know how long it takes.
  4. Do it in production, at a quiet time, watching the monitoring (lesson 12.3).
  5. Check and keep the backup until you are sure.

Here is the rehearsal in code: an old database at version 1 is copied, and only the copy is upgraded:

old = sqlite3.connect(":memory:")
upgrade(old, target=1)                     # an old database that is still at version 1
rehearsal = sqlite3.connect(":memory:")
old.backup(rehearsal)
print("rehearsal copy upgraded to", upgrade(rehearsal), "| the original is still at", old.execute("PRAGMA user_version").fetchone()[0])
applied migration 1
applied migration 2
applied migration 3
rehearsal copy upgraded to 3 | the original is still at 1

The first line, applied migration 1, comes from building the old database; the other two lines come from upgrading the copy. The original stays at version 1, untouched.

Upgrading the database software itself (for example to a newer major version of a server product) follows the same steps, and there are extra things to read in your product's documentation: whether the files can be upgraded in place or must be exported and reloaded, which features changed, and which older versions can jump directly to the new one. Do not guess. Read the official upgrade notes for your exact versions.

Changes that need no downtime are possible but need design: add new things first (a new column, nullable), switch the application, and remove old things last. Removing or renaming something that running programs still use is what causes outages.

Worked example: adding a phone number for orders

The shop wants to store a delivery phone on each order. It uses the steps above.

Step Action
1 Back up production and test a restore of that backup
2 Write migration 4: ALTER TABLE orders ADD COLUMN delivery_phone TEXT (nullable, so old rows are fine)
3 Copy production to the test environment; run migration 4; open the shop's test site and place an order
4 Decide the way back: restore the backup (estimated 40 minutes), or leave the empty column (harmless)
5 Release the program that can write the column, after the migration
6 Check the schema version is 4 and new orders contain phones; keep the backup for a week

Adding a nullable column is a low-risk change. Dropping a column, changing a type or renaming a table would need more steps, because old programs would break. The shop and steps are made up.

Common mistakes

  • Testing in production.
  • Environments that differ, for example a different database version in testing.
  • Changing the schema by hand without a numbered, recorded migration.
  • Skipping the rehearsal because the change "looks small".
  • No way back decided before the change.
  • Editing the recorded schema version to make an error go away.

Key takeaways

  • Keep development, testing and production separate, and build them the same way.
  • Know the version of the database software, the schema and the application.
  • Store a schema version in the database and apply numbered migrations; running them again must do nothing.
  • Rehearse upgrades on a copy, decide the way back in advance, and upgrade at a quiet time while monitoring.
  • For a new database software version, read the official upgrade notes for your exact versions.

Practice

1. Why should testing use the same database product and version as production?

Show answer

Different versions can behave differently or lack features, so a change that works in testing could fail in production.

2. In the lesson, what happened when upgrade(con) ran a second time?

Show answer

Nothing: the database was already at version 3, so no migrations were applied and it returned 3.

3. Why is it dangerous to set user_version by hand?

Show answer

The recorded version no longer matches the real schema. A migration might be run again and fail (or apply twice), or be skipped when it is needed.

4. Write a migration (as one SQL statement) that adds a nullable email column to customers.

Show answer

ALTER TABLE customers ADD COLUMN email TEXT

5. List the five safe steps for a risky change.

Show answer

Back up (and check the backup), rehearse on a copy, plan the way back, do it in production at a quiet time while watching, then check and keep the backup for a while.

6. Why is removing a column riskier than adding a nullable one?

Show answer

Programs that are still running may use the removed column and break immediately. A new nullable column does not disturb existing programs.