Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计异常

n-plus-one-preventionn 加一预防

Agent Skill

n-plus-one-prevention 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

612

周安装

26

GitHub Stars

10

下载量

214
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:n-plus-one-prevention(n 加一预防)
来源仓库:https://github.com/yanko-belov/code-craft
仓库路径:skills/n-plus-one-prevention
安装命令:
npx skills add https://github.com/yanko-belov/code-craft --skill n-plus-one-prevention
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/yanko-belov/code-craft --skill n-plus-one-prevention

简介

n-plus-one-prevention 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。

  • 适用于数据库查询优化、API 调用管理和性能瓶颈排查场景。
  • 通过关键词搜索、来源仓库和原始 README 核验具体用法,结合安装命令使用。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

N+1 Query Prevention

Overview

Never query in a loop. Fetch related data in a single query.

N+1 is when you fetch N items, then make N more queries to get related data. It's the most common database performance killer.

When to Use

  • Fetching a list with related data
  • Loop that contains a database query
  • Slow list/index endpoints
  • Multiple queries for one API response

The Iron Rule

NEVER put a database query inside a loop.

No exceptions:

  • Not for "it's only a few items"
  • Not for "the query is fast"
  • Not for "we'll cache it"
  • Not for "it's simpler"

Detection: N+1 Pattern

If you query inside a loop, STOP:

// ❌ VIOLATION: N+1 queries
const orders = await Order.findAll();  // 1 query

const ordersWithCustomers = await Promise.all(
  orders.map(async (order) => {
    // N queries (one per order)
    const customer = await Customer.findByPk(order.customerId);
    return { ...order, customerName: customer.name };
  })
);
// Total: 1 + N queries

For 100 orders = 101 database queries!

The Correct Pattern: Eager Loading

// ✅ CORRECT: Single query with JOIN

// Sequelize
const orders = await Order.findAll({
  include: [{ model: Customer, attributes: ['name'] }]
});
// 1 query with JOIN

// Prisma
const orders = await prisma.order.findMany({
  include: { customer: { select: { name: true } } }
});

// TypeORM
const orders = await orderRepository.find({
  relations: ['customer']
});

// Raw SQL
const orders = await db.query(`
  SELECT o.*, c.name as customer_name
  FROM orders o
  JOIN customers c ON o.customer_id = c.id
`);

Common N+1 Scenarios

1. Related Entity

// ❌ N+1
posts.map(post => await User.findById(post.authorId));

// ✅ Eager load
Post.findAll({ include: [User] });

2. Aggregates

// ❌ N+1
users.map(user => await Order.count({ where: { userId: user.id } }));

// ✅ Subquery or GROUP BY
User.findAll({
  attributes: {
    include: [[sequelize.fn('COUNT', sequelize.col('orders.id')), 'orderCount']]
  },
  include: [{ model: Order, attributes: [] }],
  group: ['User.id']
});

3. Multiple Relations

// ❌ N+1 (multiple)
orders.map(order => {
  await Customer.findByPk(order.customerId);
  await Product.findAll({ where: { orderId: order.id } });
});

// ✅ Eager load all
Order.findAll({
  include: [Customer, Product]
});

Detection Tools

// Log query count per request
let queryCount = 0;
db.on('query', () => queryCount++);

app.use((req, res, next) => {
  queryCount = 0;
  res.on('finish', () => {
    if (queryCount > 10) {
      console.warn(`N+1 alert: ${req.path} made ${queryCount} queries`);
    }
  });
  next();
});

Pressure Resistance Protocol

1. "It's Only a Few Items"

Pressure: "We only have 10 orders"

Response: 10 becomes 100 becomes 10,000. Fix it now.

Action: Always use eager loading regardless of current data size.

2. "The Query Is Fast"

Pressure: "Each query takes 1ms"

Response: 1ms × 1000 = 1 second. Network overhead adds more.

Action: One 5ms query beats 1000 × 1ms queries.

3. "We'll Cache It"

Pressure: "Redis will cache the results"

Response: Cache misses still hit the DB. First requests are slow. Cache adds complexity.

Action: Fix the query. Cache if still needed.

4. "It's Simpler"

Pressure: "Looping is easier to understand"

Response: Simple code that's 100x slower isn't simple.

Action: Learn your ORM's eager loading syntax.

Red Flags - STOP and Reconsider

  • await inside .map() or .forEach()
  • Query count grows with result size
  • List endpoints slower than detail endpoints
  • "Loading..." takes forever on lists
  • ORM lazy loading by default

All of these mean: Refactor to eager loading.

Quick Reference

N+1 (Bad)Eager Loading (Good)
Loop + queryJOIN / include
1 + N queries1 query
O(N) round tripsO(1) round trips
Slower with more dataConstant query count

Common Rationalizations (All Invalid)

ExcuseReality
"Few items"Data grows. Fix now.
"Fast query"N slow > 1 medium.
"We'll cache"Cache doesn't fix bad queries.
"It's simpler"Slow isn't simple.
"ORM handles it"ORMs default to lazy loading.

The Bottom Line

One query for the list. One query for related data. Never query in a loop.

Use eager loading (include/join) to fetch related data. Watch query counts. Any query inside a loop is a bug waiting to scale.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

29.26%
按下载量换算63

Claude Code

20.4%
按下载量换算44

windsurf

16.6%
按下载量换算36

Antigravity

12.6%
按下载量换算27

trae

8.25%
按下载量换算18

OpenCode

3.25%
按下载量换算7

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。

来源信息

继续浏览同类 Skills