# How to back up a Django SQLite database

Back up SQLite while Django runs, then run SQLite's integrity check on the copy.

## Make a consistent copy

### Django

```bash
# Copy the live Django SQLite database and check the copy.
python manage.py shell --command '
import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import mkdtemp

from django.db import connections

database = connections["default"]
if database.vendor != "sqlite":
    raise SystemExit("Choose a SQLite database alias")
source = Path(database.settings_dict["NAME"]).resolve(strict=True)
backup = Path(mkdtemp(prefix="django-backup-")) / "restored.sqlite"
with closing(sqlite3.connect(source.as_uri() + "?mode=ro", uri=True)) as origin:
    with closing(sqlite3.connect(backup)) as restored:
        origin.backup(restored)
        if restored.execute("PRAGMA integrity_check").fetchall() != [("ok",)]:
            raise SystemExit("The backup failed its integrity check")
print(backup)
'
```

### Python

```python
import sqlite3
import sys
from contextlib import closing
from pathlib import Path
from tempfile import mkdtemp

if len(sys.argv) != 2:
    raise SystemExit("Usage: python backup.py DATABASE")

source = Path(sys.argv[1]).resolve(strict=True)
backup = Path(mkdtemp(prefix="sqlite-backup-")) / "restored.sqlite"
with closing(sqlite3.connect(source.as_uri() + "?mode=ro", uri=True)) as origin:
    with closing(sqlite3.connect(backup)) as restored:
        origin.backup(restored)
        if restored.execute("PRAGMA integrity_check").fetchall() != [("ok",)]:
            raise SystemExit("The backup failed its integrity check")
print(backup)
```

## Pick the database file

Run the Django example next to `manage.py` with the application's production settings loaded. It reads the file for the `default` database alias. Change the alias to back up a different SQLite database. For a Python app without Django, save the Python example as `backup.py` and run `python backup.py /var/lib/app/main.sqlite`.

Python's [`sqlite3.Connection.backup()`](https://docs.python.org/3.13/library/sqlite3.html#sqlite3.Connection.backup) copies a file-backed SQLite database through SQLite while other connections are open. It includes committed changes in WAL mode. The example opens the source readonly and prints the path to a checked copy in a new directory. Store the copy on another machine or in a bucket so you can restore it if you lose the app host.

## Check a restore with Django

Run `sqlite3 -readonly /path/to/restored.sqlite '.tables'` and query a known recent record. Then start a separate test instance with `DATABASES["default"]["NAME"]` pointing to the restored file. Use the application release that matches the database schema and open a page that reads the record. Django's media directory or object store needs its own backup.

Before replacing the database in production, stop the web and background processes that use it. Move the original and any journal files aside together before putting the checked copy in place. Make sure the app user can read and write the new file and its directory. Keep the old files until the app has been checked.

## Keep continuous backups

[Install your Litebackup server](/install) first. On the Django host, run these commands as the user that owns the database. Use a join token from **Machines**, **Add machine** in the console, and replace the example path with the database file from production settings.

```bash
# Install the Litebackup client and join the backup server.
curl --fail --silent --show-error --location https://litebackup.com/cli.sh | bash
export LITEBACKUP_API_KEY=JOIN_TOKEN@HOST
litebackup install service --api-key "${LITEBACKUP_API_KEY}"
```

After the client joins, start continuous backup and send the first version.

```bash
# Start continuous backup and send the first SQLite version.
litebackup start /var/lib/app/main.sqlite app/
litebackup sync app/main.sqlite
```

After the first version syncs, restore it into a fresh directory.

```bash
# Restore the saved SQLite version into a fresh directory and check it.
# Runs on Linux and macOS.
RESTORE_DIR=$(mktemp -d)
litebackup restore app/main.sqlite "${RESTORE_DIR}/restored.sqlite"
sqlite3 -bail -readonly "${RESTORE_DIR}/restored.sqlite" 'PRAGMA integrity_check;'
```

The last command should print `ok`.

## Install

[Install Litebackup](/install) to keep versions from your running Django app. See [SQLite backup methods](/sqlite-backup) for one-time copies and Amazon S3, and [SQLite in production](/sqlite-in-production) for deploys with persistent storage.
