Local Databases (WSL + Docker) Guide

Technology: local-database · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/local-database

Insight:

A local database is a disposable copy of production's shape, never a place to relax production's rules. In 2026 there are four honest ways to get one: a pinned Docker container in WSL (postgres:18.6, the same engine Supabase and Neon run), the Supabase CLI stack when you also need Auth/Storage/Realtime locally, Neon Local when you want a real cloud branch behind a localhost port, and PGlite, which is Postgres 18.6 compiled to WASM and running inside your test process with no Docker at all. SQLite (node:sqlite, now a release candidate in Node 24 LTS) is the on-device store for offline-first apps. Two version traps define this refresh: npm install prisma now pulls the Prisma 8 RC, which does not read schema.prisma (pin prisma@7), and Drizzle's docs install the @rc 1.0 line while npm latest is still 0.45.4.

██╗      ██████╗  ██████╗ █████╗ ██╗
██║     ██╔═══██╗██╔════╝██╔══██╗██║
██║     ██║   ██║██║     ███████║██║
██║     ██║   ██║██║     ██╔══██║██║
███████╗╚██████╔╝╚██████╗██║  ██║███████╗
╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝╚══════╝

██████╗  █████╗ ████████╗ █████╗ ██████╗  █████╗ ███████╗███████╗
██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝
██║  ██║███████║   ██║   ███████║██████╔╝███████║███████╗█████╗
██║  ██║██╔══██║   ██║   ██╔══██║██╔══██╗██╔══██║╚════██║██╔══╝
██████╔╝██║  ██║   ██║   ██║  ██║██████╔╝██║  ██║███████║███████╗
╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝

Local Databases (WSL + Docker) Guide

Focus: Every way codeAmani runs a database on a laptop: pinned Docker containers inside WSL Ubuntu (Postgres + pgvector, Redis, MongoDB, MySQL/MariaDB) with one compose.yaml; the Supabase CLI local stack; Neon Local; PGlite (in-process Postgres for tests); the SQLite family (node:sqlite, better-sqlite3, Turso); Prisma 7 / Drizzle migrations and seeding against all of them; and offline-first sync (PowerSync, Electric, Zero, Turso Sync) for low-connectivity users. Image tags checked against Docker Hub and package versions against npm on 2026-10-20.

Overview

codeAmani ships production data to [[supabase]] (Postgres + RLS) or [[neon]] (serverless Postgres with branching). Neither is a good place to try a migration you're unsure about at 2am on hotel Wi-Fi. A local database is the mirror: same engine, same major version, same extensions, zero network, zero bill, and a two-second reset.

Pick the mirror by what you need to exercise:

You need… Use Postgres version Needs Docker Works offline
Plain Postgres (+ pgvector, RLS) for app dev Docker container (§3–4) 18.6 ✅ ✅
Supabase Auth / Storage / Realtime / Edge Functions locally Supabase CLI supabase start (§5) Supabase's image ✅ (or experimental native runtime on Linux/macOS) ✅
A real Neon branch, per git branch or per docker compose up Neon Local proxy (§6) your Neon project's ✅ ❌ (proxies to cloud)
Fast, isolated DB per unit test; browser/demo DB PGlite (§7) 18.6 (WASM) ❌ ✅
On-device store, CLI tools, offline queue SQLite: node:sqlite / better-sqlite3 / Turso (§8) — ❌ ✅
App keeps working for days offline, syncs later Sync engine: PowerSync / Electric / Zero / Turso Sync (§11) upstream Postgres for the sync service ✅
Redis / MongoDB / MySQL stand-ins Docker container (§3) — ✅ ✅
Local container Supabase CLI Neon Local PGlite
Cost free free Neon compute time on the branch free
Reset to empty compose down -v (~2 s) supabase db reset stop container (ephemeral branch deleted) new instance (~ms)
RLS + pgvector ✅ ✅ ✅ ✅ (@electric-sql/pglite-pgvector)
Auth / Storage / Realtime ❌ ✅ ❌ (Neon Auth lives in the cloud) ❌
Where the data lives Docker named volume Docker volumes Neon cloud memory, a directory, or IndexedDB
flowchart LR
  W["Windows 11 host<br/>Next.js dev · psql · TablePlus"]
  subgraph WSL["WSL 2 · Ubuntu"]
    D["Docker Engine<br/>(Desktop integration or apt)"]
    subgraph NET["compose network"]
      PG["pgvector/pgvector:0.8.7-pg18-trixie<br/>:5432"]
      RD["redis:8.10.2-alpine<br/>:6379"]
      SB["supabase start<br/>:54321 API · :54322 DB · :54323 Studio"]
      NL["neondatabase/neon_local:v1.5<br/>:5432 → Neon branch"]
    end
    V[("named volumes")]
  end
  T["vitest / node --test<br/>PGlite 0.5.10 in-process"]
  W -->|"127.0.0.1:5432<br/>WSL localhost forwarding"| PG
  D --- NET
  PG --- V
  RD --- V
  NL -.->|"HTTPS + API key"| NEON["Neon cloud branch"]
  PG -.->|"same engine, schema, RLS"| PROD["Supabase / Neon production"]
  T -.->|"same schema via migrations"| PROD

