database-patterns

Database schema design and query-optimization tool covering normalization, indexes, N+1 issues, transactions, and EXPLAIN. Trigger topics include triggers, schemas, indexes, slow queries, N+1 problems, PostgreSQL, MySQL, EXPLAIN, deadlocks, and query plans.

Last repository push
GitHub Stars
180
Forks
21
Issues / PRs
0

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 "database-patterns" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-4ceb6b59468445524f428745ecb9b05c438df01cdd0348b198e6a4fe091d178f. Verify the upstream source and version against https://github.com/softspark/ai-toolkit 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

Database schema design and query-optimization tool covering normalization, indexes, N+1 issues, transactions, and EXPLAIN. Trigger topics include triggers, schemas, indexes, slow queries, N+1 problems, PostgreSQL, MySQL, EXPLAIN, deadlocks, and query plans.

0 Downloads

Introduction source: third_party · softspark · 0.0.1 Reference

SkillPi interpretation

Tasks
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.
Software, accounts and paid services
```python from qdrant_client import QdrantClient from qdrant_client.models import Distance, VectorParams, PointStruct
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
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: Read

Database 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 CASCADE without the index causes full-table scans on delete.
  • MANDATORY: numeric IDs use bigint (or bigserial) 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

  • EXPLAIN without ANALYZE shows the planner's estimate, not the actual execution. A query plan that "looks good" with EXPLAIN can still be slow in practice — always use ANALYZE for real diagnosis.
  • ORM-generated queries often look efficient in one row but emit N+1 at scale. prisma, sequelize, activerecord all 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_activity for state=idle in transaction when 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 WHERE can demote an index-only scan to an index scan with a 10× slowdown.
  • MySQL implicit collation on JOIN across tables with different utf8mb4 collations 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-patterns for retrieval design
  • For observability of DB metrics (slow query log, connection pool saturation) — use /observability-patterns

Version history

  1. v6.2.0 GitHub ↗
    Original release notes

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    Original release notes

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    Original release notes

    ## 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

  4. v5.5.0 GitHub ↗
    Original release notes

    ### 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

  5. v5.4.2 GitHub ↗
    Original release notes

    ## 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

Only the five most recent versions are shown. View full version history at the source ↗

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value92/100

Highlights

  • 覆盖数据库模式设计与查询优化的核心主题,包括规范化、索引、N+1问题、事务、EXPLAIN等,内容深入且实用
  • 提供ORM选择指南、命名约定、软删除、审计列、UUID vs Serial等常见模式,具有广泛受众的实用能力
  • 包含向量数据库(Qdrant)模式,涵盖客户端设置、集合管理、向量插入与搜索、负载索引等,满足现代应用场景
Trigger Precision88/100

Highlights

  • 触发词精准完整,覆盖多种变体如PostgreSQL、MySQL、EXPLAIN、死锁、查询计划等,边界清晰
  • description中明确列出关键触发词,便于用户快速识别适用场景
Structure and Standards95/100

Highlights

  • Phase/步骤清晰,有出口条件,含端到端示例,frontmatter完整,单文件≤500行
  • 结构良好,包含ORM选择、模式设计、索引策略、查询优化、迁移最佳实践、连接池、向量数据库等多个章节,逻辑清晰
Execution Reliability90/100

Highlights

  • 工具来源明确,参数正确,覆盖主要异常,不可逆操作有确认机制
  • 提供详细的SQL示例、Python代码片段、PgBouncer设置等,确保执行可靠性
  • 包含常见合理化解释、规则和陷阱,帮助用户避免常见错误
Evidence Verifiability (mean of the first four)91/100

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.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

```python from qdrant_client import QdrantClient from qdrant_client.models import Distance, VectorParams, PointStruct

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.