{"id":13469475,"url":"https://github.com/RobinBlomberg/kysely-codegen","last_synced_at":"2025-03-26T06:32:12.842Z","repository":{"id":38833977,"uuid":"484872647","full_name":"RobinBlomberg/kysely-codegen","owner":"RobinBlomberg","description":"Generate Kysely type definitions from your database.","archived":false,"fork":false,"pushed_at":"2024-10-29T09:48:18.000Z","size":1230,"stargazers_count":789,"open_issues_count":47,"forks_count":72,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-29T11:51:27.520Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RobinBlomberg.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"RobinBlomberg"}},"created_at":"2022-04-23T22:47:18.000Z","updated_at":"2024-10-28T14:40:22.000Z","dependencies_parsed_at":"2023-10-11T07:11:09.959Z","dependency_job_id":"fc48294c-7dde-48bf-9ed0-5d53930c669f","html_url":"https://github.com/RobinBlomberg/kysely-codegen","commit_stats":{"total_commits":87,"total_committers":9,"mean_commits":9.666666666666666,"dds":0.1724137931034483,"last_synced_commit":"5d340f3e482aee72f52e57a430a72c6b9f961ebf"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobinBlomberg%2Fkysely-codegen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobinBlomberg%2Fkysely-codegen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobinBlomberg%2Fkysely-codegen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobinBlomberg%2Fkysely-codegen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RobinBlomberg","download_url":"https://codeload.github.com/RobinBlomberg/kysely-codegen/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245562956,"owners_count":20635907,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T15:01:41.500Z","updated_at":"2025-03-26T06:32:12.836Z","avatar_url":"https://github.com/RobinBlomberg.png","language":"TypeScript","funding_links":["https://github.com/sponsors/RobinBlomberg","https://polar.sh/RobinBlomberg"],"categories":["TypeScript","\u003ca name=\"TypeScript\"\u003e\u003c/a\u003eTypeScript","Type Generators"],"sub_categories":[],"readme":"# ![kysely-codegen](./assets/kysely-codegen-logo.svg) \u003c!-- omit from toc --\u003e\n\n`kysely-codegen` generates Kysely type definitions from your database. That's it.\n\n## Table of contents \u003c!-- omit from toc --\u003e\n\n- [Installation](#installation)\n- [Generating type definitions](#generating-type-definitions)\n- [Using the type definitions](#using-the-type-definitions)\n- [CLI arguments](#cli-arguments)\n- [Configuration file](#configuration-file)\n- [Issue funding](#issue-funding)\n\n## Installation\n\n```sh\nnpm install --save-dev kysely-codegen\n```\n\nYou will also need to install Kysely with your driver of choice:\n\n```sh\n# PostgreSQL\nnpm install kysely pg\n\n# MySQL\nnpm install kysely mysql2\n\n# SQLite\nnpm install kysely better-sqlite3\n\n# MSSQL\nnpm install kysely tedious tarn @tediousjs/connection-string\n\n# LibSQL\nnpm install @libsql/kysely-libsql\n```\n\n## Generating type definitions\n\nThe most convenient way to get started is to create an `.env` file with your database connection string:\n\n```sh\n# PostgreSQL\nDATABASE_URL=postgres://username:password@yourdomain.com/database\n\n# MySQL\nDATABASE_URL=mysql://username:password@yourdomain.com/database\n\n# SQLite\nDATABASE_URL=C:/Program Files/sqlite3/db\n\n# MSSQL\nDATABASE_URL=Server=mssql;Database=database;User Id=user;Password=password\n\n# LibSQL\nDATABASE_URL=libsql://token@host:port/database\n```\n\n\u003e If your URL contains a password with special characters, those characters may need to be [percent-encoded](https://en.wikipedia.org/wiki/Percent-encoding#Reserved_characters).\n\u003e\n\u003e If you are using _PlanetScale_, make sure your URL contains this SSL query string parameter: `ssl={\"rejectUnauthorized\":true}`\n\nThen run the following command, or add it to the scripts section in your package.json file:\n\n```sh\nkysely-codegen\n```\n\nThis command will generate a `.d.ts` file from your database, for example:\n\n\u003c!-- prettier-ignore --\u003e\n```ts\nimport { ColumnType } from 'kysely';\n\nexport type Generated\u003cT\u003e = T extends ColumnType\u003cinfer S, infer I, infer U\u003e\n  ? ColumnType\u003cS, I | undefined, U\u003e\n  : ColumnType\u003cT, T | undefined, T\u003e;\n\nexport type Timestamp = ColumnType\u003cDate, Date | string, Date | string\u003e;\n\nexport interface Company {\n  id: Generated\u003cnumber\u003e;\n  name: string;\n}\n\nexport interface User {\n  company_id: number | null;\n  created_at: Generated\u003cTimestamp\u003e;\n  email: string;\n  id: Generated\u003cnumber\u003e;\n  is_active: boolean;\n  name: string;\n  updated_at: Timestamp;\n}\n\nexport interface DB {\n  company: Company;\n  user: User;\n}\n```\n\nTo specify a different output file:\n\n```sh\nkysely-codegen --out-file ./src/db/db.d.ts\n```\n\n## Using the type definitions\n\nImport `DB` into `new Kysely\u003cDB\u003e`, and you're done!\n\n```ts\nimport { Kysely, PostgresDialect } from 'kysely';\nimport { DB } from 'kysely-codegen';\nimport { Pool } from 'pg';\n\nconst db = new Kysely\u003cDB\u003e({\n  dialect: new PostgresDialect({\n    pool: new Pool({\n      connectionString: process.env.DATABASE_URL,\n    }),\n  }),\n});\n\nconst rows = await db.selectFrom('users').selectAll().execute();\n//    ^ { created_at: Date; email: string; id: number; ... }[]\n```\n\nIf you need to use the generated types in e.g. function parameters and type definitions, you may need to use the Kysely `Insertable`, `Selectable`, `Updateable` types. Note that you don't need to explicitly annotate query return values, as it's recommended to let Kysely infer the types for you.\n\n```ts\nimport { Insertable, Updateable } from 'kysely';\nimport { DB } from 'kysely-codegen';\nimport { db } from './db';\n\nasync function insertUser(user: Insertable\u003cUser\u003e) {\n  return await db\n    .insertInto('users')\n    .values(user)\n    .returningAll()\n    .executeTakeFirstOrThrow();\n  // ^ Selectable\u003cUser\u003e\n}\n\nasync function updateUser(id: number, user: Updateable\u003cUser\u003e) {\n  return await db\n    .updateTable('users')\n    .set(user)\n    .where('id', '=', id)\n    .returning(['email', 'id'])\n    .executeTakeFirstOrThrow();\n  // ^ { email: string; id: number; }\n}\n```\n\nRead the [Kysely documentation](https://kysely.dev/docs/getting-started) for more information.\n\n## CLI arguments\n\n#### --camel-case \u003c!-- omit from toc --\u003e\n\nUse the Kysely CamelCasePlugin for generated table column names.\n\n**Example:**\n\n```ts\nexport interface User {\n  companyId: number | null;\n  createdAt: Generated\u003cTimestamp\u003e;\n  email: string;\n  id: Generated\u003cnumber\u003e;\n  isActive: boolean;\n  name: string;\n  updatedAt: Timestamp;\n}\n```\n\n#### --date-parser \u003c!-- omit from toc --\u003e\n\nSpecify which parser to use for PostgreSQL date values. (values: `string`/`timestamp`, default: `timestamp`)\n\n#### --default-schema [value] \u003c!-- omit from toc --\u003e\n\nSet the default schema(s) for the database connection.\n\nMultiple schemas can be specified:\n\n```sh\nkysely-codegen --default-schema=public --default-schema=hidden\n```\n\n#### --dialect [value] \u003c!-- omit from toc --\u003e\n\nSet the SQL dialect. (values: `postgres`/`mysql`/`sqlite`/`mssql`/`libsql`/`bun-sqlite`/`kysely-bun-sqlite`/`worker-bun-sqlite`)\n\n#### --env-file [value] \u003c!-- omit from toc --\u003e\n\nSpecify the path to an environment file to use.\n\n#### --help, -h \u003c!-- omit from toc --\u003e\n\nPrint all command line options.\n\n#### --include-pattern [value], --exclude-pattern [value] \u003c!-- omit from toc --\u003e\n\nYou can choose which tables should be included during code generation by providing a glob pattern to the `--include-pattern` and `--exclude-pattern` flags. We use [micromatch](https://github.com/micromatch/micromatch) under the hood, which provides advanced glob support. For instance, if you only want to include your public tables:\n\n```sh\nkysely-codegen --include-pattern=\"public.*\"\n```\n\nYou can also include only certain tables within a schema:\n\n```sh\nkysely-codegen --include-pattern=\"public.+(user|post)\"\n```\n\nOr exclude an entire class of tables:\n\n```sh\nkysely-codegen --exclude-pattern=\"documents.*\"\n```\n\n#### --log-level [value] \u003c!-- omit from toc --\u003e\n\nSet the terminal log level. (values: `debug`/`info`/`warn`/`error`/`silent`, default: `warn`)\n\n#### --no-domains \u003c!-- omit from toc --\u003e\n\nSkip generating types for PostgreSQL domains. (default: `false`)\n\n#### --numeric-parser \u003c!-- omit from toc --\u003e\n\nSpecify which parser to use for PostgreSQL numeric values. (values: `string`/`number`/`number-or-string`, default: `string`)\n\n#### --overrides \u003c!-- omit from toc --\u003e\n\nSpecify type overrides for specific table columns in JSON format.\n\n**Example:**\n\n```sh\nkysely-codegen --overrides='{\"columns\":{\"table_name.column_name\":\"{foo:\\\"bar\\\"}\"}}'\n```\n\n#### --out-file [value] \u003c!-- omit from toc --\u003e\n\nSet the file build path. (default: `./node_modules/kysely-codegen/dist/db.d.ts`)\n\n#### --partitions \u003c!-- omit from toc --\u003e\n\nInclude partitions of PostgreSQL tables in the generated code.\n\n#### --print \u003c!-- omit from toc --\u003e\n\nPrint the generated output to the terminal instead of a file.\n\n#### --runtime-enums \u003c!-- omit from toc --\u003e\n\nThe PostgreSQL `--runtime-enums` option generates runtime enums instead of string unions. You can optionally specify which naming convention to use for runtime enum keys. (values: [`pascal-case`, `screaming-snake-case`], default: `screaming-snake-case`)\n\n**Examples:**\n\n`--runtime-enums=false`\n\n```ts\nexport type Status = 'CONFIRMED' | 'UNCONFIRMED';\n```\n\n`--runtime-enums` or `--runtime-enums=screaming-snake-case`\n\n```ts\nexport enum Status {\n  CONFIRMED = 'CONFIRMED',\n  UNCONFIRMED = 'UNCONFIRMED',\n}\n```\n\n`--runtime-enums=pascal-case`\n\n```ts\nexport enum Status {\n  Confirmed = 'CONFIRMED',\n  Unconfirmed = 'UNCONFIRMED',\n}\n```\n\n#### --singularize \u003c!-- omit from toc --\u003e\n\nSingularize generated type aliases, e.g. as `BlogPost` instead of `BlogPosts`. The codegen uses the [pluralize](https://www.npmjs.com/package/pluralize) package for singularization.\n\nYou can specify custom singularization rules in the [configuration file](#configuration-file).\n\n#### --type-only-imports \u003c!-- omit from toc --\u003e\n\nGenerate code using the TypeScript 3.8+ `import type` syntax. (default: `true`)\n\n#### --url [value] \u003c!-- omit from toc --\u003e\n\nSet the database connection string URL. This may point to an environment variable. (default: `env(DATABASE_URL)`)\n\n#### --verify \u003c!-- omit from toc --\u003e\n\nVerify that the generated types are up-to-date. (default: `false`)\n\n## Configuration file\n\nAll codegen options can also be configured in a `.kysely-codegenrc.json` (or `.js`, `.ts`, `.yaml` etc.) file or the `kysely-codegen` property in `package.json`. See [Cosmiconfig](https://github.com/cosmiconfig/cosmiconfig) for all available configuration file formats.\n\nThe default configuration:\n\n```json\n{\n  \"camelCase\": false,\n  \"dateParser\": \"timestamp\",\n  \"defaultSchemas\": [], // [\"public\"] for PostgreSQL.\n  \"dialect\": null,\n  \"domains\": true,\n  \"envFile\": null,\n  \"excludePattern\": null,\n  \"includePattern\": null,\n  \"logLevel\": \"warn\",\n  \"numericParser\": \"string\",\n  \"outFile\": \"./node_modules/kysely-codegen/dist/db.d.ts\",\n  \"overrides\": {},\n  \"partitions\": false,\n  \"print\": false,\n  \"runtimeEnums\": false,\n  \"singularize\": false,\n  \"typeOnlyImports\": true,\n  \"url\": \"env(DATABASE_URL)\",\n  \"verify\": false\n}\n```\n\nThe configuration object adds support for more advanced options:\n\n```json\n{\n  \"camelCase\": true,\n  \"overrides\": {\n    \"columns\": {\n      \"users.settings\": \"{ theme: 'dark' }\"\n    }\n  },\n  \"singularize\": {\n    \"/^(.*?)s?$/\": \"$1_model\",\n    \"/(bacch)(?:us|i)$/i\": \"$1us\"\n  }\n}\n```\n\nThe generated output:\n\n```ts\nexport interface UserModel {\n  settings: { theme: 'dark' };\n}\n\n// ...\n\nexport interface DB {\n  bacchi: Bacchus;\n  users: UserModel;\n}\n```\n\n## Issue funding\n\nWe use [Polar.sh](https://polar.sh/RobinBlomberg) to upvote and promote specific features that you would like to see implemented. Check the backlog and help out:\n\n\u003ca href=\"https://polar.sh/RobinBlomberg\"\u003e\u003cimg src=\"https://polar.sh/embed/fund-our-backlog.svg?org=RobinBlomberg\" /\u003e\u003c/a\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRobinBlomberg%2Fkysely-codegen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FRobinBlomberg%2Fkysely-codegen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRobinBlomberg%2Fkysely-codegen/lists"}