Official Documentation

Resource URL
Docker Desktop WSL 2 backend https://docs.docker.com/desktop/features/wsl/
Install Docker Engine on Ubuntu https://docs.docker.com/engine/install/ubuntu/
Compose file reference https://docs.docker.com/reference/compose-file/
Compose startup order (depends_on) https://docs.docker.com/compose/how-tos/startup-order/
Postgres official image https://hub.docker.com/_/postgres
pgvector/pgvector image https://hub.docker.com/r/pgvector/pgvector
Supabase CLI: getting started https://supabase.com/docs/guides/local-development/cli/getting-started
Supabase local migrations & seeding https://supabase.com/docs/guides/local-development/database-migrations
Neon Local https://neon.com/docs/local/neon-local
PGlite docs / extensions https://pglite.dev/docs/ · https://pglite.dev/extensions/
Node 24 node:sqlite https://nodejs.org/docs/latest-v24.x/api/sqlite.html
Turso SDKs (which package when) https://docs.turso.tech/sdk/introduction
Prisma ORM release status (7 vs 8) https://www.prisma.io/docs/orm/release-status
Prisma ORM 7 upgrade guide https://www.prisma.io/docs/guides/upgrade-prisma-orm/v7
Drizzle get started https://orm.drizzle.team/docs/get-started
PowerSync docs https://docs.powersync.com/
Electric sync docs https://electric-sql.com/docs/intro
Zero docs https://zero.rocicorp.dev/docs/introduction
WSL networking (NAT vs mirrored) https://learn.microsoft.com/en-us/windows/wsl/networking

Versions verified 2026-10-20

Thing Pin Notes
postgres image 18.6-trixie (latest == 18.6) 19rc1 and 19beta4 tags exist; don't pin pre-releases
pgvector/pgvector 0.8.7-pg18-trixie pgvector 0.8.7 (was 0.8.6)
redis 8.10.2-alpine (latest == 8.10.2)
mongo 8.0.34-noble mongo:latest is now 9.0.4; pin the major your Atlas cluster runs
mysql 9.7.2 (lts) latest == innovation == 26.7.0 (calendar versioning)
mariadb 12.3.3 (lts) mariadb:latest is now 13.0.2 (not LTS)
neondatabase/neon_local v1.5 (== latest, built 2025-09-25)
Node.js 24 LTS (tested on 24.15.0) node:sqlite = Stability 1.2 Release candidate since v24.15.0
@electric-sql/pglite 0.5.10 embeds PostgreSQL 18.6; pgvector via @electric-sql/pglite-pgvector 0.0.11
prisma / @prisma/client 7.10.1 npm latest for prisma is 8.0.0-rc.23 — see §9
drizzle-orm / drizzle-kit 0.45.4 / 0.31.11 rc tag = 1.0.0-rc.4; Drizzle's docs install @rc
supabase (CLI, npm) 2.121.0 Node ≥ 20 when run via npx
neonctl 8.8.0
better-sqlite3 13.0.3
@tursodatabase/database / @tursodatabase/sync 0.8.3 / 0.8.3 Turso Sync is beta
@libsql/client 0.18.0 embedded replicas
pg / postgres / mysql2 / ioredis / mongodb 8.23.1 / 3.4.9 / 3.24.6 / 6.0.0 / 7.7.0

