bởi Lin X.

Kysely is a type-safe, autocompletion-friendly TypeScript SQL query builder for Node.js, Deno, Bun, Cloudflare Workers, and browsers. It ensures compile-time correctness for tables, columns, aliases, and result types across PostgreSQL, MySQL, SQLite, and more.
Kysely is a type-safe, autocompletion-friendly TypeScript SQL query builder that compiles queries at the type level, ensuring you only reference tables and columns visible in the current query scope. It targets backend Node.js services but runs in Deno, Bun, Cloudflare Workers, and browsers. The typical buyer is a TypeScript backend developer who wants compile-time SQL correctness without a full ORM.
dialect/ - Database-specific adapters, drivers, introspectors, and query compilers for PostgreSQL, MySQL, SQLite, and MSSQLdriver/ - Connection provider abstractions, runtime driver wrapper, and database connection interfacesdynamic/ - Escape-hatch utilities (DynamicModule, DynamicReferenceBuilder) for runtime-determined column/table referencesexpression/ - Core expression types, ExpressionBuilder, and ExpressionWrapper used throughout query buildinghelpers/ - Dialect-specific helper functions for PostgreSQL, MySQL, SQLite, and MSSQLmigration/ - Migrator class and FileMigrationProvider for schema migration managementoperation-node/ - Internal AST node types representing every SQL constructparser/ - Internal parsers that convert TypeScript values into operation nodesplugin/ - Plugin interface and built-in plugins (e.g., WithSchemaPlugin, camel-case mapper)query-builder/ - All query builder classes: select, insert, update, delete, merge, join, case, aggregate, etc.query-compiler/ - DefaultQueryCompiler and CompiledQuery for turning AST nodes into SQL stringsquery-executor/ - Execution pipeline: DefaultQueryExecutor, NoopQueryExecutor, provider interfacesraw-builder/ - sql template tag and RawBuilder for raw SQL fragmentsschema/ - DDL builders: CreateTableBuilder, DropTableBuilder, CreateIndexBuilder, etc.util/ - Internal utilities (object helpers, logging, type utilities)index.ts - Barrel re-export of the entire public APIKhởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 d97e3c60acfba3c4…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
kysely.ts - Kysely class: the root database handle with transaction supportquery-creator.ts - QueryCreator class: select/insert/update/delete/merge entry pointsnpm install kysely
# Choose exactly one driver package that matches your dialect:
npm install pg # PostgreSQL
npm install mysql2 # MySQL
npm install better-sqlite3 # SQLite (sync)
npm install tedious # MSSQL
No native build steps are required for kysely itself. better-sqlite3 requires a native build; ensure you have node-gyp prerequisites (Python, C++ compiler) or use a prebuilt binary.
Copy the source/ directory into your project, e.g. src/kysely-source/, or simply install the upstream package user@example.com and import from it directly - the source is identical.
Configure tsconfig.json for strict mode and module resolution:
{
"compilerOptions": {
"strict": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"esModuleInterop": true
}
}
source/ copy instead of the npm package, add a path alias:{
"compilerOptions": {
"paths": {
"kysely": ["./src/kysely-source/index.ts"]
}
}
}
Define your database schema as a TypeScript interface (see examples below). No env vars are required by Kysely itself; pass connection credentials directly to the dialect config.
Instantiate Kysely once at application startup, share the instance, and call db.destroy() on shutdown.
import { Kysely, PostgresDialect } from 'kysely'
const db = new Kysely<Database>({
dialect: new PostgresDialect({ pool }),
log: ['query', 'error'],
})
The root class that ties together a dialect, connection pool, plugins, and logging. Create a single shared instance per process. Use db.transaction().execute(trx => ...) for transactions and db.withSchema('schema_name') to scope queries to a non-default schema.
import { QueryCreator } from 'kysely'
// Accessed via db.selectFrom / db.insertInto / db.updateTable / db.deleteFrom
const query = db.selectFrom('person').selectAll()
QueryCreator is the base class behind Kysely that provides selectFrom, insertInto, updateTable, deleteFrom, and mergeInto. You rarely instantiate it directly; interact with it through the Kysely instance.
import { sql } from 'kysely'
const fragment = sql<string>`now()`
const withParam = sql`${sql.literal('active')}::text`
A tagged template literal that produces a RawBuilder / Sql fragment for embedding raw SQL safely inside typed queries. Use it when Kysely's typed API does not cover a database-specific expression. Values passed as interpolations are parameterized automatically unless wrapped in sql.literal or sql.id.
import { expressionBuilder } from 'kysely'
const eb = expressionBuilder<Database, 'person'>()
const expr = eb('age', '>', 18)
A standalone factory returning an ExpressionBuilder outside of a query chain. Useful for extracting reusable where-clause fragments into helper functions.
Connect to PostgreSQL and select typed rows from joined tables.
import { Kysely, PostgresDialect } from 'kysely'
import { Pool } from 'pg'
interface Database {
person: { id: number; name: string; age: number }
pet: { id: number; owner_id: number; name: string; species: string }
}
const db = new Kysely<Database>({
dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL }) }),
})
async function getPeopleWithPets() {
return db
.selectFrom('person')
.innerJoin('pet', 'pet.owner_id', 'person.id')
.select(['person.name', 'pet.name as pet_name', 'person.age'])
.where('person.age', '>', 18)
.orderBy('person.name', 'asc')
.execute()
}
// Return type: { name: string; pet_name: string; age: number }[]
Insert a row into PostgreSQL and retrieve the generated primary key.
async function createPerson(db: Kysely<Database>, name: string, age: number) {
const result = await db
.insertInto('person')
.values({ name, age })
.returning(['id', 'name'])
.executeTakeFirstOrThrow()
return result // { id: number; name: string }
}
Run multiple writes atomically; any thrown error triggers an automatic rollback.
import { sql } from 'kysely'
async function transferOwnership(
db: Kysely<Database>,
petId: number,
newOwnerId: number,
) {
await db.transaction().execute(async (trx) => {
await trx
.updateTable('pet')
.set({ owner_id: newOwnerId })
.where('id', '=', petId)
.execute()
await sql`SELECT pg_sleep(0)`.execute(trx) // arbitrary raw SQL in transaction
})
}
Create a table using the DDL schema builder and run migrations.
import { Kysely, Migrator, FileMigrationProvider } from 'kysely'
import * as path from 'path'
import * as fs from 'fs/promises'
async function migrateToLatest(db: Kysely<any>) {
const migrator = new Migrator({
db,
provider: new FileMigrationProvider({
fs,
path,
migrationFolder: path.join(__dirname, 'migrations'),
}),
})
const { error, results } = await migrator.migrateToLatest()
results?.forEach((r) => console.log(r.migrationName, r.status))
if (error) throw error
}
index.ts - Single barrel export; import everything public from here.kysely.ts - Defines the Kysely<DB> class: initialization, transactions, withSchema, destroy.query-creator.ts - QueryCreator<DB>: selectFrom, insertInto, updateTable, deleteFrom, mergeInto, with (CTEs).dialect/ - Each subdirectory (postgres/, mysql/, sqlite/, mssql/) contains a dialect class, driver, introspector, adapter, and query compiler. Implement the Dialect interface to add a custom database.driver/ - Driver, DatabaseConnection, ConnectionProvider interfaces plus RuntimeDriver (lifecycle management) and SingleConnectionProvider (used by transactions).dynamic/ - DynamicModule.ref() for column references that are unknown at compile time.expression/ - Expression<T> interface, ExpressionBuilder, and ExpressionWrapper - the glue between typed queries and raw nodes.helpers/ - Dialect-specific convenience functions (e.g., jsonArrayFrom for PostgreSQL).migration/ - Migrator orchestrates up/down migrations; FileMigrationProvider loads .ts/.js files from a directory.operation-node/ - Immutable AST node definitions for every SQL construct; not consumed directly by application code.parser/ - Converts user-facing TypeScript values (strings, objects, callbacks) into operation nodes; internal use only.plugin/ - KyselyPlugin interface (transformQuery / transformResult) and WithSchemaPlugin. Implement the interface to intercept all queries.query-builder/ - The builder classes: SelectQueryBuilder, InsertQueryBuilder, UpdateQueryBuilder, DeleteQueryBuilder, MergeQueryBuilder, JoinBuilder, CaseBuilder, AggregateFunctionBuilder, FunctionModule, result types (InsertResult, UpdateResult, DeleteResult, MergeResult).query-compiler/ - DefaultQueryCompiler walks the AST and emits SQL + parameters; CompiledQuery is the output.query-executor/ - DefaultQueryExecutor sends CompiledQuery to the driver and returns QueryResult; NoopQueryExecutor for testing.raw-builder/ - sql template tag, RawBuilder, and the Sql interface.schema/ - DDL builders: CreateTableBuilder, ColumnDefinitionBuilder, CreateIndexBuilder, CreateTypeBuilder, and their drop counterparts.util/ - Internal helpers (freeze, isObject, logging, type utilities). Not part of the public API..js extensions on all internal imports; if bundling with CommonJS set "module": "CommonJS" in tsconfig or use a bundler that handles .js re-exports. Fix: use "moduleResolution": "NodeNext" with "module": "NodeNext".pg types: @types/pg must be installed separately alongside pg. Fix: npm install --save-dev @types/pg.better-sqlite3 native build failures: requires Python and a C++ compiler. Fix: npm install --save-dev @types/better-sqlite3 and ensure build tools are present, or use npm install better-sqlite3 --ignore-scripts with a prebuilt binary.await on .execute(): query builders are lazy; not awaiting silently discards the query. Fix: always await or use void explicitly if fire-and-forget is intended.isolationLevel or accessMode to dialects that don't support them throws at runtime. Fix: check dialect-specific docs; MSSQL and SQLite support subsets of isolation levels.dynamic.ref(): using DynamicModule.ref() drops column-level type safety. Fix: use it only as a last resort and add runtime validation on the result shape.I have the Kysely TypeScript SQL query builder source in `source/` and a usage
guide in `USAGE.md`. The upstream package is `user@example.com`.
My project is a Node.js + TypeScript + Express REST API using PostgreSQL.
Please do the following step by step:
1. Read `USAGE.md` and `source/index.ts` to understand all public exports.
2. Define a `Database` interface in `src/db/types.ts` that maps my existing
table names and columns (I will list them below).
3. Create `src/db/index.ts` that instantiates a single shared `Kysely<Database>`
using `PostgresDialect` with a `pg.Pool` configured from `process.env.DATABASE_URL`.
4. Create a `src/db/migrations/` folder and write an initial migration file using
`CreateTableBuilder` from `source/schema/create-table-builder.ts`.
5. Wire `Migrator` and `FileMigrationProvider` in a `src/db/migrate.ts` script
runnable via `ts-node src/db/migrate.ts`.
6. Write typed repository functions (select, insert, update, delete) for my main
entity table using the query builder methods shown in `USAGE.md`.
7. Show how to wrap multiple writes in a transaction using `db.transaction().execute()`.
My tables: [PASTE YOUR SCHEMA HERE]
Kysely is released under the MIT License. See the LICENSE file in the upstream repository or source/LICENSE if present.
Upstream package: kysely on npm - source repository at github.com/kysely-org/kysely.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí