Kernlift
Database

Write a custom database adapter

Register your own connection for the Postgres or SQLite schema family and select it with DATABASE_ADAPTER.

Database connections are resolved through an adapter registry. The built-in adapters are sqlite, postgres, turso and d1; you can register your own, for example to use a company-specific Postgres driver or connection pool.

Before you begin

  • A Drizzle-compatible database client for an existing schema family: postgres or sqlite.
  • A place in your server code that runs before the first database access.

Same schema, different connection

An adapter changes only how the app connects. A completely new SQL dialect, such as MySQL, also needs its own schema file, migration chain and repository branches.

Register the adapter

Call registerDatabaseAdapter

Register it before the first getDatabase() call:

src/server/db/my-company-postgres.ts
import { registerDatabaseAdapter } from "./client";

registerDatabaseAdapter({
  id: "my-company-postgres",
  dialect: "postgres",
  runtime: "my-company-postgres",
  canHandle: ({ config }) => Boolean(config.database.url),
  create: ({ config }) => ({
    adapter: "my-company-postgres",
    dialect: "postgres",
    runtime: "my-company-postgres",
    db: createMyDrizzlePostgresClient(config.database.url),
  }),
  missingPackageHint: "Set DATABASE_URL to use my-company-postgres.",
});

canHandle returns whether the adapter can run in this environment. create returns the Drizzle database object. missingPackageHint is optional and is appended to the error when canHandle returns false.

Select it

.env
DATABASE_DIALECT=postgres
DATABASE_ADAPTER=my-company-postgres
DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/postgres

DATABASE_DIALECT must match the adapter's dialect, so migrations use the right chain.

Migrate

pnpm db:migrate

The adapter contract and registration flow are in adapter-registry.ts: registerDatabaseAdapter, listDatabaseAdapters and resolveDatabaseAdapter.

Verify

  • The app starts and /admin loads with the adapter selected.
  • pnpm validate:db-adapters passes.

Troubleshooting

DATABASE_ADAPTER="…" is not registered.

The adapter was registered after the first database access, or not at all. The error lists the registered ids. Move the registration earlier.

Database adapter "…" cannot run in this environment.

canHandle returned false, for example because DATABASE_URL is empty. The message ends with your missingPackageHint.

Database adapter "…" is already registered

An adapter with that id exists. Choose a different id.

Reference

Next steps