1. Get a Docker daemon inside WSL Ubuntu

Two supported paths. Pick one, and do not run both.

Install Docker Desktop, then Settings → Resources → WSL integration → enable your Ubuntu distro. docker and docker compose then work inside Ubuntu, and published ports land on Windows localhost. See the [[docker]] guide.

Path B: Docker Engine straight into Ubuntu (no Desktop)

Inside the WSL Ubuntu shell (commands re-checked against docs.docker.com/engine/install/ubuntu/ on 2026-10-20; supported: Ubuntu 22.04, 24.04, 26.04 LTS and 26.10):

# 1. Docker's official GPG key
sudo apt update
sudo apt install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# 2. Add the repository to Apt sources
sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
sudo apt update

# 3. Install engine + CLI + compose plugin
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# 4. Run docker without sudo (then `wsl --shutdown` to pick up the group)
sudo usermod -aG docker $USER

# 5. Verify
docker run --rm hello-world
docker compose version

Enable systemd once so the daemon starts with the distro:

sudo tee /etc/wsl.conf <<'EOF'
[boot]
systemd=true
EOF
# then from PowerShell on the host:  wsl --shutdown

Without systemd, start the daemon each session with sudo service docker start.

Filesystem rule (same as [[docker]]): keep the project on the Linux filesystem (~/code/...), never /mnt/c/.... A database data directory bind-mounted from /mnt/c crosses the 9p boundary on every fsync. Named volumes live on the WSL VM's ext4 disk and avoid it.


2. Environment variables

One .env.local per app (gitignored), one .env next to compose.yaml for Compose interpolation (also gitignored). Only real secrets go on VAR= lines; even local dev passwords are treated as secrets so the habit protects the production string that later lives in the same file.

# .env / .env.local: local only, never committed
POSTGRES_PASSWORD=<dev-only-password>
DATABASE_URL=postgresql://app:<dev-only-password>@localhost:5432/appdb
# Only if you use Neon Local (§6): a real Neon API key, store it in Hazina
NEON_API_KEY=napi_...
# Only if you use Turso Sync / embedded replicas (§8)
TURSO_AUTH_TOKEN=...

Non-secret settings:

Variable Example Used by
REDIS_URL redis://localhost:6379 ioredis
NEON_PROJECT_ID <project-id> Neon Local
PARENT_BRANCH_ID / BRANCH_ID br-... Neon Local (mutually exclusive)
DELETE_BRANCH false to keep the branch after the container stops Neon Local
TURSO_DATABASE_URL libsql://<db>-<org>.turso.io Turso
SUPABASE_TELEMETRY_DISABLED 1 Supabase CLI
Supabase local DB URL postgresql://postgres:postgres@127.0.0.1:54322/postgres printed by supabase start; fixed well-known local creds

3. docker run one-liners (pinned tags)

Pin the minor version. latest moves: on 2026-10-20 mongo:latest jumped to 9.0 and mariadb:latest to 13.0, and a Postgres major bump silently invalidates the data directory.

Postgres 18 (+ pgvector)

docker run -d --name pg \
  -e POSTGRES_USER=app \
  -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
  -e POSTGRES_DB=appdb \
  -p 127.0.0.1:5432:5432 \
  -v pgdata:/var/lib/postgresql \
  pgvector/pgvector:0.8.7-pg18-trixie      # or postgres:18.6-trixie without pgvector

⚠️ Postgres 18 changed the volume target. For 18+ the image sets PGDATA=/var/lib/postgresql/18/docker and declares VOLUME /var/lib/postgresql. For 17 and below mount at /var/lib/postgresql/data; mounting 17 at the bare path writes to an anonymous volume and your data vanishes on re-create, silently.

