Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

database-design数据库设计

Agent Skill

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

总安装

682

周安装

29

GitHub Stars

16

下载量

239
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

请帮我安装这个 Agent Skill:database-design(数据库设计)
来源仓库:https://github.com/krzysztofsurdy/code-virtuoso
仓库路径:skills/database-design
安装命令:
npx skills add https://github.com/krzysztofsurdy/code-virtuoso --skill database-design
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/krzysztofsurdy/code-virtuoso --skill database-design

简介

database-design 用于辅助数据库表结构、查询语句和迁移脚本编写,适合分析 schema 和排查查询问题。

  • 适用于数据库设计和 SQL 优化场景。
  • 通过 npx skills add 命令从 GitHub 仓库安装并使用该技能。
  • 使用时需明确数据库类型,涉及写入操作时应优先备份保护。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Database Design

Good database design determines the long-term maintainability, performance, and correctness of any data-driven application. Schema decisions made early are expensive to reverse later. Every table, column, index, and constraint should exist for a reason backed by access patterns and business rules.

Data Modeling Principles

Start from Access Patterns

Design tables around how the application reads and writes data, not around how entities look in a domain model. Two questions drive every schema decision:

  1. What queries will run most frequently? -- these determine table structure, indexes, and denormalization choices
  2. What consistency guarantees does the data need? -- these determine normalization level, constraints, and transaction boundaries

Entity Relationships

RelationshipImplementationWhen to Use
One-to-oneForeign key with UNIQUE constraint on the child tableSplitting rarely-accessed columns into a separate table, or enforcing exactly-one semantics
One-to-manyForeign key on the child table referencing the parentOrders to order items, users to addresses
Many-to-manyJoin table with composite primary keyTags to articles, students to courses
Many-to-many with attributesJoin table with its own columns beyond the two foreign keysEnrollment with grade, membership with role
Self-referentialForeign key referencing the same tableOrg charts, category trees, threaded comments

Naming Conventions

Consistent naming prevents confusion across teams and tools:

  • Tables: plural nouns in snake_case (order_items, user_addresses)
  • Columns: singular snake_case describing the value (created_at, total_amount)
  • Foreign keys: <referenced_table_singular>_id (user_id, order_id)
  • Indexes: idx_<table>_<columns> (idx_orders_user_id_created_at)
  • Constraints: chk_<table>_<rule>, uq_<table>_<columns>, fk_<table>_<referenced>

Normalization vs Denormalization

Normal Forms

FormRuleViolation Example
1NFEvery column holds atomic values; no repeating groupsStoring comma-separated tags in a single column
2NFEvery non-key column depends on the entire primary keyIn a composite-key table, a column depending on only part of the key
3NFNo non-key column depends on another non-key columnStoring both city and zip_code when zip determines city
BCNFEvery determinant is a candidate keyA scheduling table where room determines building but room is not a key

When to Denormalize

Normalization prevents anomalies but adds JOINs. Denormalize selectively when:

  • Read-heavy workloads dominate and JOIN cost is measurable in profiling
  • Reporting tables need pre-aggregated data that would otherwise require expensive queries
  • Caching a computed value avoids recalculating on every read (e.g., order_total stored on the order row)
  • Document-oriented access retrieves an entire aggregate in one read

Rules for safe denormalization:

  1. Always keep the normalized source of truth -- denormalized data is a derived cache
  2. Define how and when the denormalized copy is updated (trigger, application event, batch job)
  3. Monitor for drift between the source and the copy
  4. Document why the denormalization exists and what access pattern it serves

Choosing a Database Type

TypeStrengthsFits When
Relational (PostgreSQL, MySQL)ACID transactions, complex queries, mature tooling, JOINsStructured data with relationships, transactional workloads, most CRUD applications
Document (MongoDB, DynamoDB)Flexible schema, nested data, horizontal scalingAggregates accessed as a unit, rapidly evolving schemas, per-tenant isolation
Key-value (Redis, Memcached)Sub-millisecond reads, simple data modelSession storage, caching, counters, rate limiting
Column-family (Cassandra, ScyllaDB)High write throughput, wide rows, linear scalingTime-series, IoT telemetry, append-heavy workloads
Graph (Neo4j, Neptune)Traversal queries, relationship-centric dataSocial networks, recommendation engines, fraud detection
Time-series (TimescaleDB, InfluxDB)Optimized for time-stamped data, automatic partitioningMetrics, monitoring, financial tick data

Polyglot persistence -- using different databases for different parts of the same system -- is valid when access patterns genuinely differ. It is not valid as a way to avoid learning one database well.


Indexing Fundamentals

Indexes accelerate reads at the cost of slower writes and additional storage. Every index must justify its existence through query patterns.

Index Types

