### Install Kysely-ctl Globally with Bun Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl globally using Bun. This makes the 'kysely' command available system-wide. ```bash bun add -g kysely-ctl ``` -------------------------------- ### Install Kysely-ctl Globally with Deno Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl globally using Deno. This makes the 'kysely' command available system-wide. ```bash deno install -g -f npm:kysely-ctl@latest ``` -------------------------------- ### Install Kysely-ctl Globally with npm Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl globally using npm. This makes the 'kysely' command available system-wide. ```bash npm i -g kysely-ctl ``` -------------------------------- ### Install Kysely-ctl as a Project Dependency with Bun Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl as a development dependency using Bun. It will be available in your project's package.json. ```bash bun add -D kysely-ctl ``` -------------------------------- ### Install Kysely-ctl as a Project Dependency with Deno Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl as a development dependency using Deno. It will be available in your project's package.json. ```bash deno add -D npm:kysely-ctl ``` -------------------------------- ### Print Kysely Version Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Use the `--version` flag or its shorthand `-v` to display the installed Kysely version. This is useful for verifying the installation and checking compatibility. ```bash kysely --version ``` ```bash kysely -v ``` -------------------------------- ### Install Kysely-ctl Globally with pnpm Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl globally using pnpm. This makes the 'kysely' command available system-wide. ```bash pnpm add -g kysely-ctl ``` -------------------------------- ### Example seed file structure Source: https://context7.com/kysely-org/kysely-ctl/llms.txt A seed file contains a `seed` function that is executed to populate the database. It typically uses `db.insertInto` to add initial data. ```typescript // seeds/1716743937856_initial_data.ts import type { Kysely } from 'kysely' export async function seed(db: Kysely): Promise { await db.insertInto('users').values([ { email: 'alice@example.com' }, { email: 'bob@example.com' }, ]).execute() } ``` -------------------------------- ### Install Kysely-ctl as a Project Dependency with npm Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl as a development dependency using npm. It will be available in your project's package.json. ```bash npm i -D kysely-ctl ``` -------------------------------- ### Example migration file structure Source: https://context7.com/kysely-org/kysely-ctl/llms.txt A standard migration file includes `up` and `down` functions to apply and revert schema changes, respectively. The `up` function defines schema creation or modification, while `down` handles the reversal. ```typescript // migrations/1716743937856_create_users_table.ts import type { Kysely } from 'kysely' export async function up(db: Kysely): Promise { await db.schema .createTable('users') .addColumn('id', 'serial', (col) => col.primaryKey()) .addColumn('email', 'varchar(255)', (col) => col.notNull().unique()) .addColumn('created_at', 'timestamp', (col) => col.defaultTo('now()')) .execute() } export async function down(db: Kysely): Promise { await db.schema.dropTable('users').execute() } ``` -------------------------------- ### Define Kysely Configuration with Built-in Dialect Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Configure Kysely CLI using `defineConfig`. This example shows how to specify a built-in dialect like 'better-sqlite3' and its configuration, along with migration and seed settings. Full TypeScript autocompletion is available for dialect configurations. ```typescript // .config/kysely.config.ts import { defineConfig } from 'kysely-ctl' // Using a built-in dialect name string (autocompletion for dialectConfig) export default defineConfig({ dialect: 'better-sqlite3', dialectConfig: { database: ':memory:', }, migrations: { migrationFolder: 'migrations', // default: "migrations" next to config allowJS: false, // default: false getMigrationPrefix: () => `${Date.now()}_`, // default prefix function }, seeds: { seedFolder: 'seeds', allowJS: false, }, plugins: [], destroyOnExit: true, // default: true }) ``` -------------------------------- ### Install Kysely-ctl as a Project Dependency with pnpm Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl as a development dependency using pnpm. It will be available in your project's package.json. ```bash pnpm add -D kysely-ctl ``` -------------------------------- ### Define Kysely Configuration with Kysely Dialect Instance Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Configure Kysely CLI by providing an instance of a Kysely dialect, such as `MysqlDialect`. This allows for more complex connection pooling setups using libraries like `mysql2`. ```typescript // Using a Kysely dialect instance import { MysqlDialect } from 'kysely' import { createPool } from 'mysql2' import { defineConfig } from 'kysely-ctl' export default defineConfig({ dialect: new MysqlDialect({ pool: createPool({ uri: process.env.DATABASE_URL }), }), migrations: { migrationFolder: 'db/migrations', }, }) ``` -------------------------------- ### Install Kysely-ctl as a Project Dependency with yarn Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Installs kysely-ctl as a development dependency using yarn. It will be available in your project's package.json. ```bash yarn add -D kysely-ctl ``` -------------------------------- ### Custom Migration Prefixes with Knex Timestamp Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Configure custom migration file prefixes by providing a function to getMigrationPrefix. This example uses getKnexTimestampPrefix to adopt Knex.js's timestamp format. ```typescript import { defineConfig, getKnexTimestampPrefix } from "kysely-ctl"; export default defineConfig({ // ... migrations: { // ... getMigrationPrefix: getKnexTimestampPrefix, // ... }, // ... }); ``` -------------------------------- ### Initialize Kysely Config File Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Use `kysely init` to create a template configuration file. Specify the desired file extension (e.g., `mjs` for JavaScript ESM) using the `--extension` flag. The command skips creation if a config file already exists. ```bash kysely init kysely init --extension mjs ``` -------------------------------- ### Kysely-ctl Migrate Command Usage Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md The migrate module mirrors Knex.js CLI commands. Use `kysely migrate:` or `kysely migrate `. Note that `rollback` without `--all` is not supported. ```bash knex migrate: ``` ```bash kysely migrate: ``` ```bash kysely migrate ``` -------------------------------- ### Run SQL Queries with Kysely-ctl Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Execute SQL queries directly from the command line using the sql module. Supports single queries or interactive mode. ```bash kysely sql "select 1" ``` ```bash kysely sql -f json ✔ sqlite ❯ select 1; { "rows": [ { "1": 1 } ] } ❯ sqlite ❯ exit ``` -------------------------------- ### Run Migrations with Environment Overrides Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Execute Kysely migrations using environment-specific configurations. Use the `--environment` or `-e` flag followed by the environment name (e.g., `test`) to apply the corresponding overrides defined in the config file. ```bash # Run migrations using the "test" environment overrides kysely migrate latest --environment test # or kysely migrate latest -e test ``` -------------------------------- ### Initialize and run seeds with FileSeedProvider Source: https://context7.com/kysely-org/kysely-ctl/llms.txt The `FileSeedProvider` discovers and loads seed files from a specified folder, supporting TypeScript and optionally JavaScript. Seeds can be filtered by name. ```typescript import { Kysely } from 'kysely' import { FileSeedProvider, Seeder } from 'kysely-ctl' import path from 'node:path' const db = new Kysely({ dialect }) const seeder = new Seeder({ db, provider: new FileSeedProvider({ seedFolder: path.resolve('./seeds'), allowJS: false, }), }) // Run all seeds const { error, results } = await seeder.run() // Run only specific seeds by name (without extension) const { error: err2, results: res2 } = await seeder.run(['initial_data', 'test_users']) results.forEach((result) => { console.log(`[${result.status}] ${result.seedName}`) // [Success] initial_data // [Success] test_users }) if (error) throw error ``` -------------------------------- ### Run all pending migrations with Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Applies all pending migrations in order to bring the database schema to the latest version. Options include running without transactions or targeting a specific environment. ```bash # Run all pending migrations kysely migrate latest # Run without wrapping each migration in a transaction kysely migrate latest --no-transaction # Run against a specific environment kysely migrate latest -e production # Example output: # ℹ Starting migration to latest # ✔ Migration "1716743937856_create_users_table" applied successfully (up) # ✔ Migration "1716746051776_add_email_column" applied successfully (up) ``` -------------------------------- ### Define Kysely Configuration with Environment-Specific Overrides Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Utilize `$env` to apply environment-specific configurations for dialect settings and migration folders. The `DUMMY_DIALECT_CONFIG` placeholder ensures that dialect configuration is overridden for each environment. ```typescript // .config/kysely.config.ts import database from 'better-sqlite3' import { DUMMY_DIALECT_CONFIG, defineConfig } from 'kysely-ctl' export default defineConfig({ dialect: 'better-sqlite3', dialectConfig: DUMMY_DIALECT_CONFIG, // will throw unless overridden by $env $env: { development: { dialectConfig: () => ({ database: database('./dev.db') }), migrations: { migrationFolder: 'migrations/dev' }, }, test: { dialectConfig: () => ({ database: database(':memory:') }), }, production: { dialectConfig: () => ({ database: database(process.env.DB_PATH!) }), }, }, }) ``` -------------------------------- ### Create a new migration file using Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Generates a new timestamped migration file from a template. Supports various file extensions like `.ts`, `.js`, etc. The command `kysely migrate make ` creates the file. ```bash kysely migrate make create_users # Creates: migrations/20240315120000_create_users.ts ``` ```bash # Create a TypeScript migration (default) kysely migrate make create_users_table # Create a JS migration kysely migrate make add_email_column --extension js # Output: ✔ Created migration file at migrations/1716743937856_create_users_table.ts ``` -------------------------------- ### List available seed files Source: https://context7.com/kysely-org/kysely-ctl/llms.txt The `kysely seed list` command displays all seed files found in the configured directory. ```bash kysely seed list ``` -------------------------------- ### Run Legacy Knex-style Migration Commands Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Kysely-ctl supports legacy Knex-style command aliases for migrations and seeding. These commands are useful for managing database schema changes and initial data population. ```bash kysely migrate:latest ``` ```bash kysely migrate:make create_table ``` ```bash kysely seed:run ``` ```bash kysely seed:make initial_data ``` -------------------------------- ### Initialize and run migrations with TSFileMigrationProvider Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Use `TSFileMigrationProvider` for TypeScript-aware migration loading without extra loader flags. It works in ESM/CJS and on Windows. ```typescript import { Kysely, Migrator } from 'kysely' import { TSFileMigrationProvider } from 'kysely-ctl' import path from 'node:path' const db = new Kysely({ dialect }) const migrator = new Migrator({ db, provider: new TSFileMigrationProvider({ migrationFolder: path.resolve('./migrations'), allowJS: false, // set true to also load .js/.mjs/.cjs files }), }) const { error, results } = await migrator.migrateToLatest() results?.forEach((result) => { if (result.status === 'Success') { console.log(`Migration "${result.migrationName}" applied`) } else if (result.status === 'Error') { console.error(`Failed to apply "${result.migrationName}"`) } }) if (error) throw error ``` -------------------------------- ### Create a new seed file using Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Generates a new seed file template in the configured `seedFolder`. The command `kysely seed make ` creates the file. ```bash kysely seed make initial_data # Output: ✔ Created seed file at seeds/1716743937856_initial_data.ts ``` -------------------------------- ### Run the next single migration with Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Applies the next un-executed migration. Can also migrate up to a specific named migration by providing its name as an argument. ```bash # Apply the very next pending migration kysely migrate up # Migrate up to (and including) a specific migration by name kysely migrate up 1716746051776_add_email_column # Example output: # ℹ Starting migration up # ✔ Migration "1716743937856_create_users_table" applied successfully (up) ``` -------------------------------- ### Use Extended Kysely Configuration Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Specify which configuration file to use when running Kysely CLI commands. Use the `--config` flag followed by the path to the desired configuration file, such as the test-specific config. ```bash # Use the test-specific config kysely migrate latest --config .config/kysely.test.config.ts ``` -------------------------------- ### Configure Knex-style timestamp prefix for migrations Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Use `getKnexTimestampPrefix` to generate migration file names in the `YYYYMMDDHHmmss_` UTC format, matching Knex.js convention. This is configured within the `kysely.config.ts` file. ```typescript // .config/kysely.config.ts import { defineConfig, getKnexTimestampPrefix } from 'kysely-ctl' export default defineConfig({ dialect: 'pg', dialectConfig: { connectionString: process.env.DATABASE_URL }, migrations: { getMigrationPrefix: getKnexTimestampPrefix, // New migration files will be named like: 20240315120000_create_users.ts }, }) ``` -------------------------------- ### List migration status with Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Lists all discovered migrations and their execution status. Can be used in CI/CD pipelines to fail if pending migrations exist using the `--fail-on-pending` flag. ```bash # List all migrations kysely migrate list # Fail (exit code 1) if there are any pending migrations kysely migrate list --fail-on-pending # Example output: # ℹ Found 2 migrations: # [✓] 1716743937856_create_users_table # [ ] 1716746051776_add_email_column ``` -------------------------------- ### Kysely-ctl Seed Command Usage Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md The seed module mirrors Knex.js CLI commands. Use `kysely seed:` or `kysely seed `. Additionally, `kysely seed list` is available. ```bash knex seed: ``` ```bash kysely seed: ``` ```bash kysely seed ``` ```bash kysely seed list ``` -------------------------------- ### Execute seed files with Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Runs all seed files in the configured `seedFolder`, or a specific named seed. The command `kysely seed run` executes all seeds. ```bash # Run all seed files kysely seed run ``` -------------------------------- ### Define Base Kysely Configuration Source: https://context7.com/kysely-org/kysely-ctl/llms.txt This is the base configuration file for Kysely CLI, defining the dialect and dialect configuration. It serves as a foundation for extended configurations. ```typescript // .config/kysely.config.ts (base config) import database from 'better-sqlite3' import { defineConfig } from 'kysely-ctl' export default defineConfig({ dialect: 'better-sqlite3', dialectConfig: () => ({ database: database('./main.db') }), }) ``` -------------------------------- ### Run a specific seed file by name Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Use the `--specific` flag to run a single seed file by its name, excluding the file extension. ```bash kysely seed run --specific initial_data ``` -------------------------------- ### Configure Kysely-ctl with kysely.config.ts Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Define the configuration for kysely-ctl by exporting a defineConfig object. This includes settings for dialect, migrations, and seeds. Ensure the config file is in the project root or .config folder. ```typescript import { defineConfig } from "kysely-ctl"; export default defineConfig({ destroyOnExit, dialect, dialectConfig, migrations: { allowJS, getMigrationPrefix, migrationFolder, migrator, provider, }, plugins, seeds: { allowJS, getSeedPrefix, provider, seeder, seedFolder, } }); ``` -------------------------------- ### Execute raw SQL queries Source: https://context7.com/kysely-org/kysely-ctl/llms.txt The `kysely sql` command executes raw SQL queries. It supports single-query mode with CSV or JSON output, and an interactive REPL. ```bash kysely sql "select id, email from users limit 5" ``` ```bash kysely sql "select id, email from users limit 2" --format json ``` ```bash kysely sql -f json ``` ```bash select count(*) as total from users; ``` ```bash exit ``` -------------------------------- ### Rollback all migrations with Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Reverts all completed migrations, resetting the database to a clean state. The `--all` flag is mandatory for this operation. ```bash kysely migrate rollback --all # Example output: # ℹ Starting migration rollback # ✔ Migration "1716746051776_add_email_column" reverted (down) # ✔ Migration "1716743937856_create_users_table" reverted (down) ``` -------------------------------- ### Reuse Existing Kysely Instance in Configuration Source: https://github.com/kysely-org/kysely-ctl/blob/main/README.md Instead of providing dialect and dialectConfig, you can pass an existing Kysely instance to defineConfig. This is useful when the Kysely instance is managed elsewhere in your project. ```typescript import { defineConfig } from "kysely-ctl"; import { kysely } from 'path/to/kysely/instance'; export default defineConfig({ destroyOnExit, // ... kysely, // ... }); ``` -------------------------------- ### Define Extended Kysely Configuration Source: https://context7.com/kysely-org/kysely-ctl/llms.txt This configuration file extends a base configuration using the `extends` field. It allows composing settings from multiple files, specifying a relative path to the base config without an extension. ```typescript // .config/kysely.test.config.ts (extends base) import { defineConfig } from 'kysely-ctl' export default defineConfig({ extends: './kysely.config', // relative path, no extension needed dialectConfig: () => ({ database: ':memory:' }), migrations: { migrationFolder: 'migrations/test', }, }) ``` -------------------------------- ### Define Kysely Configuration Reusing Existing Kysely Instance Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Configure Kysely CLI to use an existing Kysely instance that has been defined elsewhere in your project. This is useful for centralizing database connection logic. ```typescript // Reusing an existing Kysely instance defined elsewhere import { defineConfig } from 'kysely-ctl' import { db } from './src/db' export default defineConfig({ kysely: db, }) ``` -------------------------------- ### Common CLI flags for kysely commands Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Kysely CLI commands share common flags for help, configuration, environment overrides, and debugging. ```bash kysely migrate --help ``` ```bash kysely seed run --help ``` ```bash kysely migrate latest --config ./custom/kysely.config.ts ``` ```bash kysely migrate latest -c ./custom/kysely.config.ts ``` ```bash kysely migrate latest --cwd /path/to/project ``` ```bash kysely migrate latest --environment production ``` ```bash kysely migrate latest -e production ``` ```bash kysely migrate latest --debug ``` ```bash kysely migrate latest --no-outdated-check ``` -------------------------------- ### Programmatic Seeder with Custom Seed Provider Source: https://context7.com/kysely-org/kysely-ctl/llms.txt The `Seeder` class can be used programmatically with custom `SeedProvider` implementations for advanced seeding logic. ```typescript import type { Kysely } from 'kysely' import { FileSeedProvider, Seeder, type SeedProvider } from 'kysely-ctl' // Custom in-memory seed provider class InMemorySeedProvider implements SeedProvider { async getSeeds() { return { seed_roles: { async seed(db: Kysely) { await db.insertInto('roles').values([ { name: 'admin' }, { name: 'user' }, ]).execute() }, }, } } } const seeder = new Seeder({ db, provider: new InMemorySeedProvider(), }) // List available seeds const seeds = await seeder.getSeeds() console.log(seeds.map((s) => s.name)) // ['seed_roles'] // Run all seeds const { error, results } = await seeder.run() // results[0] => { seedName: 'seed_roles', status: 'Success' } ``` -------------------------------- ### Undo the last migration with Kysely CLI Source: https://context7.com/kysely-org/kysely-ctl/llms.txt Reverts the most recently executed migration. Can also revert to a state just before a specific named migration by providing its name. ```bash # Undo the last executed migration kysely migrate down # Migrate down to (just before) a specific migration kysely migrate down 1716743937856_create_users_table # Example output: # ℹ Starting migration down # ✔ Migration "1716746051776_add_email_column" reverted successfully (down) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.