### Install Kysely with drivers Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Install Kysely along with the appropriate driver for your database. ```sh # PostgreSQL npm install kysely pg # MySQL npm install kysely mysql2 # SQLite npm install kysely better-sqlite3 # MSSQL npm install kysely tedious tarn @tediousjs/connection-string@1.0.0 # LibSQL npm install @libsql/kysely-libsql ``` -------------------------------- ### Install kysely-codegen Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Install kysely-codegen as a development dependency using npm. ```sh npm install --save-dev kysely-codegen ``` -------------------------------- ### Install and Basic Code Generation Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Install kysely-codegen and its dependencies. Generate types by running the command, which reads the DATABASE_URL from .env by default. You can specify a custom output file or print to the terminal. ```bash # Install kysely-codegen and required dependencies npm install --save-dev kysely-codegen npm install kysely pg # For PostgreSQL # Create .env file with database connection echo 'DATABASE_URL=postgres://username:password@localhost:5432/mydb' > .env # Generate types (reads DATABASE_URL from .env by default) kysely-codegen # Specify custom output file kysely-codegen --out-file ./src/db/types.d.ts # Print generated types to terminal instead of file kysely-codegen --print # Use a specific dialect explicitly kysely-codegen --dialect postgres --url postgres://user:pass@localhost/db # Connect to different databases kysely-codegen --dialect mysql --url mysql://user:pass@localhost/db kysely-codegen --dialect sqlite --url ./database.sqlite kysely-codegen --dialect mssql --url "Server=localhost;Database=mydb;User Id=sa;Password=pass" kysely-codegen --dialect libsql --url libsql://token@host:port/database ``` -------------------------------- ### Advanced Kysely Codegen Configuration Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md An example of an advanced configuration object for Kysely Codegen, demonstrating settings for camelCase, customImports, overrides for specific columns, singularize patterns, and type mappings. ```json { "camelCase": true, "customImports": { "InstantRange": "./custom-types", "MyCustomType": "@my-org/custom-types", "AliasedType": "./types#OriginalType" }, "overrides": { "columns": { "events.date_range": "ColumnType", "posts.author_type": "AliasedType", "users.settings": "{ theme: 'dark' }" } }, "singularize": { "/^(.*?)s?$/": "$1_model", "/(bacch)(?:us|i)$/i": "$1us" }, "typeMapping": { "date": "Temporal.PlainDate", "interval": "Temporal.Duration", "timestamptz": "Temporal.Instant" } } ``` -------------------------------- ### Combine Custom Imports with Overrides Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Integrate custom type imports with type overrides and mappings. This example maps PostgreSQL temporal types to the Temporal API, requiring the Temporal polyfill to be imported. ```bash kysely-codegen \ --custom-imports='{"Temporal":"@js-temporal/polyfill"}' \ --type-mapping='{"timestamptz":"Temporal.Instant","date":"Temporal.PlainDate"}' ``` -------------------------------- ### Kysely Codegen TypeScript Configuration Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Configure kysely-codegen using a TypeScript file (e.g., .kysely-codegenrc.ts) with the defineConfig helper. This example demonstrates setting up custom imports, type mappings, and overrides. ```typescript // .kysely-codegenrc.ts import { defineConfig } from 'kysely-codegen'; export default defineConfig({ camelCase: true, dialect: 'postgres', url: 'env(DATABASE_URL)', outFile: './src/db/types.d.ts', defaultSchemas: ['public'], runtimeEnums: 'pascal-case', singularize: true, customImports: { InstantRange: './custom-types', Temporal: '@js-temporal/polyfill', }, typeMapping: { timestamptz: 'Temporal.Instant', date: 'Temporal.PlainDate', tstzrange: 'InstantRange', }, overrides: { columns: { 'users.settings': '{ theme: "dark" | "light"; notifications: boolean }', 'posts.metadata': 'PostMetadata', }, }, }); ``` -------------------------------- ### Kysely Codegen JSON Configuration Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Configure kysely-codegen using a JSON file (e.g., .kysely-codegenrc.json). This example sets various options including dialect, output file, schema patterns, and type parsing. ```json // .kysely-codegenrc.json { "camelCase": true, "dialect": "postgres", "url": "env(DATABASE_URL)", "outFile": "./src/db/types.d.ts", "defaultSchemas": ["public"], "includePattern": "public.*", "excludePattern": "public._*", "singularize": true, "runtimeEnums": "pascal-case", "dateParser": "timestamp", "numericParser": "string", "typeOnlyImports": true, "logLevel": "warn" } ``` -------------------------------- ### Map Range Types to Custom Types Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Map database range types to custom TypeScript types. This example maps 'tstzrange' and 'daterange' to 'InstantRange' and 'DateRange' respectively, which must be defined in the custom imports. ```bash kysely-codegen \ --type-mapping='{"tstzrange":"InstantRange","daterange":"DateRange"}' \ --custom-imports='{"InstantRange":"./types","DateRange":"./types"}' ``` -------------------------------- ### Generated Kysely Type Definitions Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Example of generated TypeScript type definitions for Kysely, including generated columns and timestamps. ```ts import { ColumnType } from 'kysely'; export type Generated = T extends ColumnType ? ColumnType : ColumnType; export type Timestamp = ColumnType; export interface Company { id: Generated; name: string; } export interface User { company_id: number | null; created_at: Generated; email: string; id: Generated; is_active: boolean; name: string; updated_at: Timestamp; } export interface DB { company: Company; user: User; } ``` -------------------------------- ### Generated TypeScript Types with Custom Imports Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Example of TypeScript code generated by Kysely Codegen, showcasing the use of `import type` syntax for custom types and interfaces defined based on the configuration. ```ts import type { InstantRange } from './custom-types'; import type { MyCustomType } from '@my-org/custom-types'; import type { OriginalType as AliasedType } from './types'; import type { Temporal } from '@js-temporal/polyfill'; export interface EventModel { createdAt: Temporal.Instant; dateRange: ColumnType; eventDate: Temporal.PlainDate; } export interface UserModel { settings: { theme: 'dark' }; } // ... export interface DB { bacchi: Bacchus; events: EventModel; users: UserModel; } ``` -------------------------------- ### Define Typed JSON Columns with JSONColumnType Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Use `JSONColumnType` to define JSON columns with distinct input and output types. This example shows how to define a typed JSON column in an interface and how to override it in the configuration file. ```typescript import type { JSONColumnType, ColumnType } from 'kysely'; // Generated types might include typed JSON columns interface Posts { id: Generated; title: string; // Typed JSON column - different read/write types metadata: JSONColumnType<{ views: number; tags: string[]; author: { id: number; name: string }; }>; } // Override in config for custom JSON shapes // .kysely-codegenrc.json: // { // "overrides": { // "columns": { // "posts.metadata": "JSONColumnType" // } // }, // "customImports": { // "PostMetadata": "./types#PostMetadata" // } // } // types.ts export interface PostMetadata { views: number; tags: string[]; author: { id: number; name: string }; } // Usage const post = await db .selectFrom('posts') .select(['id', 'title', 'metadata']) .executeTakeFirstOrThrow(); // metadata is typed as { views: number; tags: string[]; author: {...} } console.log(post.metadata.views); console.log(post.metadata.tags[0]); ``` -------------------------------- ### Configure Database Connection URL Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Set up your database connection string in an .env file for different database types. ```sh # PostgreSQL DATABASE_URL=postgres://username:password@yourdomain.com/database # MySQL DATABASE_URL=mysql://username:password@yourdomain.com/database # SQLite DATABASE_URL=C:/Program Files/sqlite3/db # MSSQL DATABASE_URL=Server=mssql;Database=database;User Id=user;Password=password # LibSQL DATABASE_URL=libsql://token@host:port/database ``` -------------------------------- ### Programmatic API: Run with Default Options Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Execute the code generation process using the cli.run() method with default options. This will read configuration from environment variables and config files. ```typescript // Run with default options (reads from .env and config file) const output = await cli.run(); ``` -------------------------------- ### Specify Configuration File Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use the --config-file option to specify the path to a custom configuration file for kysely-codegen. ```sh kysely-codegen --config-file ./kysely-codegen.config.js ``` -------------------------------- ### Initialize Kysely with Generated Types Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Import the generated DB type and use it to strongly type your Kysely instance. ```ts import { Kysely, PostgresDialect } from 'kysely'; import { DB } from 'kysely-codegen'; import { Pool } from 'pg'; const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, }), }), }); const rows = await db.selectFrom('users').selectAll().execute(); // ^ { created_at: Date; email: string; id: number; ... }[] ``` -------------------------------- ### Programmatic API: Cli Class Initialization Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Initialize the Cli class from 'kysely-codegen' to programmatically control code generation. This allows integration into build scripts or custom tooling. ```typescript import { Cli } from 'kysely-codegen'; // Create CLI instance const cli = new Cli(); ``` -------------------------------- ### Programmatic API: Run with Programmatic Config Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Execute code generation using a programmatic configuration object passed to cli.run(). This bypasses any existing configuration files. ```typescript // Run with programmatic config (bypasses config file) const output = await cli.run({ config: { dialect: 'postgres', url: 'postgres://user:pass@localhost:5432/mydb', outFile: './src/db/types.d.ts', camelCase: true, runtimeEnums: 'pascal-case', } }); ``` -------------------------------- ### Specifying Multiple Default Schemas Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md You can set multiple default schemas for your database connection by repeating the --default-schema flag. ```bash kysely-codegen --default-schema=public --default-schema=hidden ``` -------------------------------- ### Verify Types Are Up-to-Date Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Use the --verify flag to check if generated types match the current database schema without modifying files. This is ideal for CI pipelines to ensure type consistency. ```bash kysely-codegen --verify ``` -------------------------------- ### Specify Output File for Type Definitions Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use the --out-file flag to specify a custom path for the generated .d.ts file. ```sh kysely-codegen --out-file ./src/db/db.d.ts ``` -------------------------------- ### Programmatic API: Run with Custom Arguments Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Run the code generation with custom command-line arguments passed via the 'argv' option to cli.run(). This overrides default behavior and configuration files. ```typescript // Run with custom argv const output = await cli.run({ argv: ['--dialect', 'postgres', '--url', 'postgres://localhost/mydb', '--print'] }); ``` -------------------------------- ### Basic Kysely Integration with Generated Types Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Integrate generated 'DB' types into your Kysely instance for fully typed database queries. Ensure the 'DB' type is imported from the correct output path. ```typescript import { Kysely, PostgresDialect } from 'kysely'; import { Pool } from 'pg'; import type { DB } from 'kysely-codegen'; // or your custom output path // Create typed Kysely instance const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, }), }), }); // Queries are now fully typed const users = await db .selectFrom('users') .select(['id', 'email', 'created_at']) .where('status', '=', 'ACTIVE') .execute(); // Type: { id: number; email: string; created_at: Date }[] // Column names and values are validated at compile time const user = await db .selectFrom('users') .selectAll() .where('id', '=', 123) .executeTakeFirst(); // Type: Selectable | undefined ``` -------------------------------- ### Generate Type Definitions Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Run the kysely-codegen command to generate .d.ts files from your database. This command can be added to your package.json scripts. ```sh kysely-codegen ``` -------------------------------- ### Load and Define Kysely Codegen Configuration Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Load configuration from default locations or a specific file using loadConfig. Validate configuration using the provided Zod schema. ```typescript import { loadConfig, defineConfig, configSchema } from 'kysely-codegen'; // Load config from default locations (.kysely-codegenrc.json, etc.) const result = loadConfig(); if (result) { console.log('Config loaded from:', result.filepath); console.log('Config:', result.config); } // Load from a specific file const customResult = loadConfig({ configFile: './config/codegen.json' }); // Validate config with Zod schema const parsed = configSchema.safeParse(result?.config); if (parsed.success) { console.log('Valid config:', parsed.data); } else { console.error('Invalid config:', parsed.error.issues); } // Define typed configuration (for .ts config files) export default defineConfig({ dialect: 'postgres', url: 'env(DATABASE_URL)', outFile: './src/db/types.d.ts', camelCase: true, runtimeEnums: 'pascal-case', }); ``` -------------------------------- ### Basic Custom Type Import Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Import custom types from local files using the --custom-imports flag. Specify the type name and its relative path. This allows using your own defined types in overrides. ```bash kysely-codegen --custom-imports='{"InstantRange":"./custom-types"}' ``` -------------------------------- ### Verify Types with Error Logging Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt When using --verify, setting --log-level to 'error' will cause the command to exit with an error code if type mismatches are found, providing diff output. ```bash kysely-codegen --verify --log-level=error ``` -------------------------------- ### Using Insertable and Updateable Types Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Utilize Kysely's Insertable and Updateable types for function parameters when working with generated types. ```ts import { Insertable, Updateable } from 'kysely'; import { DB } from 'kysely-codegen'; import { db } from './db'; async function insertUser(user: Insertable) { return await db .insertInto('users') .values(user) .returningAll() .executeTakeFirstOrThrow(); // ^ Selectable } async function updateUser(id: number, user: Updateable) { return await db .updateTable('users') .set(user) .where('id', '=', id) .returning(['email', 'id']) .executeTakeFirstOrThrow(); // ^ { email: string; id: number; } } ``` -------------------------------- ### Including Specific Tables with Glob Patterns Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use --include-pattern with glob syntax to specify which tables should be included in code generation. Supports advanced patterns via micromatch. ```bash kysely-codegen --include-pattern="public.*" ``` -------------------------------- ### Importing Named Exports with Aliasing Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use the `#` syntax to import specific named exports and alias them. This is useful for resolving type conflicts or for cleaner code. ```bash kysely-codegen --custom-imports='{"MyType":"./types#OriginalType","DateRange":"@org/utils#CustomDateRange"}' ``` -------------------------------- ### Parse Connection Strings with Kysely Codegen Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Use ConnectionStringParser to parse database connection strings and infer dialects. It handles environment variable references and supports explicit dialect overrides. ```typescript import { ConnectionStringParser, Logger } from 'kysely-codegen'; const parser = new ConnectionStringParser(); const logger = new Logger('info'); // Parse a direct connection string - dialect is inferred const pg = parser.parse({ connectionString: 'postgres://user:pass@localhost:5432/mydb', logger, }); console.log(pg); // { connectionString: 'postgres://user:pass@localhost:5432/mydb', dialect: 'postgres' } // Parse MySQL connection string const mysql = parser.parse({ connectionString: 'mysql://user:pass@localhost:3306/mydb', }); console.log(mysql.dialect); // 'mysql' // Parse environment variable reference process.env.DATABASE_URL = 'postgres://localhost/mydb'; const fromEnv = parser.parse({ connectionString: 'env(DATABASE_URL)', envFile: '.env', logger, }); console.log(fromEnv.connectionString); // 'postgres://localhost/mydb' // Parse with explicit dialect override const sqlite = parser.parse({ connectionString: './database.db', dialect: 'sqlite', }); console.log(sqlite); // { connectionString: './database.db', dialect: 'sqlite' } // Parse MSSQL connection string const mssql = parser.parse({ connectionString: 'Server=localhost;Database=mydb;User Id=sa;Password=pass', }); console.log(mssql.dialect); // 'mssql' ``` -------------------------------- ### Map PostgreSQL Temporal Types Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Globally map PostgreSQL temporal types to their corresponding TypeScript types from the Temporal API. This requires the Temporal polyfill to be imported via --custom-imports. ```bash kysely-codegen \ --type-mapping='{"timestamptz":"Temporal.Instant","date":"Temporal.PlainDate","interval":"Temporal.Duration"}' \ --custom-imports='{"Temporal":"@js-temporal/polyfill"}' ``` -------------------------------- ### Enable Camel Case for Column Names Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use the --camel-case CLI argument to apply the Kysely CamelCasePlugin for generated table column names. ```ts export interface User { companyId: number | null; createdAt: Generated; email: string; id: Generated; isActive: boolean; name: string; updatedAt: Timestamp; } ``` -------------------------------- ### Implement a Custom Serializer for Type Generation Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Create a custom `Serializer` class to control the output format of generated TypeScript types. Override the `serializeFile` method to customize how AST nodes are transformed into code. ```typescript import { Cli, Serializer, DatabaseMetadata, GeneratorDialect, transform } from 'kysely-codegen'; class CustomSerializer extends Serializer { serializeFile( metadata: DatabaseMetadata, dialect: GeneratorDialect, options?: { camelCase?: boolean; defaultSchemas?: string[] } ): string { // Get AST nodes from transformer const nodes = transform({ metadata, dialect, camelCase: options?.camelCase, defaultSchemas: options?.defaultSchemas, }); // Custom serialization logic let output = '// Custom generated types\n\n'; for (const node of nodes) { if (node.type === 'ExportStatement') { // Add custom formatting or annotations output += `/** @generated */\n`; output += this.serializeNode(node); output += '\n\n'; } } return output; } private serializeNode(node: any): string { // Implement custom node serialization return JSON.stringify(node, null, 2); } } const cli = new Cli(); await cli.run({ config: { dialect: 'postgres', url: 'env(DATABASE_URL)', serializer: new CustomSerializer(), }, }); ``` -------------------------------- ### Type Parsers for PostgreSQL Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Configure how PostgreSQL date and numeric types are parsed in generated types. Options include using string, number, or union types for numeric parsing, and string or default Date objects for date parsing. ```bash # Date parsing options kysely-codegen --date-parser=timestamp # Default: Date objects kysely-codegen --date-parser=string # Use string type # Numeric parsing options kysely-codegen --numeric-parser=string # Default: string type kysely-codegen --numeric-parser=number # Use number type kysely-codegen --numeric-parser=number-or-string # Union type ``` -------------------------------- ### Programmatic API: Generate with Parsed Options Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Generate code using the cli.generate() method with an options object previously parsed by cli.parseOptions(). ```typescript // Generate with parsed options const output = await cli.generate(options); ``` -------------------------------- ### Table Filtering with Include/Exclude Patterns Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Filter which tables are included in the generated types using glob patterns. This is useful for excluding internal tables, partitions, or focusing on specific schemas. Patterns can include specific tables or exclude entire schemas. ```bash # Include only tables from the public schema kysely-codegen --include-pattern="public.*" # Include specific tables using extended glob syntax kysely-codegen --include-pattern="public.+(user|post|comment)" # Exclude all tables starting with underscore (internal tables) kysely-codegen --exclude-pattern="*._*" # Exclude an entire schema kysely-codegen --exclude-pattern="audit.*" # Combine patterns - include public but exclude migrations kysely-codegen --include-pattern="public.*" --exclude-pattern="public.migrations" ``` -------------------------------- ### Generate TypeScript from Pre-fetched Database Metadata Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Use `serializeFromMetadata` to generate TypeScript types from manually created or modified `DatabaseMetadata`. This is useful when you need to work with metadata before generation. ```typescript import { serializeFromMetadata, getDialect } from 'kysely-codegen'; import { DatabaseMetadata } from 'kysely-codegen'; // Create metadata manually or modify introspected metadata const metadata = new DatabaseMetadata({ enums: new Map([ ['public.status', ['PENDING', 'APPROVED', 'REJECTED']], ]), tables: [ { name: 'users', schema: 'public', columns: [ { name: 'id', dataType: 'int4', isNullable: false, isAutoIncrementing: true, hasDefaultValue: true }, { name: 'email', dataType: 'varchar', isNullable: false }, { name: 'status', dataType: 'status', dataTypeSchema: 'public', isNullable: true }, { name: 'created_at', dataType: 'timestamptz', isNullable: false, hasDefaultValue: true }, ], }, ], }); const dialect = getDialect('postgres'); const output = serializeFromMetadata({ metadata, dialect, camelCase: true, runtimeEnums: true, singularize: true, }); console.log(output); // Generated TypeScript with User interface and Status enum ``` -------------------------------- ### Programmatic API: Parse Options Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Use the cli.parseOptions() method to parse command-line arguments into an options object without generating code. This is useful for validation or pre-processing. ```typescript // Parse options without generating (for validation) const options = cli.parseOptions(['--dialect', 'postgres', '--print']); console.log(options); // { dialect: 'postgres', print: true } ``` -------------------------------- ### Specify Type Mappings with Custom Imports Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use --type-mapping to map database types to custom TypeScript types and --custom-imports to specify where these custom types are located. This is useful for integrating modern JavaScript types like Temporal API. ```sh kysely-codegen --type-mapping='{"timestamptz":"Temporal.Instant","tstzrange":"InstantRange"}' --custom-imports='{"Temporal":"@js-temporal/polyfill","InstantRange":"./custom-types"}' ``` -------------------------------- ### Including Specific Tables within a Schema Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md This pattern allows you to include only certain tables within a specific schema, using regular expressions within the glob pattern. ```bash kysely-codegen --include-pattern="public.+(user|post)" ``` -------------------------------- ### JSON Configuration for Type Mappings Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Define type mappings in a JSON object to automatically apply custom TypeScript types to database columns of specific types. This configuration can be used in a .kysely-codegenrc.json file. ```json { "typeMapping": { "date": "Temporal.PlainDate", "daterange": "DateRange", "interval": "Temporal.Duration", "time": "Temporal.PlainTime", "timestamp": "Temporal.Instant", "timestamptz": "Temporal.Instant", "tsrange": "InstantRange", "tstzrange": "InstantRange" } } ``` -------------------------------- ### Generate TypeScript Types from Kysely Connection Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Use the `generate` function to create TypeScript types directly from an active Kysely database connection. Configure generation options like output file, patterns, and type mappings. ```typescript import { Kysely, PostgresDialect } from 'kysely'; import { Pool } from 'pg'; import { generate, getDialect } from 'kysely-codegen'; import { Logger } from 'kysely-codegen'; // Create Kysely connection const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL }), }), }); // Get the dialect adapter for code generation const dialect = getDialect('postgres', { dateParser: 'timestamp', numericParser: 'string', domains: true, }); // Generate types const output = await generate({ db, dialect, camelCase: true, outFile: './src/db/types.d.ts', defaultSchemas: ['public'], includePattern: 'public.*', excludePattern: 'public._*', runtimeEnums: 'pascal-case', singularize: true, typeOnlyImports: true, logger: new Logger('info'), customImports: { Temporal: '@js-temporal/polyfill', }, typeMapping: { timestamptz: 'Temporal.Instant', }, overrides: { columns: { 'users.settings': '{ theme: string }', }, }, }); // Clean up connection await db.destroy(); console.log(output); ``` -------------------------------- ### Applying Column Overrides with Aliased Types Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md After importing custom types, you can use them in column overrides. Ensure the type path matches your import. ```bash kysely-codegen --overrides='{"columns":{"events.date_range":"ColumnType"}}' ``` -------------------------------- ### Specify Custom Type Imports Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use the --custom-imports argument to provide custom type imports for type overrides, useful for external or local custom types. ```sh kysely-codegen --custom-imports='{"InstantRange":"./custom-types","MyCustomType":"@my-org/custom-types"}' ``` -------------------------------- ### Default Kysely Codegen Configuration Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md The default configuration for Kysely Codegen, typically found in a .kysely-codegenrc.json file or package.json. It specifies various settings like camelCase, customImports, and output file. ```json { "camelCase": false, "customImports": {}, "dateParser": "timestamp", "defaultSchemas": [], "dialect": null, "domains": true, "envFile": null, "excludePattern": null, "includePattern": null, "logLevel": "warn", "numericParser": "string", "outFile": "./node_modules/kysely-codegen/dist/db.d.ts", "overrides": {}, "partitions": false, "print": false, "runtimeEnums": false, "singularize": false, "skipAutogeneratedFileComment": false, "typeMapping": {}, "typeOnlyImports": true, "url": "env(DATABASE_URL)", "verify": false } ``` -------------------------------- ### Modify Introspected Metadata Before Generation Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt The `postprocess` option in `cli.run` allows you to modify introspected database metadata using an active Kysely connection before code generation. This is useful for adding custom types or adjusting schema details. ```typescript import { Cli } from 'kysely-codegen'; import { sql } from 'kysely'; const cli = new Cli(); await cli.run({ config: { dialect: 'postgres', url: 'env(DATABASE_URL)', outFile: './src/db/types.d.ts', // Postprocess to add custom enum types from lookup tables postprocess: async ({ db, metadata }) => { // Query enum values from a lookup table const statusRows = await db .selectFrom('status_types') .select('code') .execute(); const statusValues = statusRows.map(r => r.code); // Add as an enum to metadata metadata.enums.set('public.status', statusValues); // Modify column to use the new enum type const usersTable = metadata.tables.find(t => t.name === 'users'); const statusColumn = usersTable?.columns.find(c => c.name === 'status'); if (statusColumn) { statusColumn.dataType = 'status'; statusColumn.dataTypeSchema = 'public'; } return metadata; }, }, }); ``` -------------------------------- ### Applying Column Overrides Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use the --overrides flag to specify JSON-formatted type overrides for specific table columns. This allows for fine-grained control over generated types. ```bash kysely-codegen --overrides='{"columns":{"table_name.column_name":"{foo:\"bar\"}"}}' ``` -------------------------------- ### Generated Type Imports Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md This is the TypeScript code generated based on the custom import configuration, showing how aliased types are imported. ```typescript import type { OriginalType as MyType } from './types'; import type { CustomDateRange as DateRange } from '@org/utils'; ``` -------------------------------- ### Custom Singularization Rules JSON Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Define custom singularization rules using regex patterns within a JSON configuration file. This allows for handling non-standard plural forms in table names. ```json // .kysely-codegenrc.json { "singularize": { "/^(.*?)s?$/": "$1_model", "/(bacch)(?:us|i)$/i": "$1us", "/(alumn)(?:i|us)$/i": "$1us" } } ``` -------------------------------- ### PostgreSQL Runtime Enums Generation Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Generate TypeScript runtime enums instead of string union types for PostgreSQL enum columns. Supports different naming conventions for enum keys. ```bash # Default: screaming-snake-case enum keys kysely-codegen --runtime-enums # Use pascal-case for enum keys kysely-codegen --runtime-enums=pascal-case ``` ```typescript // Without --runtime-enums (default) export type Status = "CONFIRMED" | "UNCONFIRMED"; // With --runtime-enums (screaming-snake-case) export enum Status { CONFIRMED = 'CONFIRMED', UNCONFIRMED = 'UNCONFIRMED', } // With --runtime-enums=pascal-case export enum Status { Confirmed = 'CONFIRMED', Unconfirmed = 'UNCONFIRMED', } ``` -------------------------------- ### Named Custom Type Import with Alias Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Import a specific named type from an external package and alias it using the '#' syntax in --custom-imports. This is useful for disambiguating types or using specific exports. ```bash kysely-codegen --custom-imports='{"MyDate":"@org/utils#CustomDate"}' ``` -------------------------------- ### Kysely Utility Types for Typed Functions Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Utilize Kysely's Insertable, Selectable, and Updateable types with generated interfaces for typed function parameters. Generated fields are optional for Insertable types. ```typescript import { Insertable, Selectable, Updateable } from 'kysely'; import type { DB, Users } from 'kysely-codegen'; import { db } from './db'; // Selectable - represents a row returned from SELECT type User = Selectable; // Insertable - represents data for INSERT (Generated fields are optional) type NewUser = Insertable; // Updateable - represents data for UPDATE (all fields optional) type UserUpdate = Updateable; // Typed insert function async function createUser(user: NewUser): Promise { return await db .insertInto('users') .values(user) .returningAll() .executeTakeFirstOrThrow(); } // Usage - id and created_at are optional (Generated) const newUser = await createUser({ email: 'user@example.com', name: 'John Doe', // id: auto-generated // created_at: has default value }); // Typed update function async function updateUser(id: number, data: UserUpdate): Promise { return await db .updateTable('users') .set(data) .where('id', '=', id) .returningAll() .executeTakeFirst(); } // Usage - all fields optional for partial updates const updated = await updateUser(1, { name: 'Jane Doe', // only update name, keep other fields unchanged }); // Select specific columns with type inference async function getUserEmail(id: number): Promise<{ email: string } | undefined> { return await db .selectFrom('users') .select('email') .where('id', '=', id) .executeTakeFirst(); } ``` -------------------------------- ### Singularize Table Names Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Generate singular type names instead of plural table names for better readability and consistency. This option transforms plural table names like 'users' to singular 'User'. ```bash # Enable singularization kysely-codegen --singularize ``` ```typescript // Without --singularize export interface Users { ... } export interface BlogPosts { ... } // With --singularize export interface User { ... } export interface BlogPost { ... } ``` -------------------------------- ### Column Type Overrides Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Override generated types for specific columns using JSON format on the command line. This allows for custom type definitions for columns that require special handling. ```bash # Example: Override 'id' column in 'users' table to be string # kysely-codegen --column-overrides='{"users": {"id": "string"}}' # Example: Override 'created_at' to be Date # kysely-codegen --column-overrides='{"posts": {"created_at": "Date"}}' ``` -------------------------------- ### Override Multiple Column Types Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Provide multiple column overrides within the --overrides flag to define custom types for several columns simultaneously. Ensure correct JSON formatting. ```bash kysely-codegen --overrides='{"columns":{"users.settings":"UserSettings","posts.tags":"string[]"}}' ``` -------------------------------- ### Excluding Tables with Glob Patterns Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Use --exclude-pattern to prevent specific tables or groups of tables from being included in the generated code. ```bash kysely-codegen --exclude-pattern="documents.*" ``` -------------------------------- ### Generating Runtime Enums with Pascal Case Keys Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md Specify --runtime-enums=pascal-case to generate TypeScript enums where the keys follow PascalCase naming convention. ```typescript export enum Status { Confirmed = 'CONFIRMED', Unconfirmed = 'UNCONFIRMED', } ``` -------------------------------- ### Generating Runtime Enums (Default) Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md With --runtime-enums enabled (or default), PostgreSQL enums are generated as TypeScript enums. The default naming convention for keys is screaming snake case. ```typescript export enum Status { CONFIRMED = 'CONFIRMED', UNCONFIRMED = 'UNCONFIRMED', } ``` -------------------------------- ### CamelCase Transformation for Column Names Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Transform snake_case database column names to camelCase in generated types to match the Kysely CamelCasePlugin. This ensures consistency between database schema and TypeScript code. ```bash # Enable camelCase transformation kysely-codegen --camel-case ``` ```typescript // Without --camel-case export interface User { user_id: Generated; first_name: string; created_at: Generated; } // With --camel-case export interface User { userId: Generated; firstName: string; createdAt: Generated; } ``` -------------------------------- ### Generating String Union Enums Source: https://github.com/robinblomberg/kysely-codegen/blob/master/README.md When --runtime-enums is set to false, PostgreSQL enums are generated as string union types in TypeScript. ```typescript export type Status = 'CONFIRMED' | 'UNCONFIRMED'; ``` -------------------------------- ### Override Single Column Type Source: https://context7.com/robinblomberg/kysely-codegen/llms.txt Use the --overrides flag to specify a custom TypeScript type for a single database column. This is useful for columns with complex or non-standard data structures. ```bash kysely-codegen --overrides='{"columns":{"users.metadata":"{theme: string; preferences: Record}"}}' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.