TypeStructureBest For
B-treeBalanced tree, sorted dataEquality and range queries, ORDER BY, most general-purpose indexing
HashHash tableExact equality lookups only; no range support
GiSTGeneralized search treeSpatial data, geometric queries, range types, nearest-neighbor
GINGeneralized inverted indexFull-text search, JSONB containment, array membership
BRINBlock range indexLarge tables with naturally ordered data (timestamps, sequential IDs)

Composite Index Design

The order of columns in a composite index matters. The leftmost prefix rule means a composite index on (a, b, c) supports queries filtering on (a), (a, b), or (a, b, c), but not (b, c) alone.

Column ordering guidelines:

  1. Equality conditions first -- columns compared with =
  2. Range conditions last -- columns compared with >, <, BETWEEN
  3. Most selective column first among equals

Covering and Partial Indexes

  • Covering index: includes all columns the query needs, so the database reads only the index. Use INCLUDE (PostgreSQL) or just add columns to the index key.
  • Partial index: indexes only rows matching a condition, reducing size and write overhead. Ideal for querying a small subset of a large table (e.g., WHERE status = 'pending').

See Indexing Strategies Reference for detailed index types, EXPLAIN analysis, and anti-patterns.


Schema Evolution

Schema changes are inevitable. The question is whether they break running applications.

Backward-Compatible Changes (Safe)

  • Adding a new nullable column
  • Adding a new table
  • Adding a new index (may lock briefly on some engines)
  • Widening a column type (e.g., VARCHAR(50) to VARCHAR(100))

Breaking Changes (Require Migration Strategy)

  • Renaming or removing a column
  • Changing a column type in incompatible ways
  • Adding a NOT NULL constraint to an existing column with null data
  • Splitting or merging tables

The Expand-Contract Pattern

For breaking changes in production with zero downtime:

  1. Expand -- add the new structure alongside the old one
  2. Migrate -- backfill data from old to new, dual-write during transition
  3. Switch -- update application code to use the new structure
  4. Contract -- remove the old structure once nothing references it

See Migration Patterns Reference for zero-downtime strategies, rollback techniques, and multi-tool examples.


Partitioning and Sharding

Table Partitioning (Single Database)

StrategyHow It WorksUse Case
RangeRows split by value ranges (e.g., by month)Time-series data, log tables, archival
ListRows split by discrete values (e.g., by region)Multi-tenant data, geographic segmentation
HashRows distributed by hash of a columnEven distribution when no natural range exists

Sharding (Multiple Databases)

Sharding distributes data across separate database instances. Use it only after single-instance optimizations (indexing, caching, read replicas) are exhausted.

Shard key selection criteria:

  • High cardinality -- many distinct values to distribute evenly
  • Present in most queries -- avoids scatter-gather across all shards
  • Stable -- values that do not change after creation
  • Avoid hotspots -- do not shard by a value that concentrates writes (e.g., current date)

Quick Reference: Common Design Mistakes

MistakeConsequenceFix
No foreign key constraintsOrphaned rows, inconsistent dataAlways define foreign keys unless there is a documented reason not to
Over-indexingSlow writes, wasted storageIndex only columns used in WHERE, JOIN, ORDER BY of actual queries
Storing computed values without a refresh strategyStale data, silent bugsDefine update triggers, events, or batch jobs alongside any denormalization
Using ENUM types for values that changeSchema migration for every new valueUse a lookup table with a foreign key instead
Storing money as floating-pointRounding errorsUse DECIMAL/NUMERIC or store as integer cents
Missing created_at / updated_at timestampsNo auditability, difficult debuggingAdd timestamp columns to every table by default
Generic type + type_id polymorphism everywhereNo referential integrity, complex queriesEvaluate STI, CTI, or separate tables first

Reference Files

ReferenceContents
Modeling PatternsPolymorphic associations (STI/CTI/TPT), soft deletes, audit trails, temporal data, self-referential trees, JSON columns
Indexing StrategiesB-tree/hash/GiST/GIN details, composite index design, covering and partial indexes, EXPLAIN analysis, anti-patterns
Migration PatternsVersion-based vs state-based migrations, expand-contract, data migrations, rollback strategies, multi-tool examples

Integration with Other Skills

SituationRecommended Skill
Optimizing query performance and cachingInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for performance optimization patterns
Designing domain models and aggregatesInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for clean architecture and DDD guidance
Building APIs that expose database-backed resourcesInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for API design principles
Testing database interactionsInstall knowledge-virtuoso from krzysztofsurdy/code-virtuoso for testing strategies

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

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

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

平台分布

Codex

35.02%
按下载量换算84

Claude

31.18%
按下载量换算75

Cursor

19.1%
按下载量换算46

Gemini CLI

10.36%
按下载量换算25

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills