knex
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.
What this skill does
# 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
```typescript
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: "[email protected]", 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
```bash
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
```
```typescript
// 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
```bash
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
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.