Database Backups and Security · Lesson 58 of 112

Database Kinds of Backup

What you will learn

  • Physical and logical backups
  • Full and incremental backups
  • Why you should use the database's own backup tool for a busy database
  • How to make both kinds of backup in SQLite

1. Physical or logical

Kind What it copies Good for Weakness
Physical the database files themselves, byte for byte fast backup and restore of big databases usually restores only to the same kind and version of database
Logical the data as SQL statements (or another readable format) moving data between versions or systems, reading it in a text editor slower to restore on large data

2. Full or incremental

A full backup copies everything. An incremental backup copies only what changed since the last backup. Incremental backups are smaller and quicker to make, but restoring needs the last full backup plus every incremental one after it. Many setups take a full backup now and then, and smaller ones in between. How this is done depends on the database product; this course shows the idea with SQLite.

A related idea is the differential backup, which copies everything changed since the last full backup (not since the last backup of any kind). It grows over time, but restoring needs only two pieces: the full backup and the latest differential. Products use these words in slightly different ways, so read your product's documentation before relying on them.

2b. Point-in-time recovery

A nightly backup means that a mistake at 3 pm can only be undone back to last night, losing a day of work. Many server databases keep a continuous log of every change (a write-ahead log) as they work. If you keep a copy of those log files as well as an occasional full backup, you can restore the full backup and then replay the log up to the moment just before the mistake. This is called point-in-time recovery. PostgreSQL's documentation describes exactly this combination of a base backup and archived logs, and says it can restore to any point in time since the base backup. Other products have their own versions, with their own names and setup.

The idea to keep: the log makes the recovery point very small (minutes or seconds instead of a day), at the cost of storing and protecting the logs. SQLite is a small embedded database and this course does not run a log-replay demo; here we use the simpler backups below.

3. A physical backup in SQLite

Copying the file while a program is writing to it can produce a damaged copy. SQLite offers a backup function that copies a live database safely. In Python it is connection.backup(...).

import sqlite3

con = sqlite3.connect("b.db")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL, total INTEGER)")
con.executemany("INSERT INTO orders (customer,total) VALUES (?,?)", [("Rina",500),("Sam",300),("Lee",700)])
con.commit()

dest = sqlite3.connect("b_backup.db")
con.backup(dest)
dest.close()
print("backup API:", sqlite3.connect("b_backup.db").execute("SELECT COUNT(*) FROM orders").fetchone())
backup API: (3,)

4. A logical backup in SQLite

iterdump() produces the SQL needed to rebuild the database: its CREATE TABLE and INSERT statements.

dump = "\n".join(con.iterdump())
print(dump)
open("b_dump.sql", "w").write(dump)   # saved for lesson 8.3
BEGIN TRANSACTION;
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL, total INTEGER);
INSERT INTO "orders" VALUES(1,'Rina',500);
INSERT INTO "orders" VALUES(2,'Sam',300);
INSERT INTO "orders" VALUES(3,'Lee',700);
COMMIT;

You can save that text in a .sql file. It is readable, can be kept in version control for small data, and can be loaded into a fresh database (lesson 8.3). Other database products have their own dump and backup tools, with different names and options; check the documentation of the one you use.

A logical backup by hand, in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A query can build the INSERT statements itself. The quote() function turns a value into SQL text, with quotes where they are needed and NULL for missing values:

SELECT 'INSERT INTO categories VALUES (' || category_id || ', ' || quote(name) || ', ' || quote(parent_id) || ');' AS backup_line
FROM categories ORDER BY category_id LIMIT 4;
backup_line
--------------------------------------------------
INSERT INTO categories VALUES (1, 'Home', NULL);
INSERT INTO categories VALUES (2, 'Kitchen', 1);
INSERT INTO categories VALUES (3, 'Garden', 1);
INSERT INTO categories VALUES (4, 'Office', NULL);
(4 rows)
SELECT 'INSERT INTO branches VALUES (' || branch_id || ', ' || quote(name) || ', ' || quote(city) || ');' AS backup_line
FROM branches ORDER BY branch_id LIMIT 4;
backup_line
--------------------------------------------------------
INSERT INTO branches VALUES (1, 'Central', 'Lisbon');
INSERT INTO branches VALUES (2, 'Riverside', 'Toronto');
INSERT INTO branches VALUES (3, 'Harbour', 'Osaka');
INSERT INTO branches VALUES (4, 'Old Town', 'Cairo');
(4 rows)
SELECT 'INSERT INTO departments VALUES (' || department_id || ', ' || quote(name) || ', ' || quote(building) || ');' AS backup_line
FROM departments ORDER BY department_id LIMIT 4;
backup_line
----------------------------------------------------------------
INSERT INTO departments VALUES (1, 'Mathematics', 'North Hall');
INSERT INTO departments VALUES (2, 'Science', 'Lab Block');
INSERT INTO departments VALUES (3, 'Languages', 'West Hall');
INSERT INTO departments VALUES (4, 'Humanities', 'East Hall');
(4 rows)

Saved in a file, lines like these rebuild the table in an empty database. That is what a dump tool does for every table.

Worked example: which kind?

Situation Better choice Why
A 200 GB database that must be restored within an hour physical (full plus incremental) copying files is fastest
Moving a small database to a new version of the software logical the SQL text is independent of file format
A developer wants a small readable copy of the schema and sample data logical open it in a text editor

Common mistakes

  • Copying the files of a busy database with an ordinary file copy and trusting the result.
  • Only keeping logical backups of a huge database and finding the restore takes days.
  • Forgetting that incremental backups depend on the chain of earlier ones.
  • Never checking the backup (lesson 8.3).

Key takeaways

  • Physical backups copy files; logical backups save SQL or data as text.
  • Full backups copy everything; incremental backups copy only changes.
  • Use the database's own backup tool for a database in use.
  • SQLite offers backup() (physical) and iterdump() (logical).

Practice

1. Sunday: full backup. Monday to Friday: an incremental backup each night. The disk fails on Thursday afternoon. Which backups do you need to restore, and how much work is lost at most?

Show answer

The Sunday full backup plus the Monday, Tuesday and Wednesday incrementals, in order. Work done on Thursday before the failure is lost, up to about a day, unless the database also keeps a log you can replay (point-in-time recovery).

2. Why is a plain file copy risky for a database being written to?

Show answer

The file can change while it is copied, giving a copy that is damaged or half-updated.

3. What do you need to restore from incremental backups?

Show answer

The last full backup and every incremental backup made after it.

4. Which backup kind suits moving data into a different version of the software?

Show answer

A logical backup, because it does not depend on the internal file format.

5. What did con.backup(dest) do in the lesson?

Show answer

It copied the whole database into the second database file safely, and the copy had the same 3 orders.

6. At 3 pm someone deletes the wrong rows. The last backup was at midnight, but the server also archives its change log. What can you do that a plain nightly backup cannot, and what does it cost?

Show answer

Restore the midnight backup and replay the log up to just before the mistake (point-in-time recovery), losing almost no work. The cost is storing and protecting the log files and having a more complex restore procedure.