SQLite Online Backup Copies Live Databases

Copy a live SQLite database with Connection.backup, stream pages, verify integrity, and compare the copied row count.

PythonData Integrity

Code

pythonsnippet
39 lines
import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory


def seed(path: Path) -> None:
    with closing(sqlite3.connect(path)) as connection:
        connection.execute('CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT)')
        connection.executemany(
            'INSERT INTO events (kind) VALUES (?)',
            [('click',), ('view',), ('purchase',)],
        )
        connection.commit()


def main() -> None:
    with TemporaryDirectory() as tmp:
        source_path = Path(tmp) / 'source.db'
        backup_path = Path(tmp) / 'backup.db'
        seed(source_path)

        source = sqlite3.connect(source_path)
        target = sqlite3.connect(backup_path)
        source.backup(target, pages=1)
        target.close()
        source.close()

        # closing() closes the connection even if a query raises.
        with closing(sqlite3.connect(backup_path)) as copy:
            count = copy.execute('SELECT COUNT(*) FROM events').fetchone()[0]
            integrity = copy.execute('PRAGMA integrity_check').fetchone()[0]
            print('rows copied:', count)
            print('integrity:', integrity)
            print('backup size:', backup_path.stat().st_size)


if __name__ == '__main__':
    main()

What the code does

SQLite Online Backup Copies Live Databases comes down to the functions seed and main.

closing, Path, TemporaryDirectory are the only symbols borrowed from tempfile — the coupling is explicit and narrow.

What to watch for

  • Requires tempfile and sqlite3 as packages; the snippet will not run without them.

Using it

The primary signature is def seed(path: Path) -> None

Output lines are prefixed (rows copied:, integrity:, backup size:), making each step’s effect easy to spot.

The entry point wires seed together — run it once and the whole demo flows.

Key statements

with closing(sqlite3.connect(backup_path)) as copy:
    count = copy.execute('SELECT COUNT(*) FROM events').fetchone()[0]
    integrity = copy.execute('PRAGMA integrity_check').fetchone()[0]
    print('rows copied:', count)
    print('integrity:', integrity)
    print('backup size:', backup_path.stat().st_size)
with closing(sqlite3.connect(path)) as connection:
    connection.execute('CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT)')
    connection.executemany(
        'INSERT INTO events (kind) VALUES (?)',
        [('click',), ('view',), ('purchase',)],
    )
    connection.commit()

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `sqlite3`, which the package manager must provide.