knex

Knex.js 专家:一个灵活的 Node.js SQL 查询构建器,支持 PostgreSQL、MySQL、SQLite 和 MSSQL。帮助使用链式 API 编写类型安全的查询、管理数据库迁移与种子数据、构建复杂连接和子查询,并使用事务来获得直接的 SQL 控制,而无需完整 ORM 的开销。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "knex":https://skillpi.com/zh/skills/deepskill-8eebc89fef83186a49f14c97cf8464c6df2ae4122e35c1b304b8e344ba4c94c7。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Knex.js 专家:一个灵活的 Node.js SQL 查询构建器,支持 PostgreSQL、MySQL、SQLite 和 MSSQL。帮助使用链式 API 编写类型安全的查询、管理数据库迁移与种子数据、构建复杂连接和子查询,并使用事务来获得直接的 SQL 控制,而无需完整 ORM 的开销。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
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
    - node

Knex.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

  1. Knex over raw SQL — Use the query builder for parameterized queries (prevents SQL injection); fall back to knex.raw() for complex cases
  2. Migrations for schema — Never modify schema manually; use migrations for reproducible, version-controlled changes
  3. Transactions for consistency — Wrap multi-table operations in db.transaction(); auto-rollback on error
  4. Connection pooling — Set pool min/max based on expected concurrency and database connection limits
  5. Seeds for test data — Create seed files for development/testing; separate from migrations
  6. Returning for inserts — Use .returning("*") on PostgreSQL to get inserted rows without a second query
  7. Knex + TypeScript — Use generic types: db<User>("users") for type-safe select results
  8. Knex as foundation — Knex powers Objection.js and Bookshelf; learn Knex first, add ORM features as needed

当前收录版本

1.0.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供 Knex.js 从基础查询到高级事务的完整使用指南
  • 覆盖 PostgreSQL、MySQL、SQLite、MSSQL 多数据库支持
  • 包含实际工程场景的端到端代码示例
触发精准90/100

亮点

  • 触发词精准覆盖 Knex.js 核心功能点
  • description 位置正确且内容完整
  • 边界清晰,专注查询构建器领域
结构规范95/100

亮点

  • 结构清晰,分章节组织内容
  • frontmatter 完整,包含必要元数据
  • 代码示例丰富且格式规范
执行可靠90/100

亮点

  • 工具来源明确,符合官方最佳实践
  • 参数使用正确,预防 SQL 注入
  • 事务处理展示错误恢复机制
证据可验 (前四项均值)90/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。