> ## Documentation Index
> Fetch the complete documentation index at: https://docs.styne.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# A database in a sandbox

> Run SQLite or Postgres inside a sandbox, and start every run from the same seeded data.

**You need** the E2B SDK with `E2B_API_KEY` and `E2B_API_URL=https://api.styne.ai` set ([Switch from E2B](https://docs.styne.ai/e2b-drop-in.md)). A sandbox is a full Linux VM with a writable disk, so a database is a process you start in it. SQLite needs nothing; Postgres is installed with the package manager.

The disk of the `base` template is 1 GiB (see [limits](https://docs.styne.ai/limits.md#sandbox-sizes)). It is plenty for test data and a
small fixture; it is not a place for a large dataset.

## SQLite

Python 3 in the `base` template ships the `sqlite3` module, so a database is a file.

```python theme={"theme":"css-variables"}
from e2b import Sandbox

SCRIPT = """
import sqlite3
db = sqlite3.connect('/root/app.db')
db.execute('create table if not exists notes (id integer primary key, body text)')
db.executemany('insert into notes (body) values (?)', [('first',), ('second',)])
db.commit()
print(db.execute('select count(*) from notes').fetchone()[0])
"""

with Sandbox.create(template="base", timeout=300) as sbx:
    sbx.files.write("/root/seed.py", SCRIPT)
    print(sbx.commands.run("python3 /root/seed.py").stdout.strip())
```

```text theme={"theme":"css-variables"}
2
```

The file `/root/app.db` stays for as long as the sandbox does, also across a pause and a resume. To keep a seeded database for
every later task, snapshot the sandbox once and start your sandboxes from it: see
[Timeouts, pause and resume](https://docs.styne.ai/pause-tiers.md).

## Postgres

Install the server from the template's package manager, start a cluster as the `postgres` user, and connect on localhost.
The install needs the sandbox to reach the package mirrors; on a sandbox without outbound access use SQLite or bake the
install into your own snapshot first.

```python theme={"theme":"css-variables"}
from e2b import Sandbox

SETUP = "apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq postgresql"

with Sandbox.create(template="base", timeout=900) as sbx:
    sbx.commands.run(SETUP, timeout=600)
    sbx.commands.run("service postgresql start", timeout=60)
    sql = "create table t (n int); insert into t values (1),(2),(3); select sum(n) from t;"
    out = sbx.commands.run(f'su postgres -c "psql -At -c \\"{sql}\\""')
    print(out.stdout.strip().splitlines()[-1])
```

```text theme={"theme":"css-variables"}
6
```

Connect your application with `postgresql://postgres@127.0.0.1:5432/postgres` from inside the sandbox. To reach it from
outside, do not expose the database port to the internet: tunnel through a command, or run the client in the sandbox.

## Reset a database for every run

For evals and tests that need a clean database each time, build one sandbox with the schema and the fixture, snapshot it,
and start every run from the snapshot. Each run begins with the same bytes, in memory and on disk, in about the time of a
create.

```text theme={"theme":"css-variables"}
POST /sandboxes/{id}/snapshots   {"name": "db-fixture-1"}
POST /sandboxes                  {"snapshot": "db-fixture-1", "timeout": 300}
```

## Things to know

* A database process does not survive a sandbox that ended. Data you need after the sandbox is killed leaves through the
  [file routes](https://docs.styne.ai/files.md) or an export of your own before you kill it.
* Postgres in a sandbox with little memory (`code` has 1 GiB): keep `shared_buffers` small and the connection count low.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.