Skip to main content
Version: 3.0 Alpha

Database 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.

npm install --save-dev @types/better-sqlite3
npm install better-sqlite3
db.ts
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:'),
}),
});

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>;
Comments
Feel free to ask questions, give feedback, or report issues.

Don't Spam


You can edit/delete your comments by going directly to the discussion, clicking on the 'comments' link below