# Postgres 17 and below: note the /data suffix
docker run -d --name pg17 -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
  -p 127.0.0.1:5432:5432 -v pg17data:/var/lib/postgresql/data postgres:17.11-trixie

The pgvector image ships the extension but your database still needs CREATE EXTENSION IF NOT EXISTS vector;, exactly like Supabase and Neon.

MySQL 9.7 LTS / MariaDB 12.3 LTS

docker run -d --name mysql -e MYSQL_ROOT_PASSWORD="$POSTGRES_PASSWORD" -e MYSQL_DATABASE=appdb \
  -p 127.0.0.1:3306:3306 -v mysqldata:/var/lib/mysql mysql:9.7.2

docker run -d --name mariadb -e MARIADB_ROOT_PASSWORD="$POSTGRES_PASSWORD" -e MARIADB_DATABASE=appdb \
  -p 127.0.0.1:3306:3306 -v mariadbdata:/var/lib/mysql mariadb:12.3.3

mysql:latest follows the Innovation track (calendar versioning, 26.7.0 = YY.M.P). mariadb:lts is 12.3.3; mariadb:latest is the short-term 13.0.2. MariaDB env vars are MARIADB_* (MYSQL_* are legacy aliases).

Redis 8

docker run -d --name redis -p 127.0.0.1:6379:6379 -v redisdata:/data \
  redis:8.10.2-alpine redis-server --save 60 1 --appendonly yes --loglevel warning

Redis persists nothing and has no password by default; the flags above turn on RDB snapshots + AOF. This is the local stand-in for [[upstash]]; see [[caching]].

MongoDB 8.0 (single-node replica set)

docker run -d --name mongo -p 127.0.0.1:27017:27017 -v mongodata:/data/db \
  mongo:8.0.34-noble --replSet rs0 --bind_ip_all
docker exec -it mongo mongosh --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})'
# mongodb://localhost:27017/appdb?replicaSet=rs0&directConnection=true

Transactions and change streams need a replica set even locally. mongo:latest is now 9.0.4: match your Atlas cluster's major instead of following latest. See [[mongodb]].

Why 127.0.0.1:PORT:PORT

-p 5432:5432 binds 0.0.0.0 inside the WSL VM. With mirrored networking, a netsh portproxy, or a café network, that is a database with a dev password answering the LAN. -p 127.0.0.1:5432:5432 costs nothing. Make it the default.


4. The whole local stack: compose.yaml

The runnable file is examples/compose.yaml: pgvector-Postgres 18.6 + Redis 8.10.2, an opt-in Mongo profile, healthchecks, named volumes, loopback-only ports, and ${POSTGRES_PASSWORD:?} interpolation so no password is committed. The core:

name: appdb-local            # no top-level `version:` key: obsolete, Compose warns
services:
  postgres:
    image: pgvector/pgvector:0.8.7-pg18-trixie
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
      POSTGRES_DB: appdb
    ports: ["127.0.0.1:5432:5432"]
    volumes:
      - pgdata:/var/lib/postgresql              # pg18+ target, NOT /data
      - ./db/init:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 5s
      retries: 10
      start_period: 20s
volumes:
  pgdata:
docker compose up -d && docker compose ps     # STATUS shows (healthy)
docker compose exec postgres psql -U app -d appdb
docker compose --profile mongo up -d          # add Mongo when the project needs it

An app service must wait for a healthy DB (depends_on: {postgres: {condition: service_healthy}}); the short list form only waits for started. Inside the Compose network use the service name + container port (postgres:5432); from the Windows host use localhost:5432.

Seeding with /docker-entrypoint-initdb.d

Scripts run in alphabetical order only on first init of an empty data directory (Postgres: .sh, .sql, .sql.gz/.xz/.zst; Mongo: .sh, .js).

-- db/init/001_schema.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE deliveries (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id   uuid NOT NULL,
  rider_phone text NOT NULL CHECK (rider_phone ~ '^254[0-9]{9}$'),
  fare_kes    integer NOT NULL CHECK (fare_kes > 0),
  created_at  timestamptz NOT NULL DEFAULT now()
);

-- Mirror production: RLS on locally too.
ALTER TABLE deliveries ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON deliveries
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid);

