database-patterns
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "database-patterns":https://skillpi.com/zh/skills/deepskill-4ceb6b59468445524f428745ecb9b05c438df01cdd0348b198e6a4fe091d178f。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
数据库模式设计与查询优化工具,涵盖规范化、索引、N+1 问题、事务与 EXPLAIN。触发主题包括触发器、模式、索引、慢查询、N+1 问题、PostgreSQL、MySQL、EXPLAIN、死锁与查询计划。
介绍来源: third_party · softspark · 0.0.1 参考来源
SkillPi 解读
- 能完成的任务
- 翻译待完成,请参阅来源文档。
- 软件、账号及付费要求
- 翻译待完成,请参阅来源文档。
- 实测状态
- 未测试
文件浏览
Frontmatter
name: database-patterns
description: "DB schema design and query tuning: normalization, indexing, N+1, transactions, EXPLAIN. Triggers: schema, index, slow query, N+1, PostgreSQL, MySQL, EXPLAIN, deadlock, query plan."
effort: medium
user-invocable: false
allowed-tools: ReadDatabase Patterns Skill
ORM Selection
| Scenario | ORM |
|---|---|
| Node.js, type-safe | Prisma |
| Node.js, SQL-first | Drizzle |
| Python, async | SQLAlchemy 2.0 |
| Python, simple | SQLModel |
| PHP | Doctrine, Eloquent |
Schema Design
Naming Conventions
-- Tables: plural, snake_case
CREATE TABLE user_profiles (...);
-- Columns: snake_case
user_id, created_at, is_active
-- Indexes: idx_{table}_{columns}
CREATE INDEX idx_users_email ON users(email);
-- Foreign keys: fk_{table}_{ref_table}
CONSTRAINT fk_orders_users FOREIGN KEY (user_id) REFERENCES users(id)
Common Patterns
Soft Delete
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL;
-- Query active records
SELECT * FROM users WHERE deleted_at IS NULL;
Audit Columns
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created_by UUID REFERENCES users(id),
updated_by UUID REFERENCES users(id)
UUID vs Serial
| Use Case | Type |
|---|---|
| Internal only | SERIAL/BIGSERIAL |
| External/distributed | UUID |
| Human readable | SERIAL with prefix |
Index Strategies
When to Index
- Foreign keys (always)
- Columns in WHERE clauses
- Columns in ORDER BY
- Columns in JOIN conditions
Index Types
| Type | Use Case |
|---|---|
| B-tree | Equality, range (default) |
| Hash | Equality only |
| GIN | Arrays, JSONB, full-text |
| GiST | Geometric, full-text |
| BRIN | Large sequential data |
Composite Index Order
-- Good: matches query pattern
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
SELECT * FROM orders WHERE user_id = 1 AND created_at > '2024-01-01';
-- Index used for:
-- WHERE user_id = 1
-- WHERE user_id = 1 AND created_at > ...
-- Index NOT used for:
-- WHERE created_at > '2024-01-01' (missing leading column)
Query Optimization
Explain Analyze
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = 'test@example.com';
Common Issues
| Issue | Solution |
|---|---|
| Seq Scan on large table | Add index |
| High row estimate | Update statistics |
| Nested Loop on large sets | Consider hash join |
| Sort in memory | Increase work_mem |
N+1 Prevention
# Bad: N+1
for user in users:
print(user.orders) # Query per user
# Good: Eager loading
users = User.query.options(joinedload(User.orders)).all()
Migration Best Practices
Safe Migrations
-- Add column (safe)
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
-- Add NOT NULL column (safe pattern)
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
UPDATE users SET phone = '' WHERE phone IS NULL;
ALTER TABLE users ALTER COLUMN phone SET NOT NULL;
-- Rename column (use application-level)
-- 1. Add new column
-- 2. Copy data
-- 3. Update application
-- 4. Remove old column
Migration Checklist
- [ ] Tested on production-like data
- [ ] Rollback script ready
- [ ] No long locks on large tables
- [ ] Indexes created concurrently
- [ ] Application handles both states
Connection Pooling
PgBouncer Settings
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
Application Settings
| Framework | Pool Size Formula |
|---|---|
| General | (cores * 2) + disk spindles |
| Read-heavy | cores * 4 |
| Write-heavy | cores * 2 |
Vector Database (Qdrant) Patterns
Client Setup
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct
# Sync client
client = QdrantClient(host="localhost", port=6333)
# Async client
from qdrant_client import AsyncQdrantClient
async_client = AsyncQdrantClient(host="localhost", port=6333)
Collection Management
# Create collection (single vector)
client.create_collection(
collection_name="documents",
vectors_config=VectorParams(size=384, distance=Distance.COSINE)
)
# Create collection (multi-vector)
from qdrant_client.models import VectorParams
client.create_collection(
collection_name="multimodal",
vectors_config={
"text": VectorParams(size=384, distance=Distance.COSINE),
"image": VectorParams(size=512, distance=Distance.EUCLID),
}
)
Upserting Vectors
# Single upsert
client.upsert(
collection_name="documents",
points=[
PointStruct(
id=1,
vector=[0.1, 0.2, 0.3, ...], # 384-dim vector
payload={"title": "Doc 1", "category": "tech"}
)
]
)
# Batch upsert
points = [
PointStruct(id=i, vector=vectors[i], payload=payloads[i])
for i in range(len(vectors))
]
client.upsert(collection_name="documents", points=points, batch_size=100)
Searching Vectors
from qdrant_client.models import Filter, FieldCondition, MatchValue
# Basic search
results = client.search(
collection_name="documents",
query_vector=[0.1, 0.2, ...],
limit=10
)
# Search with filter
results = client.search(
collection_name="documents",
query_vector=[0.1, 0.2, ...],
query_filter=Filter(
must=[
FieldCondition(key="category", match=MatchValue(value="tech"))
]
),
limit=10,
with_payload=True,
score_threshold=0.7
)
# Search with range filter
from qdrant_client.models import Range
results = client.search(
collection_name="documents",
query_vector=query_vector,
query_filter=Filter(
must=[
FieldCondition(key="price", range=Range(gte=10, lte=100))
]
),
limit=10
)
Payload Indexing
# Create payload index for faster filtering
client.create_payload_index(
collection_name="documents",
field_name="category",
field_schema="keyword" # or "integer", "float", "bool"
)
Best Practices
| Aspect | Recommendation |
|---|---|
| Batch Size | 100-1000 points per upsert |
| Vector Dim | Match your embedding model (384, 768, 1536) |
| Filters | Index frequently filtered fields |
| Distance | COSINE for normalized, EUCLID for raw |
| Sharding | Use for >1M vectors |
Distance Metrics
| Metric | Best For | Normalized |
|---|---|---|
| COSINE | Text embeddings | Yes |
| EUCLID | Image embeddings | No |
| DOT | When vectors pre-normalized | Yes |
Common Rationalizations
| Excuse | Why It's Wrong |
|---|---|
| "We'll add indexes later when it's slow" | Missing indexes on production tables cause outages, not slowdowns — index from design |
| "The ORM handles performance" | ORMs generate queries, they don't optimize them — always check the query plan |
| "NoSQL is faster" | NoSQL trades consistency for speed — if you need joins, use a relational DB |
| "We don't need migrations, we'll update the schema directly" | Direct schema changes are irreversible and untestable — migrations are the safety net |
| "One big table is simpler" | Denormalization without measurement creates update anomalies — normalize first, denormalize with data |
Rules
- MUST profile queries with
EXPLAIN (ANALYZE, BUFFERS)before adding an index — indexes chosen by intuition miss the real hot path half the time - MUST design the schema around the dominant access pattern, not the logical entity graph — storage follows queries, not the other way round
- NEVER write to production with raw SQL when a migration file fits — ad-hoc changes break rollback and audit
- NEVER add a
SELECT *in a loop — N+1 is the most common performance regression in code review - CRITICAL: every foreign key has an index on the referencing column. Postgres does not create one automatically, and
ON DELETE CASCADEwithout the index causes full-table scans on delete. - MANDATORY: numeric IDs use
bigint(orbigserial) in new tables unless there is a stated reason to cap at 2^31. Integer overflow on a growing table is a late, painful surprise.
Gotchas
EXPLAINwithoutANALYZEshows the planner's estimate, not the actual execution. A query plan that "looks good" withEXPLAINcan still be slow in practice — always useANALYZEfor real diagnosis.- ORM-generated queries often look efficient in one row but emit N+1 at scale.
prisma,sequelize,activerecordall have "eager loading" switches that must be explicit — the default is lazy and bites under load. - Postgres transactions hold row locks until commit or rollback. A long-running transaction that reads rows another writer needs blocks progress silently. Investigate
pg_stat_activityforstate=idle in transactionwhen writes stall. - Index-only scans require both the query columns AND the filter to be in the index (or in the visibility map for heap tuples). Adding a single column to
WHEREcan demote an index-only scan to an index scan with a 10× slowdown. - MySQL implicit collation on JOIN across tables with different
utf8mb4collations forces a row-by-row collation conversion — a 100× slowdown that shows as a full scan in the plan. Align collations during schema design.
When NOT to Load
- For schema evolution (zero-downtime, expand-contract, backfill) — use
/migration-patterns - For running migrations as a task — use
/migrate - For query-plan profiling and the four golden signals — use
/performance-profiling - For vector/embedding-specific schema — this skill covers the mechanics; use
/rag-patternsfor retrieval design - For observability of DB metrics (slow query log, connection pool saturation) — use
/observability-patterns
版本历史
-
v6.2.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
原版更新说明
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
原版更新说明
## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0
-
v5.5.0
GitHub ↗
原版更新说明
### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0
-
v5.4.2
GitHub ↗
原版更新说明
## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2
此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗
当前收录版本
0.0.1
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 覆盖数据库模式设计与查询优化的核心主题,包括规范化、索引、N+1问题、事务、EXPLAIN等,内容深入且实用
- 提供ORM选择指南、命名约定、软删除、审计列、UUID vs Serial等常见模式,具有广泛受众的实用能力
- 包含向量数据库(Qdrant)模式,涵盖客户端设置、集合管理、向量插入与搜索、负载索引等,满足现代应用场景
亮点
- 触发词精准完整,覆盖多种变体如PostgreSQL、MySQL、EXPLAIN、死锁、查询计划等,边界清晰
- description中明确列出关键触发词,便于用户快速识别适用场景
亮点
- Phase/步骤清晰,有出口条件,含端到端示例,frontmatter完整,单文件≤500行
- 结构良好,包含ORM选择、模式设计、索引策略、查询优化、迁移最佳实践、连接池、向量数据库等多个章节,逻辑清晰
亮点
- 工具来源明确,参数正确,覆盖主要异常,不可逆操作有确认机制
- 提供详细的SQL示例、Python代码片段、PgBouncer设置等,确保执行可靠性
- 包含常见合理化解释、规则和陷阱,帮助用户避免常见错误
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
翻译待完成,请参阅来源文档。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。