### Setup command examples Source: https://kysera.dev/docs/cli/test Common usage patterns for the setup command. ```bash # Basic setup kysera test setup # Clean setup with seeding kysera test setup --clean --migrate --seed # CI environment kysera test setup -e ci --clean # Load fixtures kysera test setup --fixtures users posts ``` -------------------------------- ### Run the E-commerce Example Source: https://kysera.dev/docs/examples/e-commerce Commands to install dependencies and start the development server for the e-commerce example. ```bash cd examples/e-commerce pnpm install pnpm dev ``` -------------------------------- ### Initialization Modes Source: https://kysera.dev/docs/cli/init Examples of interactive and non-interactive project setup. ```bash kysera init my-app # Prompts for all options ``` ```bash # API with PostgreSQL kysera init my-app -d postgres -t api # GraphQL with MySQL kysera init my-app -d mysql -t graphql # With specific plugins kysera init my-app -p timestamps,audit,rls # Current directory kysera init . -d postgres ``` -------------------------------- ### Run the blog application example Source: https://kysera.dev/docs/examples/blog-app Commands to install dependencies, initialize the database, and execute the demonstration. ```bash # Install dependencies pnpm install # Set up PostgreSQL database createdb blog_example export DATABASE_URL="postgresql://localhost/blog_example" # Build the example pnpm build # Run the CLI demonstration pnpm start ``` -------------------------------- ### Run Example Applications Source: https://kysera.dev/docs/examples/overview Standard shell commands to clone, install, and initialize a Kysera example project. ```bash # Clone repository git clone https://github.com/kysera-dev/kysera.git cd kysera # Install dependencies pnpm install # Navigate to example cd examples/blog-app # Set up database createdb blog_example cp .env.example .env # Run migrations pnpm migrate # Start example pnpm dev ``` -------------------------------- ### Complete Migration Example Source: https://kysera.dev/docs/guides/migration-v08 Comparison of database setup code between v0.7.x and v0.8.0 versions. ```typescript import { createExecutor } from '@kysera/executor' import { createORM } from '@kysera/repository' import { rlsPlugin } from '@kysera/rls' import { softDeletePlugin } from '@kysera/soft-delete' import type { DatabaseDialect } from '@kysera/dialects' // ❌ Old type import type { RLSSchema } from '@kysera/rls' const dialect: DatabaseDialect = 'postgres' // ❌ Old type const rlsSchema: RLSSchema = { users: { tenant: { column: 'tenant_id' }, user: { column: 'created_by' } }, posts: { tenant: { column: 'tenant_id' } } } async function setupDatabase() { const executor = await createExecutor(db, [ softDeletePlugin(), rlsPlugin({ schema: rlsSchema, skipTables: ['migrations', 'system_logs'] // ❌ Old option }) ]) const orm = await createORM(executor, []) return { executor, orm } } ``` ```typescript import { createExecutor } from '@kysera/executor' import { createORM } from '@kysera/repository' import { rlsPlugin } from '@kysera/rls' import { softDeletePlugin } from '@kysera/soft-delete' import type { Dialect } from '@kysera/dialects' // ✅ New type import type { RLSSchema } from '@kysera/rls' const dialect: Dialect = 'postgres' // ✅ New type const rlsSchema: RLSSchema = { users: { tenant: { column: 'tenant_id' }, user: { column: 'created_by' } }, posts: { tenant: { column: 'tenant_id' } } } async function setupDatabase() { const executor = await createExecutor(db, [ softDeletePlugin(), rlsPlugin({ schema: rlsSchema, excludeTables: ['migrations', 'system_logs'] // ✅ New option }) ]) const orm = await createORM(executor, []) return { executor, orm } } ``` -------------------------------- ### Setup command options Source: https://kysera.dev/docs/cli/test Configuration flags for the setup command. ```bash -e, --environment Environment (test/ci/local, default: test) -d, --database Test database name --clean Drop existing test database --migrate Run migrations (default: true) --no-migrate Skip running migrations --seed Run seeders --fixtures Load specific fixtures --parallel Enable parallel test execution --isolation Isolation strategy (default: transaction) -v, --verbose Verbose output --json Output as JSON --config Path to configuration file ``` -------------------------------- ### Implement Repository and DAL Patterns Source: https://kysera.dev/docs/guides/best-practices Examples demonstrating the setup for Repository with full plugin support, DAL with executor interceptors, and pure functional DAL queries. ```typescript // Repository: Full plugin support (interceptors + extensions) import { createORM } from '@kysera/repository' import { softDeletePlugin } from '@kysera/soft-delete' import { auditPlugin } from '@kysera/audit' const orm = await createORM(db, [softDeletePlugin(), auditPlugin()]) const userRepo = orm.createRepository(createUserRepository) await userRepo.softDelete(1) // Plugin extension method works! // DAL with createExecutor: Query interceptor plugins only import { createExecutor } from '@kysera/executor' import { createQuery } from '@kysera/dal' const executor = await createExecutor(db, [softDeletePlugin()]) const getUsers = createQuery( ctx => ctx.db.selectFrom('users').selectAll().execute() // Soft-delete filter applied! ) await getUsers(executor) // DAL: Pure functional queries, no plugins import { sql } from 'kysely' const getAnalytics = createQuery((ctx, userId: number) => ctx.db .selectFrom('events') .select([sql`count(*)`.as('total')]) .where('user_id', '=', userId) .executeTakeFirst() ) ``` -------------------------------- ### Install @kysera/repository Source: https://kysera.dev/docs/api/repository Install the core package and optional validation libraries. ```bash npm install @kysera/repository # Optional: Install your preferred validation library npm install zod # Popular schema validation # or: npm install valibot # Lightweight alternative # or: npm install @sinclair/typebox # JSON Schema based # or: none - use native TypeScript validation ``` -------------------------------- ### Configure RLS Plugin Source: https://kysera.dev/docs/api/rls Examples of basic multi-tenant setup and advanced configuration with bypass rules. ```typescript import { rlsPlugin, defineRLSSchema, filter, allow } from '@kysera/rls' // Basic multi-tenant setup const plugin = rlsPlugin({ schema: defineRLSSchema({ users: { policies: [filter('read', ctx => ({ tenant_id: ctx.auth.tenantId }))] } }) }) // Full setup with bypass rules const plugin = rlsPlugin({ schema: rlsSchema, excludeTables: ['migrations', 'system_config'], bypassRoles: ['superadmin'], requireContext: true, auditDecisions: true, onViolation: violation => { logger.warn('RLS violation', violation) } }) ``` -------------------------------- ### Restore command examples Source: https://kysera.dev/docs/cli/audit Examples for previewing, confirming, and forcing an entity restoration. ```bash # Preview restore kysera audit restore 123 --dry-run # Restore with confirmation kysera audit restore 123 # Force restore without confirmation kysera audit restore 123 --force ``` -------------------------------- ### Repository Method Output Examples Source: https://kysera.dev/docs/cli/repository Example output formats for default method listing and signature views. ```text Repository Methods UserRepository: • findById • findByEmail • findActive • create • update • delete • softDelete OrderRepository: • findById • findByUser • findByStatus • create • updateStatus ... ``` ```text UserRepository: • findById(id: string): Promise • findByEmail(email: string): Promise • create(data: CreateUserInput): Promise ... ``` -------------------------------- ### Migration up examples Source: https://kysera.dev/docs/cli/migrate Common usage patterns for running migrations. ```bash # Run all pending kysera migrate up # Run next 2 migrations kysera migrate up --steps 2 # Run up to specific version kysera migrate up --to 20251003_add_posts # Preview changes kysera migrate up --dry-run # Run in specific schema (multi-tenant) kysera migrate up --schema tenant_acme ``` -------------------------------- ### Initialize Kysera Project Source: https://kysera.dev/docs/cli/init Basic command to start a new project. ```bash kysera init [project-name] ``` -------------------------------- ### Install Kysera Core Source: https://kysera.dev/docs/api/core/logger Install the core package to access logging utilities. ```bash npm install @kysera/core ``` -------------------------------- ### Health Monitor Usage Example Source: https://kysera.dev/docs/api/core/health Demonstrates starting a continuous health monitor with a callback for status changes. ```typescript import { HealthMonitor } from '@kysera/core' const monitor = new HealthMonitor(db, { interval: 30000, pool: metricsPool }) monitor.start(result => { if (result.status !== 'healthy') { alertOps('Database health degraded', result) } }) // Later monitor.stop() ``` -------------------------------- ### Kysera plugin list examples Source: https://kysera.dev/docs/cli/plugin Various usage examples for listing plugins with different filters and options. ```bash # List all plugins kysera plugin list # List installed plugins only kysera plugin list --installed # List available plugins from registry kysera plugin list --available # Filter by category kysera plugin list --category audit # Search plugins kysera plugin list --search "soft delete" # Show detailed information kysera plugin list --show-details # Show only enabled plugins kysera plugin list --enabled ``` -------------------------------- ### Install @kysera/infra Source: https://kysera.dev/docs/api/infra Install the package along with the required Kysely peer dependency. ```bash npm install @kysera/infra kysely ``` -------------------------------- ### Install Kysera Foundation Source: https://kysera.dev/docs/getting-started Install the core and executor packages to establish the foundation layer. ```bash # Install in order - executor first (foundation layer) npm install @kysera/core # Errors, pagination, types, logger (~8KB) npm install @kysera/executor # Unified Execution Layer - plugin foundation (~6KB) ``` -------------------------------- ### Create a migration example Source: https://kysera.dev/docs/api/migrations A practical example of defining a migration to create a users table. ```typescript import { createMigration } from '@kysera/migrations' import { sql } from 'kysely' const migrations = [ createMigration( '001_create_users', async db => { await db.schema .createTable('users') .addColumn('id', 'serial', col => col.primaryKey()) .addColumn('email', 'varchar(255)', col => col.notNull().unique()) .addColumn('name', 'varchar(100)', col => col.notNull()) .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`) ) .execute() }, async db => { await db.schema.dropTable('users').execute() } ) ] ``` -------------------------------- ### Install @kysera/migrations Source: https://kysera.dev/docs/api/migrations Install the package along with its required peer dependency, zod. ```bash npm install @kysera/migrations zod ``` -------------------------------- ### Install @kysera/dal and dependencies Source: https://kysera.dev/docs/api/dal Commands to install the core library, executor for plugin support, and specific plugins. ```bash # Basic installation (Kysely only) npm install @kysera/dal kysely # With plugin support (recommended) npm install @kysera/dal @kysera/executor kysely # Add plugins as needed npm install @kysera/soft-delete @kysera/rls @kysera/audit ``` -------------------------------- ### Explain Command Examples Source: https://kysera.dev/docs/cli/query Examples of using the explain command with various options like analyze and format. ```bash # Basic execution plan kysera query explain "SELECT * FROM users WHERE id = 1" # With analyze (runs the query) kysera query explain "SELECT * FROM orders WHERE user_id = 5" --analyze # JSON format output kysera query explain "SELECT * FROM products" --format json ``` -------------------------------- ### Install @kysera/dialects Source: https://kysera.dev/docs/api/dialects Install the package along with its required peer dependency, Kysely. ```bash npm install @kysera/dialects kysely ``` -------------------------------- ### Migration creation examples Source: https://kysera.dev/docs/cli/migrate Common usage patterns for creating migrations with templates. ```bash # Basic migration kysera migrate create add_users_table # With template kysera migrate create create_posts --template create-table --table posts # Add columns kysera migrate create add_email --template add-columns --table users ``` -------------------------------- ### Common generation examples Source: https://kysera.dev/docs/cli/generate Various usage examples for the generate command. ```bash # Generate model for users table kysera generate model User # Generate full CRUD with soft delete kysera generate crud Post --with-soft-delete # Generate to custom directory kysera generate crud Order --output-dir ./src/domain # Regenerate existing files kysera generate crud User --overwrite ``` -------------------------------- ### Install Health Monitoring Package Source: https://kysera.dev/docs/api/core/health Install the @kysera/infra package to access current health monitoring utilities. ```bash npm install @kysera/infra ``` -------------------------------- ### Fresh migration examples Source: https://kysera.dev/docs/cli/migrate Common usage patterns for the fresh command. ```bash # Fresh migration (requires confirmation) kysera migrate fresh # Fresh migration with seeds kysera migrate fresh --seed # Skip confirmation kysera migrate fresh --force ``` -------------------------------- ### Install Kysera packages Source: https://kysera.dev Install the core repository package and desired plugins via npm. ```bash npm install kysely @kysera/repository @kysera/soft-delete ``` -------------------------------- ### Install @kysera/executor Source: https://kysera.dev/docs/api/executor Install the package along with the required Kysely peer dependency. ```bash npm install @kysera/executor kysely ``` -------------------------------- ### Query analysis examples Source: https://kysera.dev/docs/cli/query Examples of analyzing simple and complex SQL queries. ```bash # Analyze a SELECT query kysera query analyze "SELECT * FROM users WHERE status = 'active'" # Analyze a complex query kysera query analyze "SELECT u.*, COUNT(o.id) FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id" ``` -------------------------------- ### Repository Validation Examples Source: https://kysera.dev/docs/cli/repository Examples of running validation with strict mode, table filtering, and fix suggestions. ```bash # Validate all repositories kysera repository validate # Strict validation kysera repository validate --strict # Validate specific table kysera repository validate --table users # Get fix suggestions kysera repository validate --fix ``` -------------------------------- ### Configure Audit Plugin Source: https://kysera.dev/docs/plugins/audit Examples for initializing the audit plugin with various configurations. ```javascript // Basic setup auditPlugin({ getUserId: () => currentUser?.id }) // Full setup with metadata auditPlugin({ getUserId: () => currentUser?.id, captureOldValues: true, captureNewValues: true, metadata: () => ({ ip: request.ip, userAgent: request.headers['user-agent'], requestId: request.id }), excludeTables: ['sessions', 'audit_logs'] }) // UUID primary keys auditPlugin({ primaryKeyColumn: 'uuid', getUserId: () => currentUser?.uuid }) ``` -------------------------------- ### Install Kysely and Database Driver Source: https://kysera.dev/docs/getting-started Install the required Kysely peer dependency and the specific database driver for your project. ```bash # Install Kysely (peer dependency) and database driver npm install kysely@^0.28.15 pg # For other databases: # npm install kysely@^0.28.15 mysql2 # MySQL # npm install kysely@^0.28.15 better-sqlite3 # SQLite ``` -------------------------------- ### Repository list command examples Source: https://kysera.dev/docs/cli/repository Various usage examples for the list command, including filtering by directory, pattern, and output format. ```bash # List all repositories kysera repository list # List with method details kysera repository list --show-methods # List with schema information kysera repository list --show-schemas # Scan a different directory kysera repository list --directory lib # Custom file pattern kysera repository list --pattern "**/*Repo.ts" # Output as JSON for scripting kysera repository list --json ``` -------------------------------- ### Install Kysera CLI Source: https://kysera.dev/docs/cli/overview Install the CLI globally via npm or execute commands directly using npx. ```bash npm install -g @kysera/cli # or npx @kysera/cli ``` -------------------------------- ### Query records by timestamp examples Source: https://kysera.dev/docs/cli/query Various examples for querying records using different options like duration, date ranges, and output formats. ```bash # Query users created in the last 24 hours kysera query by-timestamp --table users --last 24h # Query orders from last 7 days kysera query by-timestamp --table orders --last 7d # Query with specific date range kysera query by-timestamp --table posts \ --from "2025-01-01" \ --to "2025-01-31" # Query by updated_at column kysera query by-timestamp --table products \ --column updated_at \ --last 1w # Query oldest first kysera query by-timestamp --table logs --last 24h --order asc # Output as JSON kysera query by-timestamp --table events --last 1h --json ``` -------------------------------- ### Built-in Plugins Source: https://kysera.dev/docs/api/migrations Examples of initializing standard logging and metrics plugins. ```typescript // Logging plugin const loggingPlugin = createLoggingPlugin(logger) // Metrics plugin const metricsPlugin = createMetricsPlugin() ``` -------------------------------- ### Repository Inspection Examples Source: https://kysera.dev/docs/cli/repository Examples of inspecting a repository with various flags for source code and type information. ```bash # Inspect UserRepository kysera repository inspect UserRepository # Show source code kysera repository inspect UserRepository --show-source # Show TypeScript types kysera repository inspect UserRepository --show-types ``` -------------------------------- ### List Kysera plugins Source: https://kysera.dev/docs/cli/plugin Basic command to list available and installed plugins. ```bash kysera plugin list [options] ``` -------------------------------- ### Use formatSQL Source: https://kysera.dev/docs/api/core/debug Example of formatting a raw SQL string. ```typescript import { formatSQL } from '@kysera/core' const sql = 'SELECT id, name, email FROM users WHERE status = $1 ORDER BY created_at DESC' console.log(formatSQL(sql)) // SELECT id, name, email // FROM users // WHERE status = $1 // ORDER BY created_at DESC ``` -------------------------------- ### Migration down examples Source: https://kysera.dev/docs/cli/migrate Common usage patterns for rolling back migrations. ```bash # Rollback last migration kysera migrate down # Rollback 3 migrations kysera migrate down --steps 3 # Rollback all (requires --force) kysera migrate down --all --force # Preview rollback kysera migrate down --dry-run # Rollback in specific schema kysera migrate down --schema tenant_acme ``` -------------------------------- ### Quick Start Commands Source: https://kysera.dev/docs/cli/overview Common commands for initializing projects, managing migrations, and generating CRUD code. ```bash # Initialize new project kysera init my-app -d postgres # Create a migration kysera migrate create add_users_table # Run migrations kysera migrate up # Generate CRUD for a table kysera generate crud User # Check database health kysera health check ``` -------------------------------- ### Initialize Projects Source: https://kysera.dev/docs/cli/overview Commands to set up new Kysera projects with optional database and template configurations. ```bash kysera init my-app kysera init my-app -d postgres -t api ``` -------------------------------- ### Install @kysera/rls Source: https://kysera.dev/docs/api/rls Install the package via npm. ```bash npm install @kysera/rls ``` -------------------------------- ### Setup test environment Source: https://kysera.dev/docs/cli/test Initializes the test environment. Use the provided options to configure database, migrations, and seeding. ```bash kysera test setup ``` -------------------------------- ### Install @kysera/audit Source: https://kysera.dev/docs/api/audit Install the package via npm. ```bash npm install @kysera/audit ``` -------------------------------- ### Schema Comparison Output Source: https://kysera.dev/docs/cli/schema Example output showing differences between two schemas. ```text Schema Comparison ============================================================ Schema Overview: template tenant_acme ------------------------------ ------------------------------ Tables: 15 Tables: 16 Size: 1.24 MB Size: 2.34 MB Tables only in 'template' (1): - archived_users Tables only in 'tenant_acme' (2): + custom_settings + tenant_config Common tables (14): users, posts, comments, categories, tags ... and 9 more ------------------------------------------------------------ Summary: Total tables in 'template': 15 Total tables in 'tenant_acme': 16 Common tables: 14 Unique to 'template': 1 Unique to 'tenant_acme': 2 Hints: To sync missing tables, run migrations on 'tenant_acme' ``` -------------------------------- ### Schema clone usage examples Source: https://kysera.dev/docs/cli/schema Common usage patterns for cloning schemas. ```bash # Clone structure only kysera schema clone template new_tenant # Clone with data kysera schema clone template new_tenant --include-data # Clone as tenant schema kysera schema clone template --tenant acme # Creates: tenant_acme # Exclude certain tables kysera schema clone template new_tenant --exclude logs sessions # Without confirmation kysera schema clone template new_tenant --force ``` -------------------------------- ### Install @kysera/timestamps Source: https://kysera.dev/docs/api/timestamps Use npm to install the package as a dependency. ```bash npm install @kysera/timestamps ``` -------------------------------- ### Basic Repository Setup Source: https://kysera.dev/docs/api/repository Initialize the plugin container and create a repository with automatic plugin interceptors and extension methods. ```typescript import { createORM } from '@kysera/repository' import { softDeletePlugin } from '@kysera/soft-delete' import { rlsPlugin } from '@kysera/rls' // Create plugin container (repository manager) with plugins const orm = await createORM(db, [ rlsPlugin({ schema: rlsSchema }), // Query interceptor + repository extensions softDeletePlugin() // Query interceptor + repository extensions ]) // Create repository factory function const createUserRepository = (executor: Kysely, applyPlugins: ApplyPluginsFunction) => { const factory = createRepositoryFactory(executor) return factory.create({ tableName: 'users', mapRow: row => row, schemas: { create: zodAdapter(CreateUserSchema) } }) } // Create repository - gets both interceptors and extension methods const userRepo = orm.createRepository(createUserRepository) // Query interceptors applied automatically const users = await userRepo.findAll() // RLS + soft-delete filters applied // Extension methods available from plugins await userRepo.softDelete(userId) // from softDeletePlugin await userRepo.restore(userId) // from softDeletePlugin ``` -------------------------------- ### Install @kysera/soft-delete Source: https://kysera.dev/docs/api/soft-delete Use npm to install the soft-delete plugin package. ```bash npm install @kysera/soft-delete ``` -------------------------------- ### Initialize Adapters Across Runtimes Source: https://kysera.dev/docs/api/dialects Demonstrates how to initialize adapters for different runtimes and database drivers. All adapters follow a unified interface for consistency. ```javascript // Node.js with pg import pg from 'pg' const { Pool } = pg // Bun with pg import { Pool } from 'pg' // Node.js with better-sqlite3 import Database from 'better-sqlite3' // All work the same way const adapter = getAdapter('postgres') ``` -------------------------------- ### Create a PostgreSQL Adapter Source: https://kysera.dev/docs/api/dialects Examples of initializing the adapter with default settings, custom schemas, or custom loggers. ```typescript import { createPostgresAdapter } from '@kysera/dialects' // Default (public schema) const adapter = createPostgresAdapter() // Custom default schema const authAdapter = createPostgresAdapter({ defaultSchema: 'auth' }) // With logger const adapter = createPostgresAdapter({ defaultSchema: 'app', logger: myLogger }) ``` -------------------------------- ### Generated repository example Source: https://kysera.dev/docs/cli/generate Example output for a generated repository class. ```typescript // src/repositories/user.repository.ts import { createRepositoryFactory } from '@kysera/repository' import { UserSchema, CreateUserSchema, UpdateUserSchema } from '../schemas/user.schema' export function createUserRepository(executor: Executor) { const factory = createRepositoryFactory(executor) return factory.create({ tableName: 'users' as const, mapRow: (row) => ({ ... }), schemas: { entity: UserSchema, create: CreateUserSchema, update: UpdateUserSchema } }) } ``` -------------------------------- ### Generated model example Source: https://kysera.dev/docs/cli/generate Example output for a generated user model. ```typescript // src/models/user.ts import { Generated } from 'kysely' export interface User { id: number email: string name: string createdAt: Date } export interface UserTable { id: Generated email: string name: string created_at: Generated } export type NewUser = Omit export type UserUpdate = Partial ``` -------------------------------- ### CLI Options Source: https://kysera.dev/docs/cli/init Available flags for customizing the project initialization. ```bash -t, --template Project template (default: basic) Options: basic, api, graphql, monorepo -d, --database Database dialect (default: postgres) Options: postgres, mysql, sqlite -p, --plugins Comma-separated plugin names Default: timestamps,soft-delete --package-manager Package manager (npm/pnpm/yarn/bun) --typescript Use TypeScript (default: true) --no-typescript Use JavaScript --git Initialize git repository (default: true) --no-git Skip git initialization --install Install dependencies (default: true) --no-install Skip dependency installation ``` -------------------------------- ### Execute Blog App CLI Demonstration Source: https://kysera.dev/docs/examples/blog-app Demonstrates database health checks, user repository operations, pagination, and soft delete workflows using Kysera. ```javascript import { db, pool } from './db/connection.js' import { createUserRepository } from './repositories/user.repository.js' import { paginate } from '@kysera/core' import { checkDatabaseHealth } from '@kysera/infra' async function main() { console.log('🚀 Blog App Example - Kysera') // Check database health const health = await checkDatabaseHealth(db, pool) console.log('Database health:', health) // Create repository instance const userRepo = createUserRepository(db) // Create user console.log('\n📝 Creating user...') const user = await userRepo.create({ email: 'john@example.com', name: 'John Doe' }) console.log('Created user:', user) // Find by email console.log('\n🔍 Finding user by email...') const foundUser = await userRepo.findByEmail('john@example.com') console.log('Found user:', foundUser) // Update user console.log('\n✏️ Updating user...') if (foundUser) { const updated = await userRepo.update(foundUser.id, { name: 'John Updated' }) console.log('Updated user:', updated) } // Pagination console.log('\n📋 Listing users with pagination...') const query = db .selectFrom('users') .selectAll() .where('deleted_at', 'is', null) .orderBy('created_at', 'desc') const paginatedUsers = await paginate(query, { page: 1, limit: 10 }) console.log('Paginated users:', paginatedUsers) // Soft delete and restore console.log('\n🗑️ Soft deleting user...') if (foundUser) { await userRepo.softDelete(foundUser.id) console.log('User soft deleted') const deletedUser = await userRepo.findById(foundUser.id) console.log('User after soft delete:', deletedUser) // Should be null console.log('\n♻️ Restoring user...') await userRepo.restore(foundUser.id) const restoredUser = await userRepo.findById(foundUser.id) console.log('Restored user:', restoredUser) } await db.destroy() console.log('\n✅ Example completed!') } main().catch(error => { console.error('Error:', error) process.exit(1) }) ``` -------------------------------- ### Onboarding Commands Source: https://kysera.dev/docs/cli/repository Commands for exploring repository queries and inspecting source code. ```bash # Understand available queries kysera repository methods --filter "find*" # Inspect specific repository kysera repository inspect UserRepository --show-source ``` -------------------------------- ### Initialize database contexts with Kysera Source: https://kysera.dev/docs/api/dal Examples showing context creation with executors, plain Kysely instances, and schema overrides. ```typescript import { createContext } from '@kysera/dal' import { createExecutor } from '@kysera/executor' // With KyseraExecutor (plugins preserved) const executor = await createExecutor(db, [softDeletePlugin()]) const ctx = createContext(executor) const user = await findUserById(ctx, 1) // soft-delete filter applied // With plain Kysely const plainCtx = createContext(db) const allUsers = await findUserById(plainCtx, 1) // no plugin filtering // With schema option const schemaCtx = createContext(executor, { schema: 'auth' }) const authUsers = await findUserById(schemaCtx, 1) // queries use 'auth' schema ``` -------------------------------- ### Install Testing Package Source: https://kysera.dev/docs/api/core/testing Install the dedicated testing package as a development dependency. ```bash npm install --save-dev @kysera/testing ``` -------------------------------- ### Initialize Repository with Plugins Source: https://kysera.dev/docs/api/repository Demonstrates the lifecycle of creating an ORM with plugins, extending repositories, and executing intercepted queries. ```typescript import { createORM } from '@kysera/repository' import { softDeletePlugin } from '@kysera/soft-delete' // 1. createORM creates executor with plugins const orm = await createORM(db, [softDeletePlugin()]) // 2. createRepository creates base repository const userRepo = orm.createRepository((executor, applyPlugins) => { const factory = createRepositoryFactory(executor) return factory.create({ tableName: 'users', ... }) }) // 3. Plugins extend the repository via extendRepository // Result: userRepo has both automatic filtering AND extension methods // 4. Query interceptors apply automatically const users = await userRepo.findAll() // -> SELECT * FROM users WHERE deleted_at IS NULL // 5. Extension methods available await userRepo.softDelete(userId) // -> UPDATE users SET deleted_at = NOW() WHERE id = ? ``` -------------------------------- ### Basic repository creation with plugins Source: https://kysera.dev/docs/api/repository Example showing how to define a repository factory and instantiate it with the soft delete plugin. ```typescript import { withPlugins } from '@kysera/repository' import { softDeletePlugin } from '@kysera/soft-delete' // Define your repository factory const createUserRepo = (executor: Kysely, applyPlugins: ApplyPluginsFunction) => { const factory = createRepositoryFactory(executor) return factory.create({ tableName: 'users', mapRow: row => ({ id: row.id, email: row.email, name: row.name }), schemas: { create: zodAdapter( z.object({ email: z.string().email(), name: z.string() }) ) } }) } // Create repository with soft delete plugin const userRepo = await withPlugins(createUserRepo, db, [ softDeletePlugin({ deletedAtColumn: 'deleted_at' }) ]) // Use extended methods from plugin await userRepo.softDelete(1) await userRepo.restore(2) ``` -------------------------------- ### Generated schema example Source: https://kysera.dev/docs/cli/generate Example output for a generated Zod schema file. ```typescript // src/schemas/user.schema.ts import { z } from 'zod' export const UserSchema = z.object({ id: z.number(), email: z.string().email(), name: z.string(), createdAt: z.date() }) export const CreateUserSchema = z.object({ email: z.string().email(), name: z.string().min(1).max(100) }) export const UpdateUserSchema = CreateUserSchema.partial() export type User = z.infer export type CreateUser = z.infer export type UpdateUser = z.infer ``` -------------------------------- ### Install Required Peer Dependency Source: https://kysera.dev/docs/guides/migration-v07 Install the required @kysera/executor package when upgrading to v0.7. ```bash pnpm add @kysera/executor ``` -------------------------------- ### Install Debug Package Source: https://kysera.dev/docs/api/core/debug Install the @kysera/debug package to access current debug utilities. ```bash npm install @kysera/debug ``` -------------------------------- ### Quick Start with Factories and Transactions Source: https://kysera.dev/docs/api/testing Demonstrates creating a data factory and running a test within an automatically rolling-back transaction. ```typescript import { testInTransaction, createFactory } from '@kysera/testing' const createUser = createFactory({ email: () => `user-${Date.now()}@example.com`, name: 'Test User', role: 'user' }) it('creates user', async () => { await testInTransaction(db, async trx => { const userData = createUser({ name: 'Alice' }) const user = await trx.insertInto('users').values(userData).returningAll().executeTakeFirst() expect(user?.name).toBe('Alice') }) // Database automatically rolled back - no cleanup needed! }) ``` -------------------------------- ### Install Missing Dependencies Source: https://kysera.dev/docs/guides/troubleshooting Ensure the executor package is installed and all Kysera packages are updated to the same version. ```bash pnpm add @kysera/executor ``` ```bash pnpm update @kysera/core @kysera/executor @kysera/repository @kysera/dal ``` -------------------------------- ### Define multiple migrations example Source: https://kysera.dev/docs/api/migrations An example of using defineMigrations to register multiple migration definitions. ```typescript const migrations = defineMigrations({ '001_create_users': { description: 'Create users table', up: async (db) => { await db.schema.createTable('users')./* ... */.execute() }, down: async (db) => { await db.schema.dropTable('users').execute() } }, '002_add_posts': { description: 'Create posts table', breaking: false, up: async (db) => { /* ... */ }, down: async (db) => { /* ... */ } } }) ``` -------------------------------- ### Setup with Repository Source: https://kysera.dev/docs/api/soft-delete Initialize the ORM with the softDeletePlugin to enable automatic filtering and soft-delete methods on repositories. ```typescript import { createORM } from '@kysera/repository' import { softDeletePlugin } from '@kysera/soft-delete' const orm = await createORM(db, [ softDeletePlugin({ deletedAtColumn: 'deleted_at', tables: ['users', 'posts'] }) ]) const userRepo = orm.createRepository(createUserRepository) // Automatic filtering - findAll excludes soft-deleted const activeUsers = await userRepo.findAll() // Soft delete operations await userRepo.softDelete(userId) await userRepo.restore(userId) ``` -------------------------------- ### Metrics Pool Usage Example Source: https://kysera.dev/docs/api/core/health Demonstrates initializing a PostgreSQL pool with metrics tracking. ```typescript import { createMetricsPool } from '@kysera/core' import { Pool } from 'pg' const pool = new Pool({ max: 10 }) const metricsPool = createMetricsPool(pool) // Get metrics console.log(metricsPool.totalCount) // 10 console.log(metricsPool.idleCount) // 8 console.log(metricsPool.waitingCount) // 0 ``` -------------------------------- ### Initializing and Using the Executor Source: https://kysera.dev/docs/api/overview Demonstrates creating an executor with plugins and executing queries, including transaction support. ```typescript import { createExecutor } from '@kysera/executor' import { softDeletePlugin } from '@kysera/soft-delete' const executor = await createExecutor(db, [softDeletePlugin()]) // Automatic soft-delete filtering const users = await executor.selectFrom('users').selectAll().execute() // Works in transactions await executor.transaction().execute(async trx => { // Plugins automatically applied const user = await trx.selectFrom('users').where('id', '=', 1).executeTakeFirst() }) ``` -------------------------------- ### Repository Method Examples Source: https://kysera.dev/docs/cli/repository Common usage patterns for listing, filtering, and grouping repository methods. ```bash # List all methods kysera repository methods # Show full signatures kysera repository methods --show-signatures # Filter by pattern kysera repository methods --filter "find*" # Group by method type kysera repository methods --group-by method-type ``` -------------------------------- ### Repository Factory Usage Example Source: https://kysera.dev/docs/api/repository Demonstrates initializing repositories and performing operations within a transaction using the factory. ```typescript import { createRepositoriesFactory } from '@kysera/repository' // Define your repository factories const createRepos = createRepositoriesFactory({ users: executor => createUserRepository(executor), posts: executor => createPostRepository(executor), comments: executor => createCommentRepository(executor) }) // Normal usage with database instance const repos = createRepos(db) await repos.users.findById(1) await repos.posts.findAll() // Transaction usage (clean one-liner!) await db.transaction().execute(async trx => { const repos = createRepos(trx) const user = await repos.users.create({ name: 'Alice', email: 'alice@example.com' }) await repos.posts.create({ userId: user.id, title: 'Hello World' }) await repos.comments.create({ postId: post.id, text: 'Great post!' }) }) ``` -------------------------------- ### Audit comparison examples Source: https://kysera.dev/docs/cli/audit Examples for comparing audit entries with different output formats and detail levels. ```bash # Compare two audit entries kysera audit compare 100 123 # Compare with full values kysera audit compare 100 123 --show-values # Output as JSON kysera audit compare 100 123 --json ``` -------------------------------- ### Quick Migration Usage Source: https://kysera.dev/docs/api/migrations Basic implementation examples for running, rolling back, and checking migration status. ```typescript // Quick usage await runMigrations(db, migrations) await rollbackMigrations(db, migrations, 1) const status = await getMigrationStatus(db, migrations) ``` -------------------------------- ### Audit Log Entry Examples Source: https://kysera.dev/docs/api/audit Examples of audit log structures generated for different database operations. ```javascript await userRepo.create({ email: 'john@example.com', name: 'John' }) // Audit log entry: // { // operation: 'INSERT', // old_values: null, // new_values: '{"email":"john@example.com","name":"John","id":1}' // } ``` ```javascript await userRepo.update(userId, { name: 'John Smith' }) // Audit log entry: // { // operation: 'UPDATE', // old_values: '{"name":"John"}', // new_values: '{"name":"John Smith"}' // } ``` ```javascript await userRepo.delete(userId) // Audit log entry: // { // operation: 'DELETE', // old_values: '{"id":1,"email":"john@example.com","name":"John Smith"}', // new_values: null // } ``` -------------------------------- ### Initialize Template Schema Source: https://kysera.dev/docs/cli/schema Commands to create and migrate the base template schema. ```bash # Create template schema kysera schema create template # Run migrations in template kysera migrate up --schema template ``` -------------------------------- ### Audit statistics command examples Source: https://kysera.dev/docs/cli/audit Examples for filtering audit statistics by time period, table, user, and output format. ```bash # Overall statistics for last day kysera audit stats # Statistics for last week kysera audit stats --period 1w # Statistics for specific table kysera audit stats --table users # Statistics for specific user kysera audit stats --user "admin-123" # Output as JSON kysera audit stats --format json # Statistics for last month as chart kysera audit stats --period 1m --format chart ``` -------------------------------- ### Install Kysera Infrastructure Source: https://kysera.dev/docs/getting-started Add infrastructure utilities for health checks, debugging, testing, and migrations. ```bash npm install @kysera/infra # Health checks, retry, circuit breaker (~12KB) npm install @kysera/debug # Query logging and profiling (~5KB) npm install @kysera/testing # Test utilities (~6KB) - dev dependency npm install @kysera/migrations # Migration system (~11KB) ``` -------------------------------- ### Create a simple repository Source: https://kysera.dev/docs/api/repository/factory Initializes a repository without the factory pattern, defaulting to nativeAdapter. ```typescript function createSimpleRepository( executor: Executor, tableName: TableName, mapRow: (row: Selectable) => Entity, options?: { primaryKey?: PrimaryKeyColumn primaryKeyType?: PrimaryKeyTypeHint dialect?: DialectConfig } ): Repository ``` ```typescript const userRepo = createSimpleRepository(db, 'users', row => row, { primaryKey: 'id' }) ``` -------------------------------- ### Install MSSQL Dependencies Source: https://kysera.dev/docs/guides/multi-database Required packages for MSSQL integration. ```bash pnpm add kysely tedious tarn pnpm add -D @types/tedious @types/tarn ``` -------------------------------- ### Initialize Infrastructure Utilities Source: https://kysera.dev/docs/api/infra Configure health monitoring, circuit breakers, and graceful shutdown handlers for a Kysely database instance. ```typescript import { checkDatabaseHealth, HealthMonitor, withRetry, CircuitBreaker, registerShutdownHandlers, createMetricsPool } from '@kysera/infra' // Create metrics-enabled pool const metricsPool = createMetricsPool(pgPool) // Health monitoring const monitor = new HealthMonitor(db, { pool: metricsPool, intervalMs: 30000 }) monitor.start(result => { if (result.status !== 'healthy') console.warn('Health issue:', result) }) // Resilience patterns const breaker = new CircuitBreaker(5, 60000) const users = await breaker.execute(() => withRetry(() => db.selectFrom('users').execute())) // Graceful shutdown registerShutdownHandlers(db, { timeout: 10000, onShutdown: async () => monitor.stop() }) ``` -------------------------------- ### Install SQLite Dependencies Source: https://kysera.dev/docs/guides/multi-database Required packages for SQLite integration. ```bash pnpm add kysely better-sqlite3 pnpm add -D @types/better-sqlite3 ``` -------------------------------- ### Install MySQL Dependencies Source: https://kysera.dev/docs/guides/multi-database Required packages for MySQL integration. ```bash pnpm add kysely mysql2 ``` -------------------------------- ### Install PostgreSQL Dependencies Source: https://kysera.dev/docs/guides/multi-database Required packages for PostgreSQL integration. ```bash pnpm add kysely pg pnpm add -D @types/pg ``` -------------------------------- ### Profiling Examples Source: https://kysera.dev/docs/cli/debug Common usage patterns for profiling queries, tables, and comparing performance. ```bash # Profile a specific query kysera debug profile --query "SELECT * FROM users WHERE status = 'active'" # Profile table operations kysera debug profile --table users --operation select # Profile with execution plan kysera debug profile --query "SELECT * FROM orders" --show-plan # Compare two queries kysera debug profile \ --query "SELECT * FROM users WHERE id = 1" \ --compare "SELECT * FROM users WHERE email = 'test@example.com'" # Custom iterations kysera debug profile --query "SELECT 1" --iterations 1000 --warmup 50 ```