Skip to content

Kysely Codegen with added support for planetscale. (Use planetscale branch). A PR will be submitted when the kysely codegen already has a plugin system. See this PR (https://github.com/RobinBlomberg/kysely-codegen/pull/58) for more detailed explanation

License

Notifications You must be signed in to change notification settings

harisraharjo/kysely-codegen

 
 

Repository files navigation

Kysely Codegen

kysely-codegen generates Kysely type definitions from your database. That's it.

Table of contents

Installation

npm install --save-dev kysely-codegen

# You will also need to install Kysely with your driver of choice:
npm install kysely pg
npm install kysely mysql2
npm install kysely better-sqlite3

Generating type definitions

The most convenient way to get started is to create an .env file with your database connection string:

# PostgreSQL
DATABASE_URL=postgres://username:[email protected]/database

# MySQL
DATABASE_URL=mysql://username:[email protected]/database

# SQLite
DATABASE_URL=C:/Program Files/sqlite3/db

Then run:

kysely-codegen

This command will generate a .d.ts file from your database, for example:

import { Generated, ColumnType } from 'kysely';

export type Timestamp = ColumnType<Date, Date | string, Date | string>;

export interface Company {
  id: Generated<number>;
  name: string;
}

export interface User {
  company_id: number | null;
  created_at: Generated<Timestamp>;
  email: string;
  id: Generated<number>;
  is_active: boolean;
  name: string;
  updated_at: Timestamp;
}

export interface DB {
  company: Company;
  user: User;
}

For more options, run kysely-codegen --help.

Using the type definitions

Import DB into new Kysely<DB>, and you're done!

import { Kysely, PostgresDialect } from 'kysely';
import { DB } from 'kysely-codegen';
import { Pool } from 'pg';

const db = new Kysely<DB>({
  dialect: new PostgresDialect({
    pool: new Pool({
      connectionString: process.env.DATABASE_URL,
    }),
  }),
});

const rows = await db.selectFrom('user').selectAll().execute();
// [
//   {
//     company_id: number | null;
//     created_at: Date;
//     email: string;
//     id: number;
//     is_active: boolean;
//     name: string;
//     updated_at: Date;
//   }
// ]

About

Kysely Codegen with added support for planetscale. (Use planetscale branch). A PR will be submitted when the kysely codegen already has a plugin system. See this PR (https://github.com/RobinBlomberg/kysely-codegen/pull/58) for more detailed explanation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 99.9%
  • JavaScript 0.1%