Database Client
Unlike Prisma, ZenStack doesn't bundle any database driver. You're responsible for installing a compatible one. Also it doesn't read database connection string from the schema. Instead, you pass in the connection information when creating the client.
The zen generate
command compiles the ZModel schema into TypeScript code, which we can in turn use to initialize a type-safe database client. ZenStack uses Kysely to handle the low-level database operations, so the client is initialize with a Kysely dialect - an object that encapsulates database details.
The samples below only shows creating a client using SQLite (via better-sqlite3) and PostgreSQL (via node-postgres), however you can also use any other Kysely dialects for these two types of databases.
- SQLite
- PostgreSQL
- npm
- pnpm
- bun
- yarn
npm install --save-dev @types/better-sqlite3
npm install better-sqlite3
pnpm add --save-dev @types/better-sqlite3
pnpm add better-sqlite3
bun add --dev @types/better-sqlite3
bun add better-sqlite3
yarn add --dev @types/better-sqlite3
yarn add better-sqlite3
import { ZenStackClient } from '@zenstackhq/runtime';
import { SqliteDialect } from 'kysely';
import SQLite from 'better-sqlite3';
import { schema } from '@/zenstack/schema';
export const db = new ZenStackClient(schema, {
dialect: new SqliteDialect({
database: new SQLite(':memory:'),
}),
});
- npm
- pnpm
- bun
- yarn
npm install --save-dev @types/pg
npm install pg
pnpm add --save-dev @types/pg
pnpm add pg
bun add --dev @types/pg
bun add pg
yarn add --dev @types/pg
yarn add pg
import { ZenStackClient } from '@zenstackhq/runtime';
import { schema } from '@/zenstack/schema';
import { PostgresDialect } from 'kysely';
import { Pool } from 'pg';
export const db = new ZenStackClient(schema, {
dialect: new PostgresDialect({
pool: new Pool({
connectionString: process.env.DATABASE_URL,
}),
}),
});
The created db
object has the full ORM API inferred from the type of the schema
parameter. When necessary, you can also explicitly get the inferred client type like:
import type { ClientContract } from '@zenstackhq/runtime';
import type { SchemaType } from '@/zenstack/schema';
export type DbClient = ClientContract<SchemaType>;