Once a project has real migrations (Prisma/Drizzle/Supabase, §5 and §9), keep db/init to extensions only and let the migration tool own the schema, so there is one source of truth.


5. Supabase CLI local stack

When the feature touches Supabase Auth, Storage, Realtime, PostgREST or Edge Functions, a bare Postgres container is not enough. The Supabase CLI runs the whole stack in Docker.

npm install supabase@2.121.0 --save-dev     # pin per project; Windows alt: scoop install supabase
npx supabase init                           # creates ./supabase (commit it) + config.toml
npx supabase start                          # first run pulls every image; slow once

supabase start prints the local endpoints. The defaults:

Service URL
API gateway (REST, Auth, Storage, Realtime, Functions) http://127.0.0.1:54321
Postgres postgresql://postgres:postgres@127.0.0.1:54322/postgres
Studio http://127.0.0.1:54323
Mailpit (captured auth emails) http://127.0.0.1:54324
Local MCP endpoint http://127.0.0.1:54321/mcp

Keys print as sb_publishable_... / sb_secret_...; they are local-only but the secret key still never goes in client code.

The migration loop:

npx supabase migration new add_deliveries     # writes supabase/migrations/<ts>_add_deliveries.sql
npx supabase db reset                         # re-create local DB: all migrations + supabase/seed.sql
npx supabase db diff --schema public -f fix   # capture changes made in Studio as a migration
npx supabase gen types typescript --local > lib/database.types.ts
npx supabase stop                             # keeps data; `stop --no-backup` deletes it
# Ship: npx supabase link --project-ref <ref> && npx supabase db push

Full Supabase detail lives in [[supabase]].


6. Neon Local

Neon Local is not a local Postgres. It is a proxy container that gives your app a localhost:5432 endpoint and routes it to a Neon cloud branch, either an existing one (BRANCH_ID) or an ephemeral branch created on container start and deleted on stop (PARENT_BRANCH_ID, the default behaviour).

# compose.override.yaml: Neon Local instead of the local Postgres container
services:
  db:
    image: neondatabase/neon_local:v1.5
    ports: ["127.0.0.1:5432:5432"]
    environment:
      NEON_API_KEY: ${NEON_API_KEY}
      NEON_PROJECT_ID: ${NEON_PROJECT_ID}
      PARENT_BRANCH_ID: ${PARENT_BRANCH_ID}   # omit → branch from the default branch
      # DELETE_BRANCH: "false"                # keep it after `down`
    # Persistent branch per git branch:
    # volumes:
    #   - ./.neon_local/:/tmp/.neon_local      # add .neon_local/ to .gitignore
    #   - ./.git/HEAD:/tmp/.git/HEAD:ro,consistent

Connect with postgres://neon:npg@localhost:5432/<db>?sslmode=require. The proxy uses a self-signed certificate, so pg/postgres.js need ssl: { rejectUnauthorized: false } for this localhost proxy only; never copy that into the production config. The Neon serverless driver works over HTTP only:

import { neon, neonConfig } from "@neondatabase/serverless"; // 1.2.0

neonConfig.fetchEndpoint = "http://localhost:5432/sql";
neonConfig.useSecureWebSocket = false;
neonConfig.poolQueryViaFetch = true;
const sql = neon("postgres://neon:npg@localhost:5432/neondb");

Use it when the thing under test depends on Neon itself (branch data, Neon extensions, prod-sized data). It needs the network and bills compute, so it is not the offline story. neonctl 8.8.0 (npx neonctl branches create, connection-string) covers scripted branches; see [[neon]].


7. PGlite: Postgres 18.6 inside your process

@electric-sql/pglite 0.5.10 is real Postgres (18.6 at this version, confirmed with SELECT version()) compiled to WASM. No Docker, no port, starts in milliseconds, one fresh database per test.

import { PGlite } from "@electric-sql/pglite";
import { vector } from "@electric-sql/pglite-pgvector"; // separate package now

