### Dockerfile Example for Custom PostgreSQL Setup Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/configuration.md Example Dockerfile demonstrating how to set up a custom PostgreSQL environment. Includes installing extensions and running initialization scripts. ```dockerfile FROM postgres:18-alpine # Add custom initialization scripts COPY init.sql /docker-entrypoint-initdb.d/ # Add extensions or other setup RUN apt-get update && apt-get install -y postgresql-contrib ``` -------------------------------- ### Complete Vitest Configuration with Kysely Postgres Plugin Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/configuration.md This example shows a comprehensive Vitest configuration file using the Kysely Postgres plugin. It includes database connection details, Docker container setup, and migration/seeding configurations. Ensure you have the necessary imports and types defined. ```typescript // vitest.config.ts import path from "node:path"; import { kyselyPostgres } from "@kysely-vitest/postgres/plugin.js"; import { defineConfig } from "vitest/config"; import type { DB } from "./src/db.js"; import { seed } from "./src/tests/seed.js"; export default defineConfig({ plugins: [ kyselyPostgres({ // Connection configuration config: { // PostgreSQL connection settings host: "localhost", port: 5433, database: "myapp_test", user: "myuser", password: "mypassword", // Additional postgres.js options ssl: false, application_name: "myapp_tests", // Docker configuration dockerContainer: { image: "postgres", tag: "18-alpine", environment: { // Additional env vars beyond POSTGRES_* POSTGRES_INITDB_ARGS: "-c timezone=UTC", }, healthcheck: { test: ["CMD-SHELL", "pg_isready -U myuser"], interval: "5s", timeout: "5s", retries: 5, startPeriod: "10s", }, }, }, // Migration and seeding migrationFolder: path.resolve(__dirname, "src/db/migrations"), seed, }), ], test: { include: ["src/**/*.spec.ts"], testTimeout: 10000, globals: true, }, }); ``` -------------------------------- ### Install Postgres Adapter Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/readme.md Install the `@kysely-vitest/postgres` adapter and its peer dependency `kysely-postgres-js`. Ensure you have Vitest installed as a dev dependency. ```shell npm install kysely-postgres-js && npm install -D @kysely-vitest/postgres # or yarn add kysely-postgres-js && yarn add -D @kysely-vitest/postgres # or pnpm add kysely-postgres-js && pnpm add -D @kysely-vitest/postgres ``` -------------------------------- ### Install Custom Adapter Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/README.md Install the core Kysely Vitest package for custom adapter integration. ```bash npm install -D @kysely-vitest/core ``` -------------------------------- ### Create Custom Plugin Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/configuration.md Demonstrates how to create a custom database plugin using `createPlugin`. This example shows the structure for providing a name, config key, configuration provider, and dialect factory. ```typescript import { createPlugin } from "@kysely-vitest/core/plugin.js"; export const myPlugin = createPlugin({ name: "mydb", configKey: "myDbConfig" as const, configProvider: async (config) => ({ config: { host: "localhost", ...config }, dockerContainer: false, }), dialectFactory: (config) => new MyDialect(config), }); ``` -------------------------------- ### Example ConfigProvider Implementation Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/types.md An example implementation of `ConfigProvider` that sets default host and port, and defines a Docker container for a database. ```typescript const configProvider: ConfigProvider = async (config) => { return { config: { host: "localhost", port: 5432, ...config, }, dockerContainer: { image: "mydb", tag: "latest", ports: [{ hostPort: 5432, containerPort: 5432 }], }, }; }; ``` -------------------------------- ### Install Dependencies for @kysely-vitest/postgres Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/packages/postgres/readme.md Install the necessary packages for @kysely-vitest/postgres using npm, yarn, or pnpm. ```shell npm install kysely kysely-postgres-js && npm install -D vitest @kysely-vitest/postgres ``` ```shell yarn add kysely kysely-postgres-js && yarn add -D vitest @kysely-vitest/postgres ``` ```shell pnpm add kysely kysely-postgres-js && pnpm add -D vitest @kysely-vitest/postgres ``` -------------------------------- ### Example docker-compose.yml for Unmanaged Container Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/packages/postgres/readme.md A sample `docker-compose.yml` file to set up an unmanaged PostgreSQL database for testing. ```yaml version: "3.8" services: postgres: image: "postgres:15" ports: - "5432:5432" environment: POSTGRES_DB: "testdb" POSTGRES_USER: "test" POSTGRES_PASSWORD: "test" volumes: - "postgres_data:/var/lib/postgresql/data" volumes: postgres_data: ``` -------------------------------- ### Install Kysely and Vitest Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/readme.md Install Kysely and Vitest as peer dependencies. Ensure you have Vitest installed as a dev dependency. ```shell npm install kysely && npm install -D vitest # or yarn add kysely && yarn add -D vitest # or pnpm add kysely && pnpm add -D vitest ``` -------------------------------- ### Kysely Vitest Setup Flow Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/INDEX.md Follow this sequence for setting up and configuring Kysely Vitest. ```markdown 1. Read README.md (overview) ↓ 2. Check quick-reference.md (examples) ↓ 3. Configure using configuration.md ↓ 4. Reference api-reference/* as needed ↓ 5. Handle errors with errors.md ``` -------------------------------- ### Install PostgreSQL Adapter Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/README.md Install the PostgreSQL adapter for Kysely Vitest, including the necessary Kysely and PostgreSQL packages. ```bash npm install -D @kysely-vitest/postgres kysely-postgres-js postgres ``` -------------------------------- ### PostgreSQL ConfigProvider Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md An example ConfigProvider for PostgreSQL that handles default values, port mapping, and Docker container configuration. It returns a configuration object and optionally a Docker container specification. ```typescript const configProvider: ConfigProvider = async ({ dockerContainer, ...config }) => { const port = config.port ?? DEFAULT_POSTGRES_PORT; const database = config.database ?? DEFAULT_POSTGRES_DB; const user = config.user ?? DEFAULT_POSTGRES_USER; if (dockerContainer) { return { config: { ...config, host: "localhost", port, database, user, }, dockerContainer: { image: "postgres", tag: "latest", ports: [{ hostPort: port, containerPort: 5432 }], environment: { POSTGRES_DB: database, POSTGRES_USER: user, }, }, }; } return { config, dockerContainer: false }; }; ``` -------------------------------- ### PostgreSQL DialectFactory Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md An example implementation of a DialectFactory for PostgreSQL, demonstrating how to create a Kysely dialect instance using the postgres adapter. ```typescript export const postgresDialectFactory: DialectFactory = (config) => { return new PostgresJSDialect({ postgres: postgres({ ...config }), }); }; ``` -------------------------------- ### Usage Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-test.md An example demonstrating how to use createTestFunction to set up a database-aware test function and use it within Vitest. ```APIDOC ## Usage Example ```typescript import { createTestFunction } from "@kysely-vitest/core/test.js"; import type { DialectFactory } from "@kysely-vitest/core/types.js"; import type { DB } from "../db.js"; export const MY_CONFIG_KEY = "myDialectConfig" as const; export const myDialectFactory: DialectFactory = (config) => { // Create and return your Dialect instance }; export const dbTest = createTestFunction({ configKey: MY_CONFIG_KEY, dialectFactory: myDialectFactory, }); // Usage in test file import { describe, expect } from "vitest"; describe("database tests", () => { dbTest("inserts a user", async ({ db }) => { const user = await db .insertInto("users") .values({ name: "Alice" }) .returningAll() .executeTakeFirstOrThrow(); expect(user.name).toBe("Alice"); // All changes are automatically rolled back after test completes }); dbTest("each test has isolated data", async ({ db }) => { const users = await db.selectFrom("users").selectAll().execute(); // Users inserted in previous test are not visible here expect(users).toEqual([]); }); }); ``` ``` -------------------------------- ### Migration File Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Defines the 'up' and 'down' functions for a database migration to create a 'users' table. ```typescript // src/db/migrations/001_create_users.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("username", "varchar", (col) => col.notNull().unique()) .execute(); } export async function down(db: Kysely): Promise { await db.schema.dropTable("users").execute(); } ``` -------------------------------- ### Start Docker Container Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-docker.md Starts a Docker container and waits for it to be ready. Use this to spin up necessary services like databases for your tests. It handles image building from Dockerfiles, port mapping, environment variables, and health checks. ```typescript async function startDockerContainer( container: DockerContainer, ): Promise ``` ```typescript type DockerContainer = DockerContainerBase & ( | { image: string; tag: string; dockerFile?: never } | { dockerFile: string; image?: string; tag?: never } ) ``` ```typescript import { startDockerContainer } from "@kysely-vitest/core/docker.js"; const containerName = await startDockerContainer({ image: "postgres", tag: "18-alpine", ports: [ { hostPort: 5432, containerPort: 5432 }, ], environment: { POSTGRES_DB: "testdb", POSTGRES_USER: "testuser", POSTGRES_PASSWORD: "test", }, healthcheck: { test: ["CMD-SHELL", "pg_isready -U testuser"], interval: "5s", timeout: "5s", retries: 5, }, }); console.log(`Container started: ${containerName}`); ``` -------------------------------- ### TypeScript: PostgreSQL Dialect Factory Implementation Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/errors.md Provides an example of a PostgreSQL dialect factory implementation using `postgres.js`. Ensure the `postgres` package is installed to avoid missing dependency errors. ```typescript // PostgreSQL adapter example export const postgresDialectFactory: DialectFactory = (config) => { return new PostgresJSDialect({ postgres: postgres({ // Requires postgres.js package debug: false, onnotice() {}, ...config, }), }); }; // Missing dependency error: // Error: Cannot find module 'postgres' // Fix: npm install postgres ``` -------------------------------- ### Example Plugin Error Log Formats Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/errors.md Illustrative examples of how plugin errors are formatted when logged. ```text [postgres] Error during migrations: ENOENT: no such file or directory ``` ```text [postgres] Error during setup: Connection refused ``` ```text [postgres] Error during migrations: syntax error in migration ``` -------------------------------- ### Manual Docker Compose Workflow Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md A sequence of commands to manually manage a Docker Compose setup for testing, including starting, testing, and stopping the database. ```bash docker-compose up -d npm test docker-compose down ``` -------------------------------- ### Example SeedFunction Implementation Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/types.md An example of how to implement the `SeedFunction` type to insert initial data into a 'users' table. ```typescript const seed: SeedFunction = async (db) => { await db .insertInto("users") .values([ { username: "alice" }, { username: "bob" }, ]) .execute(); }; ``` -------------------------------- ### Configuration Provider Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/README.md A configuration provider function that returns the final configuration and optionally a Docker container specification. ```typescript const configProvider = async (userConfig) => { return { config: { /* final config to inject */ }, dockerContainer: { /* Docker spec */ } | false }; }; ``` -------------------------------- ### Configure kyselyPostgres Plugin Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-types.md Example of how to configure the kyselyPostgres plugin in vitest.config.ts, passing the database configuration and the seed function. ```typescript import { defineConfig } from "vitest/config"; import { kyselyPostgres } from "@kysely-vitest/postgres/plugin.js"; import type { DB } from "./src/db.js"; import { seed } from "./src/tests/seed.js"; export default defineConfig({ plugins: [ kyselyPostgres({ config: { /* ... */ }, seed, }), ], test: { /* ... */ }, }); ``` -------------------------------- ### Configuration Resolution Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/configuration.md Illustrates how user-provided configuration is processed and merged with default values by the configProvider. This is particularly relevant when using the `dockerContainer` option, showing how defaults for host, port, database, user, and password are applied, and how port mappings and environment variables are set up. ```typescript // User config { port: 5434, dockerContainer: { image: "postgres", tag: "17-alpine" } } // After configProvider { host: "localhost", // ← added default port: 5434, // ← kept from user database: "testdb", // ← added default user: "testuser", // ← added default password: "test", // ← added default dockerContainer: { image: "postgres", tag: "17-alpine", ports: [{ hostPort: 5434, containerPort: 5432 }], // ← added environment: { POSTGRES_DB: "testdb", POSTGRES_USER: "testuser", POSTGRES_PASSWORD: "test", }, healthcheck: { ... } // ← added default } } ``` -------------------------------- ### Example Error Stack Trace Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/errors.md A sample stack trace for a database migration error, showing the error message and call stack. ```text [postgres] Error during migrations: syntax error in SQL statement Error: syntax error in SQL statement "CREATE TABL users..." at createDbConnection (dialect.ts:42:15) at migrateToLatest (migration.ts:156:8) at configureVitest (plugin.ts:57:18) at ... ``` -------------------------------- ### Core Plugin Creation Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/MANIFEST.txt Documentation for the `createPlugin()` function, used for creating Kysely-Vitest plugins. Includes details on its signature, parameters, related types, and usage examples. ```APIDOC ## createPlugin() ### Description Creates a Kysely-Vitest plugin. ### Signature `createPlugin()` ### Parameters - **K** (Type Parameter): Type for Kysely instance. - **C** (Type Parameter): Type for plugin configuration. ### Related Types - `PluginConfig` - `PluginParams` - `ConfigProvider` - `DockerContainer` - `HealthcheckConfig` ### Error Handling Details on error handling and recovery mechanisms. ### Usage Examples Complete usage examples demonstrating plugin creation. ``` -------------------------------- ### Basic Postgres Test Setup Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/postgres-test.md Set up the `pgTest` function with your database type. This function will be used to create isolated transactional test environments. ```typescript // src/tests/pgTest.ts import { createPostgresTestFunction } from "@kysely-vitest/postgres/test.js"; import type { DB } from "../db.js"; export const pgTest = createPostgresTestFunction(); ``` -------------------------------- ### IntegratekyselyPostgres Plugin in Vitest Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/configuration.md Shows how to use the `kyselyPostgres` plugin within `vitest.config.ts`. This example configures connection details, specifies a migration folder, and includes a seed function. ```typescript import path from "node:path"; import { defineConfig } from "vitest/config"; import { kyselyPostgres } from "@kysely-vitest/postgres/plugin.js"; export default defineConfig({ plugins: [ kyselyPostgres({ config: { host: "localhost", port: 5432, database: "testdb", user: "testuser", password: "test", }, migrationFolder: path.resolve(__dirname, "migrations"), seed: seedFunction, }), ], }); ``` -------------------------------- ### createPlugin(config) Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/README.md Creates a Vitest plugin factory for database setup. This function is part of the core framework. ```APIDOC ## createPlugin(config) ### Description Creates a Vitest plugin factory for database setup. ### Parameters - **config** (object) - Configuration for the plugin. ``` -------------------------------- ### SQL: Database Connection Error Examples Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/errors.md Illustrates common database connection errors due to incorrect port, password, or non-existent user. Verify database accessibility, credentials, and user permissions. ```typescript // Wrong port (5433 instead of 5432) config: { host: "localhost", port: 5433, // ← container listens on 5432, mapped to 5433 database: "testdb", } // Wrong password config: { password: "wrong", // ← actual password is "test" } // User doesn't exist config: { user: "nonexistent", // ← must be created first } ``` -------------------------------- ### Create Config Provider and Plugin for Custom Adapter Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md Implement the configuration provider and create the plugin for your custom database adapter. The config provider handles configuration and Docker container setup, while the plugin integrates it with Vitest. ```typescript // src/config.ts export const configProvider: ConfigProvider = async (config) => { return { config: { /* final config */ }, dockerContainer: { /* container spec */ } | false, }; }; // src/plugin.ts export const myPlugin = createPlugin({ name: "mydb", configKey: MY_CONFIG_KEY, configProvider, dialectFactory: myDialectFactory, }); ``` -------------------------------- ### Validate Configuration at Startup Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/errors.md Implement configuration validation at the start of your application to fail fast with clear error messages if required properties are missing. ```typescript // Fail fast with clear error message const configProvider = async (config: MyConfig) => { if (!config.password) { throw new Error("password is required"); } return { config, dockerContainer: false }; }; ``` -------------------------------- ### Docker Compose for Unmanaged PostgreSQL Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/readme.md Example `docker-compose.yml` to set up an unmanaged PostgreSQL database for testing. Ensure the database is running before executing tests. ```yaml # in docker-compose.yml services: postgres: image: postgres:18-alpine environment: POSTGRES_DB: testdb POSTGRES_USER: test POSTGRES_PASSWORD: test ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U test"] interval: 10s timeout: 5s retries: 5 ``` -------------------------------- ### Usage Example for createTestFunction Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-test.md Demonstrates how to set up and use createTestFunction in a Vitest test file, including defining configuration and performing database operations within isolated transactions. ```typescript import { createTestFunction } from "@kysely-vitest/core/test.js"; import type { DialectFactory } from "@kysely-vitest/core/types.js"; import type { DB } from "../db.js"; export const MY_CONFIG_KEY = "myDialectConfig" as const; export const myDialectFactory: DialectFactory = (config) => { // Create and return your Dialect instance }; export const dbTest = createTestFunction({ configKey: MY_CONFIG_KEY, dialectFactory: myDialectFactory, }); // Usage in test file import { describe, expect } from "vitest"; describe("database tests", () => { dbTest("inserts a user", async ({ db }) => { const user = await db .insertInto("users") .values({ name: "Alice" }) .returningAll() .executeTakeFirstOrThrow(); expect(user.name).toBe("Alice"); // All changes are automatically rolled back after test completes }); dbTest("each test has isolated data", async ({ db }) => { const users = await db.selectFrom("users").selectAll().execute(); // Users inserted in previous test are not visible here expect(users).toEqual([]); }); }); ``` -------------------------------- ### startDockerContainer(config) Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/README.md Starts a managed Docker container. This function is part of the core framework's Docker utilities. ```APIDOC ## startDockerContainer(config) ### Description Starts a managed Docker container. ### Parameters - **config** (object) - Configuration for the Docker container. ``` -------------------------------- ### Kysely Migration File Structure Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/configuration.md Example of the expected folder structure for Kysely migration files. Files are named with a numerical prefix and run in ascending order. ```plaintext migrations/ ├── 001_create_users.ts ├── 002_create_posts.ts ├── 003_add_indexes.ts ``` -------------------------------- ### Creating Custom Test Functions Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-test.md An example of how to create custom, database-specific test function wrappers using createTestFunction. ```APIDOC ## Creating Custom Test Functions For database-specific adapters, wrap `createTestFunction`: ```typescript // postgres adapter export function createPostgresTestFunction() { return createTestFunction({ configKey: POSTGRES_CONFIG_KEY, dialectFactory: postgresDialectFactory, }); } ``` ``` -------------------------------- ### startDockerContainer Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-docker.md Starts a Docker container based on the provided configuration and waits for it to become ready. It returns a unique container name (UUID) that can be used for subsequent cleanup operations. ```APIDOC ## startDockerContainer ### Description Starts a Docker container and waits for it to be ready. Returns the container name (UUID) for cleanup. ### Method Signature ```typescript async function startDockerContainer( container: DockerContainer, ): Promise ``` ### Parameters #### container (DockerContainer) - Required Configuration for the container to start. The `DockerContainer` type requires either an `image` and `tag` or a `dockerFile`. **DockerContainerBase Fields:** - **environment** (Record) - Optional - Environment variables. - **ports** (Array<{hostPort, containerPort}>) - Optional - Port mappings. - **healthcheck** (HealthcheckConfig) - Optional - Container health configuration. **HealthcheckConfig Fields:** - **test** (string[]) - Required - Command array for health test. - **interval** (string) - Optional - Time between checks (e.g., "5s"). - **timeout** (string) - Optional - Timeout per check (e.g., "5s"). - **retries** (number) - Optional - Consecutive failures before unhealthy. - **startPeriod** (string) - Optional - Grace period before checks start. ### Return Type - **string**: UUID container name used to identify the container. ### Behavior 1. Generates a unique container name using UUID. 2. If `dockerFile` is provided, builds a Docker image from the Dockerfile. 3. Constructs Docker run arguments from container configuration. 4. Starts container with `docker run`. 5. Waits for container to reach healthy or running status. 6. Returns the container name for later cleanup. ### Error Handling Throws an error if: - Docker build fails (when using Dockerfile). - Docker run command fails. - Container fails to reach healthy/running status (retries infinitely with 500ms delays). ### Usage Example ```typescript import { startDockerContainer } from "@kysely-vitest/core/docker.js"; const containerName = await startDockerContainer({ image: "postgres", tag: "18-alpine", ports: [ { hostPort: 5432, containerPort: 5432 }, ], environment: { POSTGRES_DB: "testdb", POSTGRES_USER: "testuser", POSTGRES_PASSWORD: "test", }, healthcheck: { test: ["CMD-SHELL", "pg_isready -U testuser"], interval: "5s", timeout: "5s", retries: 5, }, }); console.log(`Container started: ${containerName}`); ``` ``` -------------------------------- ### Database Seeding Function Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/packages/postgres/readme.md Example of a seeding function for the Kysely Vitest adapter. This function truncates the 'users' table and inserts initial data. ```typescript // in src/tests/seed.js import type { SeedFunction } from "@kysely-vitest/postgres/types.js"; import { sql } from "kysely"; import type { DB } from "../db.js"; export const seed: SeedFunction = async (db) => { await sql`TRUNCATE TABLE "users" RESTART IDENTITY CASCADE`.execute(db); await db .insertInto("users") .values([{ username: "alice" }, { username: "bob" }]) .execute(); }; ``` -------------------------------- ### Implement PostgreSQL Dialect Factory Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-types.md Example implementation of a DialectFactory for PostgreSQL using kysely-postgres-js. This factory is used to configure and create a Kysely Dialect instance for PostgreSQL. ```typescript import type { DialectFactory } from "@kysely-vitest/core/types.js"; import { PostgresJSDialect } from "kysely-postgres-js"; import postgres from "postgres"; export const POSTGRES_CONFIG_KEY = "postgresConfig" as const; declare module "vitest" { export interface ProvidedContext { postgresConfig: postgres.Options>; } } export const postgresDialectFactory: DialectFactory = (config) => { return new PostgresJSDialect({ postgres: postgres(config), }); }; ``` -------------------------------- ### Kysely Postgres Plugin with Managed Docker Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/postgres-plugin.md Use the plugin to automatically manage a Docker container for your PostgreSQL database. This example uses the latest `postgres` image. ```typescript import path from "node:path"; import { kyselyPostgres } from "@kysely-vitest/postgres/plugin.js"; import { defineConfig } from "vitest/config"; import type { DB } from "./src/db.js"; export default defineConfig({ plugins: [ kyselyPostgres({ config: { port: 5433, dockerContainer: true, // Uses postgres:latest }, migrationFolder: path.resolve(__dirname, "migrations"), }), ], test: { /* ... */ }, }); ``` -------------------------------- ### Implement Database Seeding Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-types.md Example of a SeedFunction to populate 'users' and 'posts' tables. It first truncates existing data and then inserts new records, demonstrating how to seed reference data or initial state. ```typescript import type { SeedFunction } from "@kysely-vitest/core/types.js"; import { sql } from "kysely"; import type { DB } from "../db.js"; export const seed: SeedFunction = async (db) => { // Clear existing data await sql`TRUNCATE TABLE "users" RESTART IDENTITY CASCADE`.execute(db); // Insert seed data await db .insertInto("users") .values([ { username: "alice", email: "alice@example.com" }, { username: "bob", email: "bob@example.com" }, ]) .execute(); // Insert related data await db .insertInto("posts") .values([ { title: "First Post", content: "Hello", authorId: 1 }, { title: "Second Post", content: "World", authorId: 2 }, ]) .execute(); }; ``` -------------------------------- ### Create Database Seed Function Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Example of a seed function to populate the database with initial data. It truncates existing tables and inserts new users and posts, returning inserted data. ```typescript // src/tests/seed.ts import type { SeedFunction } from "@kysely-vitest/postgres/types.js"; import type { DB } from "../db.js"; export const seed: SeedFunction = async (db) => { // Clear existing data await sql`TRUNCATE TABLE "posts" CASCADE`.execute(db); await sql`TRUNCATE TABLE "users" RESTART IDENTITY CASCADE`.execute(db); // Insert seed data const alice = await db .insertInto("users") .values({ username: "alice", email: "alice@example.com" }) .returningAll() .executeTakeFirstOrThrow(); const bob = await db .insertInto("users") .values({ username: "bob", email: "bob@example.com" }) .returningAll() .executeTakeFirstOrThrow(); // Insert related data await db .insertInto("posts") .values([ { title: "Post 1", content: "Hello", authorId: alice.id }, { title: "Post 2", content: "World", authorId: bob.id }, ]) .execute(); }; ``` -------------------------------- ### buildContainerArgs Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-docker.md Constructs Docker run command arguments as a single string. This function is useful for programmatically generating the arguments needed to start a Docker container with specific configurations. ```APIDOC ## buildContainerArgs ### Description Constructs Docker run command arguments as a single string. This function is useful for programmatically generating the arguments needed to start a Docker container with specific configurations. ### Parameters #### Path Parameters * **environment** (Record | undefined) - Optional - Environment variables to set * **ports** (Array<{hostPort, containerPort}> | undefined) - Optional - Port mappings * **healthcheck** (HealthcheckConfig | undefined) - Optional - Health configuration * **containerName** (string) - Required - Container name to assign * **imageRef** (string) - Required - Docker image reference (e.g., "postgres:18-alpine") ### Return Type * **string** - Space-separated Docker run arguments (without `docker run` prefix) ### Argument Format ``` -d --name [ports...] [env...] [healthcheck...] ``` Components: - `-d` - Run detached - `--name ` - Container name - `-p :` - Port mapping (one per port) - `-e KEY=VALUE` - Environment variable (one per variable) - `--health-cmd="..."` - Healthcheck command - `--health-interval=` - Health check interval - `--health-timeout=` - Health check timeout - `--health-retries=` - Retry count before unhealthy - `--health-start-period=` - Grace period - `` - Docker image reference ### Usage Example ```typescript import { buildContainerArgs } from "@kysely-vitest/core/docker.js"; const args = buildContainerArgs( { environment: { POSTGRES_USER: "test", POSTGRES_PASSWORD: "secret", }, ports: [ { hostPort: 5432, containerPort: 5432 }, ], healthcheck: { test: ["CMD-SHELL", "pg_isready -U test"], interval: "5s", retries: 5, }, }, "my-postgres-container", "postgres:18-alpine" ); // Result: "-d --name my-postgres-container -p 5432:5432 -e POSTGRES_USER=test -e POSTGRES_PASSWORD=secret --health-cmd=\"CMD-SHELL pg_isready -U test\" --health-interval=5s --health-retries=5 postgres:18-alpine" ``` ``` -------------------------------- ### Test Function Fixture Setup Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md Extends Vitest's test function with 'perWorker' and 'db' fixtures. 'perWorker' provides a Kysely instance for the worker, while 'db' provides a transaction-scoped Kysely instance for each test. ```typescript test.extend({ perWorker: [ async ({}, use) => { // 1. Inject config from context const config = inject(configKey); // 2. Create dialect from config const dialect = dialectFactory(config); // 3. Create worker-level connection const db = new Kysely({ dialect }); // 4. Provide to tests await use(db); // 5. Cleanup on worker shutdown await db.destroy(); }, { scope: "worker", auto: true }, ], async db({ perWorker }, use) { // 6. Start transaction for test const trx = await perWorker.startTransaction().execute(); try { // 7. Provide transaction to test await use(trx); } finally { // 8. Rollback after test await trx.rollback().execute(); } }, }) ``` -------------------------------- ### Initialize and Run Kysely Migrations Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md Set up the Kysely Migrator with a database instance and a migration provider. Then, migrate the database to the latest version. ```typescript new Migrator({ db, provider: new FileMigrationProvider({ fs, path, migrationFolder }), }) migrator.migrateToLatest() ``` -------------------------------- ### Minimal Project Structure Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Illustrates a basic file organization for a project using Kysely and Vitest. ```tree src/ ├── db.ts # Database types ├── db/ │ └── migrations/ │ ├── 001_create_users.ts │ └── 002_create_posts.ts ├── tests/ │ ├── pgTest.ts # Test function │ ├── seed.ts # Seed function │ └── users.spec.ts # Tests └── vitest.config.ts # Plugin config ``` -------------------------------- ### Kysely Generic Type DB Example Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/types.md Illustrates the usage of the generic Kysely type, where DB maps table names to their respective types. This example shows how to define table types and instantiate Kysely with a specific database schema. ```typescript type DB = { users: UserTable; posts: PostTable; }; type UserTable = { id: Generated; name: string; }; // Usage const db: Kysely = new Kysely({ dialect }); const users = await db.selectFrom("users").selectAll().execute(); ``` -------------------------------- ### Configure Docker Container (Custom Dockerfile) Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Uses a custom Dockerfile to build the PostgreSQL image for testing. Ensure the Dockerfile is correctly specified using `path.resolve`. ```typescript import path from "node:path"; dockerContainer: { dockerFile: path.resolve(__dirname, "Dockerfile"), } ``` -------------------------------- ### Configure Vitest Plugin Hook Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md Use this hook to access Vitest context and project methods within your test setup. ```typescript configureVitest(context) { // context.vitest: Logger, onClose // context.project: provide() method } ``` -------------------------------- ### Create and Configure Core Plugin Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/core-plugin.md Demonstrates how to create a custom dialect plugin and configure it within vitest.config.ts. Ensure necessary types and dialect implementations are imported. ```typescript import { createPlugin } from "@kysely-vitest/core/plugin.js"; import type { DialectFactory, SeedFunction } from "@kysely-vitest/core/types.js"; import { MyDialect } from "kysely/my-dialect"; import type { DB } from "./db.js"; export const MY_CONFIG_KEY = "myDialectConfig" as const; export const myDialectFactory: DialectFactory = (config) => { return new MyDialect(config); }; export const configProvider: ConfigProvider = async (config) => { return { config: { host: "localhost", port: 5432, ...config }, dockerContainer: { image: "mydb", tag: "latest", ports: [{ hostPort: 5432, containerPort: 5432 }], }, }; }; export const myPlugin = createPlugin({ name: "mydb", configKey: MY_CONFIG_KEY, configProvider, dialectFactory: myDialectFactory, }); // Usage in vitest.config.ts import { defineConfig } from "vitest/config"; import path from "node:path"; export default defineConfig({ plugins: [ myPlugin({ config: { /* your config */ }, migrationFolder: path.resolve(__dirname, "migrations"), seed: myOptionalSeedFunction, }), ], test: { /* test config */ }, }); ``` -------------------------------- ### Docker Container Management Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/MANIFEST.txt API reference for functions related to Docker container management, including starting, stopping, and building containers. ```APIDOC ## Docker Container Functions ### startDockerContainer() - **Description**: Starts a Docker container. - **Signature**: `startDockerContainer()` ### stopDockerContainer() - **Description**: Stops a Docker container. - **Signature**: `stopDockerContainer()` ### buildContainerArgs() - **Description**: Builds arguments for a Docker container. - **Signature**: `buildContainerArgs()` ### DockerContainer Type - **Description**: Structure defining a Docker container. ### Health Check Configuration - **Description**: Configuration options for health checks. ### Usage Examples Examples demonstrating Docker patterns. ``` -------------------------------- ### Configure PostgreSQL Plugin with Docker Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Configure the Kysely Vitest PostgreSQL plugin using a Docker container for the database. Ensure the 'vitest/config' is imported. ```typescript // vitest.config.ts import path from "node:path"; import { kyselyPostgres } from "@kysely-vitest/postgres/plugin.js"; import { defineConfig } from "vitest/config"; import type { DB } from "./src/db.js"; export default defineConfig({ plugins: [ kyselyPostgres({ config: { database: "testdb", user: "testuser", password: "test", port: 5433, dockerContainer: { image: "postgres", tag: "18-alpine", }, }, migrationFolder: path.resolve(__dirname, "src/db/migrations"), }), ], test: { /* ... */ }, }); ``` -------------------------------- ### Docker Command Construction (TypeScript) Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md Illustrates how the plugin programmatically constructs `docker run` commands, including arguments for detached mode, naming, port mapping, environment variables, and health checks. ```typescript // buildContainerArgs constructs: -d --name uuid -p host:container -e KEY=VALUE --health-cmd="..." image:tag const args = buildContainerArgs( { environment, ports, healthcheck }, containerName, imageRef ); await execAsync(`docker run ${args}`); ``` -------------------------------- ### Required Dependencies Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Lists the necessary npm packages for Kysely, its PostgreSQL dialect, and Vitest. ```json { "dependencies": { "kysely": "^0.28.0", "kysely-postgres-js": "^1.5.0" }, "devDependencies": { "vitest": "^4.0.0", "@kysely-vitest/postgres": "^0.4.0", "postgres": "^3.4.0" } } ``` -------------------------------- ### Verify Connection Configuration Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Ensure the database port and host are correctly configured to match the running database instance. This helps resolve 'Connection Refused' errors. ```typescript config: { port: 5432, // matches docker port mapping host: "localhost", } ``` -------------------------------- ### Kysely Postgres Plugin with Async Password Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/postgres-plugin.md Handle database passwords asynchronously, for example, by fetching them from environment variables or a secret manager. This enhances security. ```typescript kyselyPostgres({ config: { host: "localhost", user: "testuser", password: async () => { // Fetch password from environment or secret manager return process.env.DB_PASSWORD || "fallback"; }, dockerContainer: true, }, migrationFolder: path.resolve(__dirname, "migrations"), }) ``` -------------------------------- ### Verify Migrations with psql Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md Connect to a PostgreSQL database using `psql` and query the `kysely_migrations` table to verify migration status. ```bash # Connect to database and check migrations table psql -h localhost -p 5432 -U testuser -d testdb # In psql: SELECT * FROM kysely_migrations; ``` -------------------------------- ### Create Seed Function for Database Seeding Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/packages/core/readme.md Define a seed function to populate your database before tests. This example truncates the 'users' table and inserts initial data. ```typescript // in src/tests/seed.js import type { SeedFunction } from "@kysely-vitest/core/types.js"; import { sql } from "kysely"; import type { DB } from "../db.js"; export const seed: SeedFunction = async (db) => { await sql`TRUNCATE TABLE "users" RESTART IDENTITY CASCADE`.execute(db); await db .insertInto("users") .values([{ username: "alice" }, { username: "bob" }]) .execute(); }; ``` -------------------------------- ### HealthcheckConfig Type Definition Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/types.md Defines the configuration for a Docker container's health check. Includes the test command, intervals, timeouts, retries, and start period. ```typescript type HealthcheckConfig = { test: string[]; interval?: string; timeout?: string; retries?: number; startPeriod?: string; } ``` -------------------------------- ### Basic Kysely Postgres Plugin Configuration Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/api-reference/postgres-plugin.md Configure the plugin with direct database connection details. Ensure your database is running and accessible. ```typescript import path from "node:path"; import { kyselyPostgres } from "@kysely-vitest/postgres/plugin.js"; import { defineConfig } from "vitest/config"; import type { DB } from "./src/db.js"; export default defineConfig({ plugins: [ kyselyPostgres({ config: { host: "localhost", port: 5432, database: "testdb", user: "testuser", password: "test", }, migrationFolder: path.resolve(__dirname, "migrations"), }), ], test: { /* ... */ }, }); ``` -------------------------------- ### PostgreSQL Plugin Factory Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/MANIFEST.txt Documentation for the `kyselyPostgres` plugin factory, detailing its configuration options, Docker integration, and usage with test functions. ```APIDOC ## kyselyPostgres Plugin Factory ### Signature `kyselyPostgres` ### PluginConfig Type - **Description**: Type for PostgreSQL plugin configuration, including all fields. - **Fields**: Detailed table of configuration fields, types, requirements, defaults, and descriptions. ### Default Values Table of default configuration values. ### Docker Configuration Options for configuring Docker integration. ### Managed vs Unmanaged Containers Explanation of container management modes. ### Usage Examples Examples covering basic usage, Docker integration, Dockerfile usage, and async password handling. ### Integration Details on integration with `createPostgresTestFunction`. ``` -------------------------------- ### Custom Docker Health Check Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/configuration.md Configure a custom Docker health check for a PostgreSQL container. Specify test commands, intervals, timeouts, retries, and start periods. ```typescript dockerContainer: { image: "postgres", tag: "18-alpine", healthcheck: { test: ["CMD-SHELL", "pg_isready -U testuser"], interval: "10s", timeout: "10s", retries: 3, startPeriod: "20s", }, } ``` -------------------------------- ### Verify Test Isolation with Kysely Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Demonstrates how each test starts with seed data and that changes made in one test do not affect subsequent tests. This confirms proper test isolation. ```typescript pgTest("each test starts with seed data", async ({ db }) => { const users = await db.selectFrom("users").selectAll().execute(); // Seed has alice and bob expect(users.length).toBe(2); // Add new user in this test await db .insertInto("users") .values({ username: "charlie" }) .execute(); }); pgTest("changes from previous test are not visible", async ({ db }) => { const users = await db.selectFrom("users").selectAll().execute(); // Only seed data, charlie is not here expect(users.length).toBe(2); }); ``` -------------------------------- ### Running Tests with npm Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/quick-reference.md Common npm commands for executing Vitest tests, including watch mode, specific files, and coverage. ```bash # Run tests once npm test # Watch mode npm test -- --watch # Specific test file npm test -- users.spec.ts # Specific test npm test -- --reporter=verbose # With coverage npm test -- --coverage ``` -------------------------------- ### Use Absolute Paths for Folders and Files Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/errors.md Best practice for defining migration folders and Dockerfiles using `path.resolve` to ensure correct resolution regardless of the current working directory. ```typescript // ✓ Correct migrationFolder: path.resolve(__dirname, "migrations"), dockerFile: path.resolve(__dirname, "Dockerfile"), // ✗ Wrong migrationFolder: "./migrations", dockerFile: "Dockerfile", ``` -------------------------------- ### Injecting PostgreSQL Configuration in Vitest (TypeScript) Source: https://github.com/jonathanarnault/kysely-vitest/blob/main/_autodocs/architecture.md Demonstrates how to use Vitest's `inject()` function to retrieve the typed PostgreSQL configuration, ensuring type safety during test setup. ```typescript const config: PostgresConfig = inject("postgresConfig"); ```