由 Arno L. 出售

Knex.js is a flexible, portable SQL query builder for Node.js supporting PostgreSQL, MySQL, SQLite3, MSSQL, Oracle, CockroachDB, and more, with transactions, connection pooling, and full TypeScript support.
This block provides the full Knex.js library source (lib/), a multi-dialect SQL query builder for Node.js supporting PostgreSQL, MySQL, SQLite3, MSSQL, CockroachDB, Oracle, and more. It covers query construction, schema building, migrations, connection pooling, and transactions. Typical buyers are backend engineers embedding a battle-tested query layer into a Node.js or TypeScript service without relying on a heavy ORM.
index.js - Main entry point; re-exports the Knex factory functionclient.js - Base Client class shared by all dialects; handles pooling, query execution, loggingformatter.js - Core SQL formatter used during query compilationformatter/ - Extended formatter utilitiesraw.js - Raw expression builder for inline SQL fragmentsref.js - Ref builder for column referencesconstants.js - Library-wide constants (query types, lock modes, etc.)logger.js - Internal logger wrapperbuilder-interface-augmenter.js - TypeScript interface augmentation utilitiesknex-builder/ - Knex factory and KnexTimeoutError; top-level API surfacequery/ - QueryBuilder and QueryCompiler base classesschema/ - SchemaBuilder, TableCompiler, ColumnCompiler, ViewCompilermigrations/ - Migration runner, source adapters, and CLI integrationexecution/ - Transaction base class and runner utilitiesutil/ - Shared helpers (helpers.js, save-async-stack.js, etc.)dialects/ - Per-database dialect overrides (better-sqlite3, cockroachdb, mssql, mysql, mysql2, oracle, oracledb, pgnative, postgres, redshift, sqlite3)npm install colorette commander debug escalade esm get-package-type getopts interpret lodash pg-connection-string rechoir resolve-from tarn tildify
For database-specific native drivers, install the relevant peer package:
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This Express backend / api 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
管道 avcp-2026-08-04.1 · SHA-256 b459e54681c4b6b3…
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.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
# Pick one or more:
npm install pg # postgres / redshift / pgnative / cockroachdb
npm install mysql # mysql
npm install mysql2 # mysql2
npm install sqlite3 # sqlite3
npm install better-sqlite3 # better-sqlite3
npm install mssql # mssql
npm install oracledb # oracledb
better-sqlite3 and sqlite3 require native compilation. Ensure Python 3.x with setuptools and (on Windows) Visual Studio Build Tools with the "Desktop development with C++" workload are installed before running npm install.
Copy the source/ directory into your project, e.g. src/vendor/knex/.
In tsconfig.json, add a path alias so imports resolve cleanly:
{
"compilerOptions": {
"paths": {
"knex-src": ["./src/vendor/knex/index.js"],
"knex-src/*": ["./src/vendor/knex/*"]
}
}
}
Because the source uses CommonJS (require/module.exports), ensure your project either runs under CJS or uses a bundler/transpiler that handles CJS interop. If using ESM, set "esModuleInterop": true in tsconfig.json.
No environment variables are required at the library level. Connection credentials are passed directly to the Knex factory at runtime (see examples below).
For migrations, point knex.migrate at your migrations directory and optionally configure a knexfile.js at the project root.
import Knex from './src/vendor/knex/index.js';
function Knex(config: Knex.Config): Knex.Knex;
interface Config {
client: string; // e.g. 'pg', 'mysql2', 'sqlite3', 'better-sqlite3'
connection: object | string;
pool?: { min?: number; max?: number };
migrations?: { tableName?: string; directory?: string };
debug?: boolean;
}
The main entry point. Call once at startup with your database config; the returned instance is the query builder root. Reuse the same instance across your application — it manages the connection pool internally.
import { getDialectByNameOrAlias } from './src/vendor/knex/dialects/index.js';
function getDialectByNameOrAlias(clientName: string): any;
Resolves a dialect name or known alias (e.g. 'pg' → postgres) and returns the dialect class. Use this when you need to instantiate a dialect directly, inspect its capabilities, or extend it with a custom subclass before passing it to Knex.
// source: client.js
class Client {
queryBuilder(): QueryBuilder;
queryCompiler(builder: QueryBuilder, formatter: Formatter): QueryCompiler;
columnCompiler(...args: any[]): ColumnCompiler;
tableCompiler(...args: any[]): TableCompiler;
transaction(...args: any[]): Transaction;
raw(sql: string, bindings?: any[]): Raw;
}
The abstract base extended by every dialect. Subclass Client when adding a new database backend; override individual factory methods (queryCompiler, columnCompiler, etc.) to inject dialect-specific behaviour, exactly as Client_CockroachDB does over Client_PostgreSQL.
Configure a pg connection, create a table via the schema builder, insert a row, and select it back.
const Knex = require('./src/vendor/knex/index.js');
const db = Knex({
client: 'pg',
connection: {
host: 'localhost',
port: 5432,
user: 'app',
password: 'secret',
database: 'mydb',
},
pool: { min: 2, max: 10 },
});
async function run() {
// Create table if missing
const exists = await db.schema.hasTable('users');
if (!exists) {
await db.schema.createTable('users', (t) => {
t.increments('id');
t.string('email').notNullable().unique();
t.timestamps(true, true);
});
}
// Insert
const [id] = await db('users').insert({ email: 'alice@example.com' }).returning('id');
// Select
const user = await db('users').where({ id }).first();
console.log(user); // { id: 1, email: 'alice@example.com', ... }
await db.destroy();
}
run().catch(console.error);
Wrap multiple writes in a transaction; an error in any step rolls back all changes.
const Knex = require('./src/vendor/knex/index.js');
const db = Knex({ client: 'mysql2', connection: { host: 'localhost', user: 'root', password: '', database: 'shop' } });
async function transferFunds(fromId: number, toId: number, amount: number) {
await db.transaction(async (trx) => {
const sender = await trx('accounts').where({ id: fromId }).forUpdate().first();
if (sender.balance < amount) throw new Error('Insufficient funds');
await trx('accounts').where({ id: fromId }).decrement('balance', amount);
await trx('accounts').where({ id: toId }).increment('balance', amount);
await trx('audit_log').insert({
action: 'transfer',
from_id: fromId,
to_id: toId,
amount,
created_at: db.fn.now(),
});
});
}
transferFunds(1, 2, 500).catch(console.error).finally(() => db.destroy());
Use getDialectByNameOrAlias to inspect or extend a dialect at runtime.
const { getDialectByNameOrAlias } = require('./src/vendor/knex/dialects/index.js');
const Knex = require('./src/vendor/knex/index.js');
// Resolve 'pg' alias → postgres dialect class
const PostgresDialect = getDialectByNameOrAlias('pg');
// Subclass to add custom logging
class InstrumentedPostgres extends PostgresDialect {
async _query(connection: any, obj: any) {
const start = Date.now();
const result = await super._query(connection, obj);
console.log(`[SQL] ${obj.sql} — ${Date.now() - start}ms`);
return result;
}
}
const db = Knex({ client: InstrumentedPostgres, connection: process.env.DATABASE_URL });
db('users').select('*').then(console.log).finally(() => db.destroy());
index.js - Thin re-export; the single public entry point for the library.knex-builder/ - Contains the Knex factory that wires together a Client, pool, and query builder interface.client.js - Abstract base Client; manages driver loading, pool lifecycle, and query dispatch.formatter.js / formatter/ - Translates builder state into SQL strings; handles identifier quoting and parameter binding.raw.js - Wraps raw SQL strings with optional bindings so they compose safely inside builders.ref.js - Wraps a column/table reference to prevent accidental string-escaping in composed queries.query/ - QueryBuilder (fluent API: .select, .where, .join, …) and QueryCompiler (turns builder state into SQL).schema/ - SchemaBuilder, TableCompiler, ColumnCompiler, ViewCompiler; DDL generation.migrations/ - Migration runner, locking, batch tracking, and file-source adapters.execution/ - Base Transaction class and async runner that handles savepoints and rollback.util/ - Miscellaneous helpers: alias resolution, async-stack saving, object utilities.constants.js - Shared string constants for query types, join modes, lock types.logger.js - Thin wrapper around debug for internal library logging.builder-interface-augmenter.js - Applies TypeScript module augmentation to extend the builder interface.dialects/ - One subdirectory per supported database; each overrides only the methods that differ from the base.client alias not resolving - Knex accepts aliases ('pg', 'sqlite') via resolveClientNameWithAliases; if you pass an unrecognised string, getDialectByNameOrAlias throws Invalid clientName. Fix: use one of the canonical names listed in dialects/index.js.module.exports). In an ESM project, use import Knex from '...' only with "esModuleInterop": true and "allowSyntheticDefaultImports": true in tsconfig.json.better-sqlite3 build failure - Requires Python 3 + setuptools and a C++ compiler. On Python 3.12+, run pip install setuptools before npm install.trx.commit() / trx.rollback() or use the callback form of db.transaction().returning() on MySQL/SQLite - INSERT … RETURNING is only supported on PostgreSQL and newer SQLite. On MySQL, use insertId from the raw response instead.db.destroy() not called in scripts - The tarn pool keeps the process alive. Always call await db.destroy() at the end of CLI scripts or tests.I have a copy of the Knex SQL query builder source in `src/vendor/knex/`
(upstream package: user@example.com). The integration guide is in `USAGE.md`.
Please help me integrate Knex into my existing Node.js/TypeScript project step by step:
1. Read `USAGE.md` to understand the public API and available exports.
2. Read `src/vendor/knex/index.js` for the main entry point and
`src/vendor/knex/dialects/index.js` for dialect loading.
3. Create a `src/db.ts` module that initialises a Knex instance using my
environment variables (DATABASE_URL or individual host/user/password/database vars).
4. Export the `db` instance as a singleton so other modules can import it.
5. Add a `src/migrations/` directory and wire up `db.migrate.latest()` on app startup.
6. Show me how to write a type-safe query with `.where()`, `.join()`, and `.returning()`.
7. Show me how to wrap two inserts in a transaction with automatic rollback on error.
8. Point out any ESM/CJS interop issues specific to my project setup and how to fix them.
Use only the APIs documented in USAGE.md and visible in the source files.
Do not invent method names.
Knex is released under the MIT License. See source/LICENSE if present, or refer to the official repository. Upstream package: user@example.com by Tim Griesser and contributors.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费