const mem = await PGlite.create({ extensions: { vector } });              // memory://
const disk = await PGlite.create("./.pglite/dev", { extensions: { vector } }); // Node: directory
// Browser: new PGlite("idb://my-app")  (IndexedDB)
await mem.exec("CREATE EXTENSION IF NOT EXISTS vector;");
const { rows } = await mem.query<{ v: string }>("SELECT version() AS v");

8. SQLite family: node:sqlite, better-sqlite3, Turso

SQLite is the right store on the device: CLI tools, kiosk/POS terminals, desktop apps, mobile caches, and the outbox of an offline-first app.

node:sqlite (built into Node)

Node line Status
v22.13.0 / v23.4.0 unflagged (no --experimental-sqlite), still experimental
v24.15.0 (current LTS line) Stability 1.2: Release candidate

Tested on Node 24.15.0 (SQLite 3.51.3), no warning printed. Synchronous API: new DatabaseSync(path, { enableForeignKeyConstraints, timeout, readBigInts, ... }), db.exec(), db.prepare() → run/get/all/iterate, plus sqlite.backup() (async) and session/changeset APIs (createSession, applyChangeset). Runnable offline outbox: examples/offline-outbox.mts (zero dependencies).

codeAmani rule: node:sqlite is fine for local tools, scripts, kiosks and test fixtures. For a long-running production server keep better-sqlite3 13.0.3 (stable, native addon) until node:sqlite reaches Stability 2.

Turso / libSQL

Package Use
@tursodatabase/database 0.8.3 local/embedded Turso Database (the Rust SQLite rewrite); connect("local.db")
@tursodatabase/sync 0.8.3 local-first reads and writes with explicit push() / pull() to Turso Cloud (beta)
@libsql/client 0.18.0 libSQL client; embedded replicas (local reads, writes go to the cloud primary, client.sync())

Turso's own guidance: if a local database is involved, use the @tursodatabase/* packages; for offline writes and multi-writer convergence, @tursodatabase/sync. Drizzle support for @tursodatabase/database is beta.


9. ORMs: migrations and seeding locally

Prisma ORM 7 (pin it)

⚠️ npm install prisma / npx prisma now install the Prisma 8 release candidate (prisma npm latest = 8.0.0-rc.23, docs default to v8). The v8 CLI does not read schema.prisma and has no generate, migrate dev or db push. Prisma 8 is RC (GA expected October 2026), PostgreSQL-only at RC quality (SQLite experimental, MySQL "coming soon"), and lacks $extends, most nested writes and isolation levels. Stay on 7: "prisma": "^7" and "@prisma/client": "^7" (both 7.10.1 today), and write npx prisma@7 in CI. Prisma 7 gets fixes for 18 months after v8 GA; Prisma 6 security patches end 2026-11-19.

Prisma 7 changes that bite in local dev (all from the v7 upgrade guide):

Runnable: examples/prisma7/ (schema.prisma, prisma.config.ts, src/db.ts, prisma/seed.ts; type-checked against 7.10.1).

npm i @prisma/client@7.10.1 @prisma/adapter-pg@7.10.1 dotenv && npm i -D prisma@7.10.1 tsx
npx prisma@7 migrate dev --name init   # create + apply migration to the local DB
npx prisma@7 generate                  # no longer implicit
npx prisma@7 db seed                   # no longer implicit
npx prisma@7 migrate reset             # drop + re-apply (local only)

Drizzle ORM

npm latest is 0.45.4 (drizzle-kit 0.31.11). Drizzle's get-started pages now install drizzle-orm@rc / drizzle-kit@rc (1.0.0-rc.4, published 2026-06-27; the roadmap shows v1 at "98%"). codeAmani pins 0.45.4 for app code until 1.0 is tagged latest; trying the RC on a branch is fine.

// drizzle.config.ts
import "dotenv/config";
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  out: "./drizzle",
  schema: "./src/db/schema.ts",
  dialect: "postgresql",
  dbCredentials: { url: process.env.DATABASE_URL! },
});
npx drizzle-kit generate   # SQL migration files from schema diffs (commit them)
npx drizzle-kit migrate    # apply to DATABASE_URL
npx drizzle-kit push       # prototype only: sync schema without migration files
npx drizzle-kit studio     # local data browser

