Skip to content

Kysely extension for Kanel

Generate Kysely types directly from your Postgres database. This packages extends Kanel with some Kysely specific features. Check ./example/.kanelrc.js for how to customize your schema generation.

typescript
// @generated
// This file is automatically generated by Kanel. Do not modify manually.

import type { ColumnType, Selectable, Insertable, Updateable } from "kysely";

/** Identifier type for actor */
export type ActorId = number & { __flavor?: "ActorId" };

/** Represents the table public.actor */
export default interface ActorTable {
  /** Database type: pg_catalog.int4 */
  actor_id: ColumnType<ActorId, ActorId | null, ActorId | null>;

  /** Database type: pg_catalog.varchar */
  first_name: ColumnType<string, string, string | null>;

  /** Database type: pg_catalog.varchar */
  last_name: ColumnType<string, string, string | null>;

  /** Database type: pg_catalog.timestamp */
  last_update: ColumnType<Date, Date | null, Date | null>;
}

export type Actor = Selectable<ActorTable>;

export type NewActor = Insertable<ActorTable>;

export type ActorUpdate = Updateable<ActorTable>;

Assuming you already have Kanel installed, add this with

bash
$ npm i -D kanel-kysely

To use it, add it to your .kanelrc.js file:

javascript
const { makeKyselyHook } = require("kanel-kysely");

module.exports = {
  // ... your config here.

  preRenderHooks: [makeKyselyHook()],
};

Note About Branded IDs

Kanel generates some types with extra guards.

typescript
/** Identifier type for actor */
export type ActorId = number & { __flavor?: "ActorId" };

{ __flavor?: 'ActorId' } exists at build time and not at runtime. It will prevent you from accidentally passing an incorrect value for the Id.

To pass a string value as primary key or foreign key reference, just add a type assertion for the <table>Id generated type.

In cases such as subqueries, the type assertion will happen automatically.

Usage with CamelCasePlugin

If you use Kysely with CamelCasePlugin then append kyselyCamelCaseHook to preRenderHooks:

ts
const { makeKyselyHook, kyselyCamelCaseHook } = require("kanel-kysely");

module.exports = {
  // ... your config here.

  preRenderHooks: [makeKyselyHook(), kyselyCamelCaseHook],
};

Type Filter

If you're using Kysely for migrations, you might want to filter the types of the migration tables, such as kysely_migration and kysely_migration_lock. The kyselyTypeFilter will do this for you.

ts
  const { kyselyTypeFilter } = require("kanel-kysely");

  module.exports = {
    /// ... your config here.

    typeFilter: kyselyTypeFilter,
  };