[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-af5da312-5ad7-4294-8e01-7f6208a26fc2":3,"$fqzqUw2IrrbRVd8_cA1eQKbSx8x7sU3bYKf2dvslZ64w":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"af5da312-5ad7-4294-8e01-7f6208a26fc2","database-designer","使用时，当用户请求设计数据库模式、规划数据迁移、优化查询、在SQL和NoSQL之间选择或建模数据关系时。","cat_coding_backend","mod_coding","alirezarezvani,coding","---\nname: \"database-designer\"\ndescription: \"Use when the user asks to design database schemas, plan data migrations, optimize queries, choose between SQL and NoSQL, or model data relationships.\"\n---\n\n# Database Designer - POWERFUL Tier Skill\n\n## Overview\n\nA comprehensive database design skill that provides expert-level analysis, optimization, and migration capabilities for modern database systems. This skill combines theoretical principles with practical tools to help architects and developers create scalable, performant, and maintainable database schemas.\n\n## Core Competencies\n\n### Schema Design & Analysis\n- **Normalization Analysis**: Automated detection of normalization levels (1NF through BCNF)\n- **Denormalization Strategy**: Smart recommendations for performance optimization\n- **Data Type Optimization**: Identification of inappropriate types and size issues\n- **Constraint Analysis**: Missing foreign keys, unique constraints, and null checks\n- **Naming Convention Validation**: Consistent table and column naming patterns\n- **ERD Generation**: Automatic Mermaid diagram creation from DDL\n\n### Index Optimization\n- **Index Gap Analysis**: Identification of missing indexes on foreign keys and query patterns\n- **Composite Index Strategy**: Optimal column ordering for multi-column indexes\n- **Index Redundancy Detection**: Elimination of overlapping and unused indexes\n- **Performance Impact Modeling**: Selectivity estimation and query cost analysis\n- **Index Type Selection**: B-tree, hash, partial, covering, and specialized indexes\n\n### Migration Management\n- **Zero-Downtime Migrations**: Expand-contract pattern implementation\n- **Schema Evolution**: Safe column additions, deletions, and type changes\n- **Data Migration Scripts**: Automated data transformation and validation\n- **Rollback Strategy**: Complete reversal capabilities with validation\n- **Execution Planning**: Ordered migration steps with dependency resolution\n\n## Database Design Principles\n→ See references\u002Fdatabase-design-reference.md for details\n\n## Best Practices\n\n### Schema Design\n1. **Use meaningful names**: Clear, consistent naming conventions\n2. **Choose appropriate data types**: Right-sized columns for storage efficiency\n3. **Define proper constraints**: Foreign keys, check constraints, unique indexes\n4. **Consider future growth**: Plan for scale from the beginning\n5. **Document relationships**: Clear foreign key relationships and business rules\n\n### Performance Optimization\n1. **Index strategically**: Cover common query patterns without over-indexing\n2. **Monitor query performance**: Regular analysis of slow queries\n3. **Partition large tables**: Improve query performance and maintenance\n4. **Use appropriate isolation levels**: Balance consistency with performance\n5. **Implement connection pooling**: Efficient resource utilization\n\n### Security Considerations\n1. **Principle of least privilege**: Grant minimal necessary permissions\n2. **Encrypt sensitive data**: At rest and in transit\n3. **Audit access patterns**: Monitor and log database access\n4. **Validate inputs**: Prevent SQL injection attacks\n5. **Regular security updates**: Keep database software current\n\n## Query Generation Patterns\n\n### SELECT with JOINs\n\n```sql\n-- INNER JOIN: only matching rows\nSELECT o.id, c.name, o.total\nFROM orders o\nINNER JOIN customers c ON c.id = o.customer_id;\n\n-- LEFT JOIN: all left rows, NULLs for non-matches\nSELECT c.name, COUNT(o.id) AS order_count\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.id\nGROUP BY c.name;\n\n-- Self-join: hierarchical data (employees\u002Fmanagers)\nSELECT e.name AS employee, m.name AS manager\nFROM employees e\nLEFT JOIN employees m ON m.id = e.manager_id;\n```\n\n### Common Table Expressions (CTEs)\n\n```sql\n-- Recursive CTE for org chart\nWITH RECURSIVE org AS (\n  SELECT id, name, manager_id, 1 AS depth\n  FROM employees WHERE manager_id IS NULL\n  UNION ALL\n  SELECT e.id, e.name, e.manager_id, o.depth + 1\n  FROM employees e INNER JOIN org o ON o.id = e.manager_id\n)\nSELECT * FROM org ORDER BY depth, name;\n```\n\n### Window Functions\n\n```sql\n-- ROW_NUMBER for pagination \u002F dedup\nSELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn\nFROM orders;\n\n-- RANK with gaps, DENSE_RANK without gaps\nSELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM leaderboard;\n\n-- LAG\u002FLEAD for comparing adjacent rows\nSELECT date, revenue,\n  revenue - LAG(revenue) OVER (ORDER BY date) AS daily_change\nFROM daily_sales;\n```\n\n### Aggregation Patterns\n\n```sql\n-- FILTER clause (PostgreSQL) for conditional aggregation\nSELECT\n  COUNT(*) AS total,\n  COUNT(*) FILTER (WHERE status = 'active') AS active,\n  AVG(amount) FILTER (WHERE amount > 0) AS avg_positive\nFROM accounts;\n\n-- GROUPING SETS for multi-level rollups\nSELECT region, product, SUM(revenue)\nFROM sales\nGROUP BY GROUPING SETS ((region, product), (region), ());\n```\n\n---\n\n## Migration Patterns\n\n### Up\u002FDown Migration Scripts\n\nEvery migration must have a reversible counterpart. Name files with a timestamp prefix for ordering:\n\n```\nmigrations\u002F\n├── 20260101_000001_create_users.up.sql\n├── 20260101_000001_create_users.down.sql\n├── 20260115_000002_add_users_email_index.up.sql\n└── 20260115_000002_add_users_email_index.down.sql\n```\n\n### Zero-Downtime Migrations (Expand\u002FContract)\n\nUse the expand-contract pattern to avoid locking or breaking running code:\n\n1. **Expand** — add the new column\u002Ftable (nullable, with default)\n2. **Migrate data** — backfill in batches; dual-write from application\n3. **Transition** — application reads from new column; stop writing to old\n4. **Contract** — drop old column in a follow-up migration\n\n### Data Backfill Strategies\n\n```sql\n-- Batch update to avoid long-running locks\nUPDATE users SET email_normalized = LOWER(email)\nWHERE id IN (SELECT id FROM users WHERE email_normalized IS NULL LIMIT 5000);\n-- Repeat in a loop until 0 rows affected\n```\n\n### Rollback Procedures\n\n- Always test the `down.sql` in staging before deploying `up.sql` to production\n- Keep rollback window short — if the contract step has run, rollback requires a new forward migration\n- For irreversible changes (dropping columns with data), take a logical backup first\n\n---\n\n## Performance Optimization\n\n### Indexing Strategies\n\n| Index Type | Use Case | Example |\n|------------|----------|---------|\n| **B-tree** (default) | Equality, range, ORDER BY | `CREATE INDEX idx_users_email ON users(email);` |\n| **GIN** | Full-text search, JSONB, arrays | `CREATE INDEX idx_docs_body ON docs USING gin(to_tsvector('english', body));` |\n| **GiST** | Geometry, range types, nearest-neighbor | `CREATE INDEX idx_locations ON places USING gist(coords);` |\n| **Partial** | Subset of rows (reduce size) | `CREATE INDEX idx_active ON users(email) WHERE active = true;` |\n| **Covering** | Index-only scans | `CREATE INDEX idx_cov ON orders(customer_id) INCLUDE (total, created_at);` |\n\n### EXPLAIN Plan Reading\n\n```sql\nEXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;\n```\n\nKey signals to watch:\n- **Seq Scan** on large tables — missing index\n- **Nested Loop** with high row estimates — consider hash\u002Fmerge join or add index\n- **Buffers shared read** much higher than **hit** — working set exceeds memory\n\n### N+1 Query Detection\n\nSymptoms: application issues one query per row (e.g., fetching related records in a loop).\n\nFixes:\n- Use `JOIN` or subquery to fetch in one round-trip\n- ORM eager loading (`select_related` \u002F `includes` \u002F `with`)\n- DataLoader pattern for GraphQL resolvers\n\n### Connection Pooling\n\n| Tool | Protocol | Best For |\n|------|----------|----------|\n| **PgBouncer** | PostgreSQL | Transaction\u002Fstatement pooling, low overhead |\n| **ProxySQL** | MySQL | Query routing, read\u002Fwrite splitting |\n| **Built-in pool** (HikariCP, SQLAlchemy pool) | Any | Application-level pooling |\n\n**Rule of thumb:** Set pool size to `(2 * CPU cores) + disk spindles`. For cloud SSDs, start with `2 * vCPUs` and tune.\n\n### Read Replicas and Query Routing\n\n- Route all `SELECT` queries to replicas; writes to primary\n- Account for replication lag (typically \u003C1s for async, 0 for sync)\n- Use `pg_last_wal_replay_lsn()` to detect lag before reading critical data\n\n---\n\n## Multi-Database Decision Matrix\n\n| Criteria | PostgreSQL | MySQL | SQLite | SQL Server |\n|----------|-----------|-------|--------|------------|\n| **Best for** | Complex queries, JSONB, extensions | Web apps, read-heavy workloads | Embedded, dev\u002Ftest, edge | Enterprise .NET stacks |\n| **JSON support** | Excellent (JSONB + GIN) | Good (JSON type) | Minimal | Good (OPENJSON) |\n| **Replication** | Streaming, logical | Group replication, InnoDB cluster | N\u002FA | Always On AG |\n| **Licensing** | Open source (PostgreSQL License) | Open source (GPL) \u002F commercial | Public domain | Commercial |\n| **Max practical size** | Multi-TB | Multi-TB | ~1 TB (single-writer) | Multi-TB |\n\n**When to choose:**\n- **PostgreSQL** — default choice for new projects; best extensibility and standards compliance\n- **MySQL** — existing MySQL ecosystem; simple read-heavy web applications\n- **SQLite** — mobile apps, CLI tools, unit test databases, IoT\u002Fedge\n- **SQL Server** — mandated by enterprise policy; deep .NET\u002FAzure integration\n\n### NoSQL Considerations\n\n| Database | Model | Use When |\n|----------|-------|----------|\n| **MongoDB** | Document | Schema flexibility, rapid prototyping, content management |\n| **Redis** | Key-value \u002F cache | Session store, rate limiting, leaderboards, pub\u002Fsub |\n| **DynamoDB** | Wide-column | Serverless AWS apps, single-digit-ms latency at any scale |\n\n> Use SQL as default. Reach for NoSQL only when the access pattern clearly benefits from it.\n\n---\n\n## Sharding & Replication\n\n### Horizontal vs Vertical Partitioning\n\n- **Vertical partitioning**: Split columns across tables (e.g., separate BLOB columns). Reduces I\u002FO for narrow queries.\n- **Horizontal partitioning (sharding)**: Split rows across databases\u002Fservers. Required when a single node cannot hold the dataset or handle the throughput.\n\n### Sharding Strategies\n\n| Strategy | How It Works | Pros | Cons |\n|----------|-------------|------|------|\n| **Hash** | `shard = hash(key) % N` | Even distribution | Resharding is expensive |\n| **Range** | Shard by date or ID range | Simple, good for time-series | Hot spots on latest shard |\n| **Geographic** | Shard by user region | Data locality, compliance | Cross-region queries are hard |\n\n### Replication Patterns\n\n| Pattern | Consistency | Latency | Use Case |\n|---------|------------|---------|----------|\n| **Synchronous** | Strong | Higher write latency | Financial transactions |\n| **Asynchronous** | Eventual | Low write latency | Read-heavy web apps |\n| **Semi-synchronous** | At-least-one replica confirmed | Moderate | Balance of safety and speed |\n\n---\n\n## Cross-References\n\n- **sql-database-assistant** — query writing, optimization, and debugging for day-to-day SQL work\n- **database-schema-designer** — ERD modeling, normalization analysis, and schema generation\n- **migration-architect** — large-scale migration planning across database engines or major schema overhauls\n- **senior-backend** — application-layer patterns (connection pooling, ORM best practices)\n- **senior-devops** — infrastructure provisioning for database clusters and replicas\n\n---\n\n## Conclusion\n\nEffective database design requires balancing multiple competing concerns: performance, scalability, maintainability, and business requirements. This skill provides the tools and knowledge to make informed decisions throughout the database lifecycle, from initial schema design through production optimization and evolution.\n\nThe included tools automate common analysis and optimization tasks, while the comprehensive guides provide the theoretical foundation for making sound architectural decisions. Whether building a new system or optimizing an existing one, these resources provide expert-level guidance for creating robust, scalable database solutions.\n","","imported","https:\u002F\u002Fgithub.com\u002Falirezarezvani\u002Fclaude-skills","user_system_seed","SkillOPIC",true,181,1068,"2026-05-16 13:53:33",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"ef7f53e0-a496-4752-8c94-59f68ead27dd","1.0.0","database-designer.zip",63049,"uploads\u002Fskills\u002Faf5da312-5ad7-4294-8e01-7f6208a26fc2\u002Fdatabase-designer.zip","02fa35622054e4c8d822b69bcaeaece89e6c57ea01e0106a343c1ef7c3086977","[{\"path\":\"README.md\",\"isDirectory\":false,\"size\":11966},{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":12010},{\"path\":\"assets\u002Fsample_query_patterns.json\",\"isDirectory\":false,\"size\":9244},{\"path\":\"assets\u002Fsample_schema.json\",\"isDirectory\":false,\"size\":9365},{\"path\":\"assets\u002Fsample_schema.sql\",\"isDirectory\":false,\"size\":8301},{\"path\":\"expected_outputs\u002Findex_optimization_sample.txt\",\"isDirectory\":false,\"size\":2639},{\"path\":\"expected_outputs\u002Fmigration_sample.txt\",\"isDirectory\":false,\"size\":4509},{\"path\":\"expected_outputs\u002Fschema_analysis_sample.txt\",\"isDirectory\":false,\"size\":7474},{\"path\":\"index_optimizer.py\",\"isDirectory\":false,\"size\":38896},{\"path\":\"migration_generator.py\",\"isDirectory\":false,\"size\":50373},{\"path\":\"references\u002Fdatabase-design-reference.md\",\"isDirectory\":false,\"size\":14014},{\"path\":\"references\u002Fdatabase_selection_decision_tree.md\",\"isDirectory\":false,\"size\":16344},{\"path\":\"references\u002Findex_strategy_patterns.md\",\"isDirectory\":false,\"size\":11831},{\"path\":\"references\u002Fnormalization_guide.md\",\"isDirectory\":false,\"size\":10672},{\"path\":\"schema_analyzer.py\",\"isDirectory\":false,\"size\":42034}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]