The same schema runs on drizzle-orm/node-postgres (container/Supabase/Neon Local), drizzle-orm/pglite (tests) and drizzle-orm/neon-http (prod). drizzle-seed (0.3.1) generates deterministic fake rows.

Seeding rules (any tool)

  1. Seeds are deterministic and idempotent (fixed UUIDs, deleteMany / ON CONFLICT DO NOTHING), so reset → seed is repeatable.
  2. Seeds use realistic formats: integer KES, 254XXXXXXXXX phones, Africa/Nairobi timestamps for Kenya-targeted projects; ZIP codes and USD cents for US projects.
  3. Seeds never contain production data or real customer phone numbers. Use Daraja's sandbox test number 254708374149 and obviously fake ranges.

10. Connecting from the Windows host and Next.js

WSL 2's default NAT mode forwards published ports to Windows localhost, so psql, TablePlus, DBeaver, Prisma/Drizzle Studio and a host-side next dev all reach localhost:5432. Docker Desktop does the same through its proxy.

psql "postgresql://app:<dev-only-password>@localhost:5432/appdb"
wsl.exe hostname -I        # distro IP, rarely needed in NAT mode

Windows 11 22H2+ mirrored mode ([wsl2] networkingMode=mirrored in %UserProfile%\.wslconfig, then wsl --shutdown) shares one loopback both ways, and also makes WSL reachable from the LAN, which is why every -p above starts with 127.0.0.1:.

Use a pooled client held on globalThis so Next.js HMR doesn't open a new pool per reload, and parameterized queries only. Runnable: examples/db.ts (pg 8.23.1, getDeliveries, and withTenant() that sets app.tenant_id with set_config(..., true) inside a transaction so RLS behaves as on Supabase). TLS is decided from the parsed hostname: off for localhost/127.0.0.1, verified everywhere else.


11. Offline-first sync (low-connectivity users)

A local dev database helps the developer. A local client database helps the user whose connection drops. Pattern: the app reads and writes a database on the device (SQLite, PGlite or IndexedDB), and a sync layer reconciles with Postgres when the uplink returns.

Engine Model Writes Status (2026-10-20) Notes
PowerSync Postgres / MongoDB / MySQL → client SQLite Local first → upload queue → your backend API validates Postgres GA; Open Edition (self-host) GA SDKs @powersync/web 2.5.0, @powersync/react-native 2.3.3, @powersync/node 1.2.0; Supabase integration guide; "Sync Streams" config
Electric Postgres → shapes streamed over HTTP Read-path only: writes go through your API Open source; Electric Cloud managed @electric-sql/client 1.5.28; pairs with PGlite via @electric-sql/pglite-sync 0.6.11
Zero (Rocicorp) Postgres → zero-cache (SQLite replica) → client Custom mutators via your /mutate endpoint 1.x (@rocicorp/zero 1.11.0; docs show rocicorp/zero:1.10.0 image) Needs wal_level=logical and a direct (non-pgbouncer) upstream connection
Turso Sync Turso Cloud ↔ local Turso DB Local reads and writes, explicit push()/pull() Beta @tursodatabase/sync 0.8.3; SQLite-shaped, not Postgres
DIY outbox Any Local SQLite outbox + idempotency key, flush on reconnect — examples/offline-outbox.mts; enough for "queue orders while offline"

