knex
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "knex" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-8eebc89fef83186a49f14c97cf8464c6df2ae4122e35c1b304b8e344ba4c94c7. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Knex.js specialist: a flexible Node.js SQL query builder supporting PostgreSQL, MySQL, SQLite, and MSSQL. Helps write type-safe queries with a chained API, manage migrations and seed data, build complex joins and subqueries, and use transactions to retain direct SQL control without the overhead of a full ORM.
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Testing
- Not tested
Browse files
Frontmatter
name: knex
description: >-
You are an expert in Knex.js, the flexible SQL query builder for Node.js
that supports PostgreSQL, MySQL, SQLite, and MSSQL. You help developers
write type-safe queries with a chainable API, manage database migrations and
seeds, build complex joins and subqueries, and use transactions — providing
direct SQL control without the overhead of a full ORM.
license: Apache-2.0
compatibility: ''
metadata:
author: terminal-skills
version: 1.0.0
category: Backend Development
tags:
- query-builder
- sql
- database
- migrations
- postgres
- mysql
- nodeKnex.js — SQL Query Builder for Node.js
You are an expert in Knex.js, the flexible SQL query builder for Node.js that supports PostgreSQL, MySQL, SQLite, and MSSQL. You help developers write type-safe queries with a chainable API, manage database migrations and seeds, build complex joins and subqueries, and use transactions — providing direct SQL control without the overhead of a full ORM.
Core Capabilities
Query Building
import knex from "knex";
const db = knex({
client: "pg",
connection: process.env.DATABASE_URL,
pool: { min: 2, max: 20 },
});
// Select with joins
const posts = await db("posts")
.join("users", "posts.author_id", "users.id")
.select("posts.*", "users.name as author_name")
.where("posts.published", true)
.orderBy("posts.created_at", "desc")
.limit(10)
.offset(20);
// Insert
const [user] = await db("users")
.insert({ name: "Alice", email: "alice@example.com", role: "user" })
.returning("*");
// Update
await db("users").where({ id: 42 }).update({ name: "Alice Updated" });
// Delete
await db("users").where({ id: 42 }).del();
// Aggregation
const stats = await db("orders")
.select(db.raw("DATE_TRUNC('month', created_at) as month"))
.sum("amount as total")
.count("* as count")
.groupByRaw("DATE_TRUNC('month', created_at)")
.orderBy("month", "desc");
// Subquery
const activeUsers = await db("users")
.whereIn("id", db("posts").select("author_id").where("created_at", ">", thirtyDaysAgo))
.select("*");
// Transaction
await db.transaction(async (trx) => {
const [order] = await trx("orders").insert({ user_id: 1, total: 99.99 }).returning("*");
await trx("order_items").insert(items.map(i => ({ ...i, order_id: order.id })));
await trx("users").where({ id: 1 }).decrement("balance", 99.99);
});
// Raw SQL when needed
const result = await db.raw(`
SELECT u.*, COUNT(p.id) as post_count
FROM users u LEFT JOIN posts p ON u.id = p.author_id
WHERE u.created_at > ?
GROUP BY u.id
HAVING COUNT(p.id) > ?
`, [startDate, minPosts]);
Migrations
npx knex migrate:make create_users_table
npx knex migrate:latest
npx knex migrate:rollback
npx knex seed:make seed_users
npx knex seed:run
// migrations/20260101_create_users.ts
export async function up(knex) {
await knex.schema.createTable("users", (t) => {
t.increments("id").primary();
t.string("name", 100).notNullable();
t.string("email").notNullable().unique();
t.enum("role", ["user", "admin"]).defaultTo("user");
t.jsonb("profile").defaultTo("{}");
t.timestamps(true, true);
});
await knex.schema.createTable("posts", (t) => {
t.increments("id").primary();
t.string("title").notNullable();
t.text("body").notNullable();
t.boolean("published").defaultTo(false);
t.integer("author_id").unsigned().references("id").inTable("users").onDelete("CASCADE");
t.timestamps(true, true);
t.index(["author_id", "published"]);
});
}
export async function down(knex) {
await knex.schema.dropTable("posts");
await knex.schema.dropTable("users");
}
Installation
npm install knex pg # PostgreSQL
Best Practices
- Knex over raw SQL — Use the query builder for parameterized queries (prevents SQL injection); fall back to
knex.raw()for complex cases - Migrations for schema — Never modify schema manually; use migrations for reproducible, version-controlled changes
- Transactions for consistency — Wrap multi-table operations in
db.transaction(); auto-rollback on error - Connection pooling — Set pool
min/maxbased on expected concurrency and database connection limits - Seeds for test data — Create seed files for development/testing; separate from migrations
- Returning for inserts — Use
.returning("*")on PostgreSQL to get inserted rows without a second query - Knex + TypeScript — Use generic types:
db<User>("users")for type-safe select results - Knex as foundation — Knex powers Objection.js and Bookshelf; learn Knex first, add ORM features as needed
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 Knex.js 从基础查询到高级事务的完整使用指南
- 覆盖 PostgreSQL、MySQL、SQLite、MSSQL 多数据库支持
- 包含实际工程场景的端到端代码示例
Highlights
- 触发词精准覆盖 Knex.js 核心功能点
- description 位置正确且内容完整
- 边界清晰,专注查询构建器领域
Highlights
- 结构清晰,分章节组织内容
- frontmatter 完整,包含必要元数据
- 代码示例丰富且格式规范
Highlights
- 工具来源明确,符合官方最佳实践
- 参数使用正确,预防 SQL 注入
- 事务处理展示错误恢复机制
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 95, 96, 97, 98, 99
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.