Decision rule: if you only need "don't lose the user's action while offline", the DIY outbox is enough. If users need to read and edit shared data for hours offline, use PowerSync (writes-through-your-API matches codeAmani's "server validates everything" rule). Electric is the read-heavy choice. Zero is the reactive-UI choice when you are online most of the time. Pricing for the hosted tiers was not verified in this refresh: check each vendor's pricing page before committing.


12. Teardown, reset, inspection

docker compose stop                  # pause; data survives
docker compose down                  # remove containers + network; volumes SURVIVE
docker compose down -v               # remove volumes too: the true reset (re-runs db/init)
docker compose up -d --force-recreate --pull always

docker volume ls && docker system df
docker system prune -a --volumes     # nuclear: everything unused, all projects

# Back up / restore a local Postgres
docker compose exec -T postgres pg_dump -U app -d appdb > backup.sql
docker compose exec -T postgres psql -U app -d appdb < backup.sql

npx supabase db reset                # Supabase CLI equivalent of down -v + migrate + seed
npx prisma@7 migrate reset           # Prisma equivalent against DATABASE_URL

13. Picking the store

flowchart TD
  A["What are you testing?"] --> B{"Supabase Auth / Storage /<br/>Realtime / Edge Functions?"}
  B -->|yes| SB["supabase start (CLI 2.121.0)"]
  B -->|no| C{"Unit / integration tests<br/>that need Postgres?"}
  C -->|yes| PGL["PGlite 0.5.10 per test<br/>(Postgres 18.6, pgvector)"]
  C -->|no| D{"Need Neon branch data<br/>or Neon-only features?"}
  D -->|yes| NL["Neon Local v1.5<br/>ephemeral branch"]
  D -->|no| E{"Shape?"}
  E -->|"relational + embeddings"| PV["pgvector/pgvector:0.8.7-pg18-trixie"]
  E -->|"cache · rate limits · queue"| RD["redis:8.10.2-alpine"]
  E -->|"documents"| MG["mongo:8.0.34-noble + replSet"]
  E -->|"on-device / offline"| SQ["node:sqlite · better-sqlite3 13 · Turso"]
  E -->|"legacy MySQL"| MY["mysql:9.7.2 / mariadb:12.3.3 (LTS)"]

codeAmani notes


Troubleshooting

Issue Fix
Cannot connect to the Docker daemon in WSL Path B without systemd: sudo service docker start, or [boot] systemd=true in /etc/wsl.conf + wsl --shutdown
permission denied ... /var/run/docker.sock sudo usermod -aG docker $USER, then wsl --shutdown
Data gone after recreate (Postgres ≤17) Mounted at /var/lib/postgresql instead of /var/lib/postgresql/data. 18+ uses the bare path
database files are incompatible with server Volume initialized by another Postgres major. pg_dump from the old tag, down -v, restore
port is already allocated Native Windows Postgres, or supabase start and a container both want a port. Remap: -p 127.0.0.1:55432:5432
Windows can't reach localhost:5432 after sleep/VPN wsl --shutdown, restart the distro; or try networkingMode=mirrored
App container ECONNREFUSED postgres:5432 Add depends_on: {postgres: {condition: service_healthy}} + pg_isready healthcheck
type "vector" does not exist CREATE EXTENSION vector; (container) or pass extensions: { vector } from @electric-sql/pglite-pgvector (PGlite)
Cannot find module '@electric-sql/pglite/vector' pgvector moved to the @electric-sql/pglite-pgvector package
npx prisma generate: unknown command / schema ignored You got the Prisma 8 RC CLI. npm i -D prisma@7 and use npx prisma@7
Prisma 7: DATABASE_URL undefined in CLI v7 doesn't load .env; add import "dotenv/config" to prisma.config.ts
Prisma 7: seed didn't run after migrate dev Expected in v7: run npx prisma@7 db seed
Prisma 7 hangs connecting pg has no connect timeout by default; set connectionTimeoutMillis on PrismaPg
Drizzle docs code fails on 0.45.4 The docs target @rc (1.0). Match the docs version or pin and read the 0.x docs
Neon Local: self-signed certificate Expected: ssl: { rejectUnauthorized: false } for the localhost proxy only
Neon serverless driver can't reach Neon Local It supports HTTP only: set fetchEndpoint, useSecureWebSocket = false, poolQueryViaFetch = true
supabase start port clash between two worktrees One stack per machine on default ports; change ports in each config.toml
Mongo: Transaction numbers are only allowed on a replica set member Start with --replSet rs0 --bind_ip_all, run rs.initiate(...) once
Redis empty after restart Pass --save 60 1 --appendonly yes and mount /data
Postgres crawls / fsync storms Data on /mnt/c via bind mount. Use a named volume
the attribute 'version' is obsolete Delete the top-level version: key

Official docs: