数据库安装
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- 安全
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 低消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部 API Key
- 不需要
- 兼容的系统
- Windows
- 底层运行要求
- Node.js · Python
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- Shell 执行
- 读取环境变量
- 网络行为
- 仅限本地
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: sql-database-patterns
description: Use this skill when the agent is designing schemas, reviewing migrations, tuning queries, modeli…
category: 安全
runtime: Node.js / Python
---
# sql-database-patterns 输出预览
## PART A: 任务判断
- 适用问题:安全审计、密钥扫描、权限检查或风险分析。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“When to Use / When NOT to Use / SQL Database Engines”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于安全审计、密钥扫描、权限检查或风险分析,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“When to Use / When NOT to Use / SQL Database Engines”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、执行终端命令、读取环境变量、主要在本地完成、通常不需要额外 API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;主要在本地完成;通常不需要额外 API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文出现了 `/develop`、`/code-review`、`/architecture-design`、`/migrate`、`/bugfix` 这类斜杠命令;如果你的 Agent 支持命令触发,优先用命令开场,再补充目标和边界。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、执行终端命令、读取环境变量。
先用一个小任务确认它会围绕“When to Use / When NOT to Use / SQL Database Engines”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: sql-database-patterns
description: Use this skill when the agent is designing schemas, reviewing migrations, tuning queries, modeli…
category: 安全
source: tomevault-io/skills-registry
---
# sql-database-patterns
## 什么时候使用
- 用于审阅代码、文档或方案并给出可执行反馈 适合处理安全审计、密钥扫描、权限检查和风险分析,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查、可继续迭代的步骤;通常不需要额外 A…
- 面向安全审计、密钥扫描、权限检查或风险分析,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「When to Use / When NOT to Use / SQL Database Engines」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;主要在本地完成;通常不需要额外 API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "sql-database-patterns" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> When to Use / When NOT to Use / SQL Database Engines
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Node.js / Python | 读取文件、写入/修改文件、执行终端命令、读取环境变量 | 主要在本地完成
安全层 -> 通常不需要额外 API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Database Patterns
Reference knowledge for relational and NoSQL database engineering — schema design, query optimization, indexing, partitioning, replication, NoSQL modeling, monitoring, and backup.
When to Use
- Designing or evolving a schema; reviewing a migration PR
- Tuning a slow query (EXPLAIN, indexing)
- Modeling access patterns in MongoDB, DynamoDB, Cassandra, Redis
- Planning partitioning, sharding, or replication topology
- Configuring monitoring, slow-query logging, vacuum/bloat checks
- Designing backup, restore, RTO/RPO strategy
When NOT to Use
- ORM-layer modeling in app code →
python-engineer/java-engineer(reference this skill) - Data pipelines / warehousing →
data-engineer - Database infra provisioning →
devops-engineer
SQL Database Engines
PostgreSQL
timestamptznottimestamp;textnotvarchar;numeric(p,s)for moneypg_stat_statements,pg_stat_user_tables,pg_stat_activityfor diagnosticspgauditfor audit trail;pgcryptofor column-level encryptionpg_repackfor online bloat reorganization;REINDEX CONCURRENTLYfor index bloat- Streaming replication: async for read replicas, sync for zero data loss
- PITR via
pg_basebackup+ WAL archiving - Failover: Patroni,
pg_auto_failover, or cloud-managed
MySQL
- InnoDB default; check
innodb_buffer_pool_sizesizing (60-80% RAM) - Use
EXPLAIN FORMAT=JSONfor execution plan;performance_schemafor diagnostics - Slow query log:
long_query_time,log_queries_not_using_indexes - Replication: row-based (RBR) default; GTID for failover; semi-sync for durability
- ProxySQL for read/write split and connection pooling
- Avoid
utf8(3-byte) — useutf8mb4(4-byte) for full Unicode
SQL Server
- Clustered index = physical row order; pick narrow, increasing, unique key
- Statistics auto-updated; use
UPDATE STATISTICSafter bulk loads sys.dm_exec_query_stats,sys.dm_db_missing_index_detailsfor tuning- Always On Availability Groups for HA; log shipping for DR
- Use
OPTION (RECOMPILE)sparingly — parameter sniffing is usually preferable - TDE for encryption at rest; Always Encrypted for column-level
Schema Design
- Normalization: 3NF by default. Denormalize only with measured read-performance justification
- Primary keys: Surrogate (
BIGSERIAL, UUID) for most tables. Natural keys only when immutable and unique - Foreign keys: Always explicit ON DELETE/ON UPDATE. CASCADE for child lifecycle, RESTRICT for references, SET NULL for optional
- Naming:
snake_case, plural tables (users,orders). FK:{table_singular}_id - Constraints: NOT NULL by default. CHECK for value ranges. UNIQUE for business keys
- Data types: Most specific type for storage + correctness
- Audit columns:
created_at timestamptz DEFAULT now(),updated_at timestamptzon every table
SQL Optimization
- EXPLAIN ANALYZE: Always use actual execution. Compare estimated vs actual rows — gaps = stale statistics
- Seq scan elimination: Add indexes. Check
work_memfor hash joins and sorts - Join order: Optimizer handles most cases. 10+ joins → use
join_collapse_limitor explicit order - CTEs: PG 12+ inlines by default. Use
MATERIALIZEDonly for optimization fences - Subquery vs JOIN: Prefer JOIN for correlated subqueries. EXISTS over IN for large subsets
- Batch ops:
INSERT ... ON CONFLICT(upsert).COPYfor bulk. Avoid row-by-row loops - Locking:
FOR UPDATE SKIP LOCKEDfor queues.NOWAITfor fast fail. Advisory locks for app coordination - Statistics:
ANALYZEafter bulk loads. Increasedefault_statistics_targetfor skewed distributions - No
SELECT *in production code — specify columns explicitly
Indexing Strategies
- B-tree (default): Equality + range. Composite: equality columns first, then range
- Hash: Equality-only, faster than B-tree for
=but no range - GIN: Full-text search, JSONB
@>, arrays.gin_trgm_opsforLIKE '%term%' - GiST: Spatial (PostGIS), range types, nearest-neighbor
- BRIN: Large append-only tables with natural ordering (time-series). Tiny index size
- Partial indexes:
WHERE active = true— index only filtered rows - Covering indexes:
INCLUDE (col)for index-only scans - Expression indexes:
CREATE INDEX ON t (lower(email))for case-insensitive lookups - Composite order: Most selective first for equality; leftmost prefix rule applies
- Maintenance:
REINDEX CONCURRENTLYfor bloat. Monitorpg_stat_user_indexesfor unused indexes - Justify cost: Every index must have a documented query pattern. Indexes slow writes and waste storage
Partitioning + Replication
Partitioning
- Range: Time-series (month/year), numeric ranges — most common
- List: Categorical (region, status, tenant_id) — good for multi-tenant
- Hash: Even distribution when no natural range/list. High-throughput writes
- Pruning: Queries must include partition key in WHERE for pruning
- Maintenance: Pre-create future partitions. Detach and archive old ones
- Constraints: PK and UNIQUE must include partition key
Replication
- Streaming replication (PostgreSQL): Async for read replicas, sync for zero data loss. Monitor replication lag
- Connection routing: Read queries to replicas, writes to primary. Use PgBouncer or application-level routing
- Failover: Automated via Patroni,
pg_auto_failover, or cloud-managed. Test failover regularly - Logical replication: For selective table replication, version upgrades, multi-master
- RTO/RPO: Define Recovery Time Objective and Recovery Point Objective. Design backup frequency and failover speed accordingly
NoSQL
MongoDB
- Schema design follows access patterns, not normalization. Embed for 1:1 and 1:few. Reference for 1:many and many:many
- Indexes: compound indexes follow ESR rule (Equality → Sort → Range). Use
explain()withexecutionStats - Aggregation pipeline for complex queries. Avoid
$lookupon large collections — denormalize instead - Sharding: choose shard key based on cardinality + write distribution + query isolation. Avoid monotonic keys (ObjectId) as shard key
- Write concern:
{w: "majority"}for durability;j: truefor journaled - Replica sets: minimum 3 voting members; use hidden/delayed secondaries for analytics
Redis
- Data structures: Strings (cache), Hashes (objects), Lists (queues), Sets (tags), Sorted Sets (leaderboards), Streams (event log)
- Key naming:
{service}:{entity}:{id}:{field}— consistent, scannable, eviction-friendly - TTL on every key — never store data without expiration unless explicitly persistent
- Memory management:
maxmemory-policy(allkeys-lrufor cache,noevictionfor queues). Monitorused_memoryvsmaxmemory - Persistence: RDB snapshots + AOF for durability; AOF-only for stricter RPO
- Cluster mode for horizontal scaling; sentinel for HA with single primary
Cassandra / ScyllaDB
- Model by query, not entity. Each query pattern = one table. Denormalization expected
- Partition key = distribution, clustering key = sort within partition
- Avoid partitions >100MB. Time bucketing for growing partitions
LOCAL_QUORUMfor strong consistency,ONEfor eventual- Avoid secondary indexes on high-cardinality columns; use materialized views or denormalized tables
- Tombstones:
gc_grace_secondstuning critical for deletion-heavy workloads
DynamoDB
- Single-table design: PK + SK overloading. GSIs for alternative access patterns
- Avoid hot partitions — random suffix on PK for high-throughput items
ProjectionExpressionto minimize read cost. Batch for bulk ops. TTL for auto-expiration- On-demand vs provisioned capacity — choose based on traffic predictability
- DAX for sub-millisecond read cache
- Streams for change data capture into Lambda / Kinesis
Time-Series + Graph
Time-Series
- TimescaleDB (PG extension): hypertables = automatic time-range partitioning + compression
- InfluxDB: tag/field separation, downsampling via continuous queries
- Use BRIN indexes on append-only time columns in PostgreSQL
- Retention policies: drop or compress partitions older than N days
- Pre-aggregate (continuous aggregates) for dashboard queries
Graph
- Neo4j: model relationships as first-class. Cypher queries for path/traversal
- Property graphs vs RDF/SPARQL — choose based on schema rigidity
- Index on node label + property for entry points
- Avoid unbounded variable-length paths in production queries
Monitoring + Capacity Planning
- Key metrics: QPS, latency (p50/p95/p99), active connections, replication lag, cache hit ratio, disk I/O, bloat
- PostgreSQL:
pg_stat_statements(query analysis),pg_stat_user_tables(seq scans, dead tuples),pg_stat_activity(locks) - Slow query log: Enable with threshold (100ms). Review top offenders weekly
- Connection pooling: PgBouncer or pgpool-II. Monitor saturation and wait time
- Vacuum: Tune
autovacuumper table. Monitorn_dead_tup. VACUUM FULL only in maintenance windows - Bloat: Monitor table/index bloat.
pg_repackfor online reorganization - Capacity: Project growth from current rate + business plan. Plan disk + memory + connection headroom 6–12 months ahead
Backup + Recovery
- PostgreSQL:
pg_basebackup+ WAL archiving for PITR.pg_dumpfor logical backups - MySQL:
mysqldump(logical),xtrabackup(physical, hot), binlog for PITR - Verify restores on schedule — untested backups are not backups
- Off-site copy: Backups must survive primary site failure
- Encryption at rest for backup files
- RTO/RPO documented and tested per database tier
Database Security
- Least privilege: App accounts get only required permissions on specific tables. Never use superuser for applications
- Row-Level Security (RLS): PostgreSQL RLS for multi-tenant isolation. Enable
FORCE ROW LEVEL SECURITYon the table owner - Encryption: TLS for connections (
sslmode=verify-full). Encryption at rest via disk/tablespace. Column-level (pgcrypto) for PII - Audit logging:
pgauditfor DDL/DML audit trail. Log all privileged operations - SQL injection: Parameterized queries only. Never concatenate user input. Review stored procedures for dynamic SQL
- No secrets in SQL files: Connection strings, passwords, keys → env vars or secret managers
When this applies
| Workflow | Apply this knowledge |
|---|---|
Agent(db-engineer) |
Auto-loaded |
/develop (DB work package) |
Spawned db-engineer loads this |
/code-review (migration PRs) |
Indexing + schema sections |
/architecture-design (data model) |
NoSQL + partitioning sections |
/migrate (schema migrations) |
Replication + backup sections |
/bugfix (query/perf) |
EXPLAIN + indexing sections |
Integration
- Consumed by:
db-engineer(primary),data-engineer,python-engineer/java-engineer(ORM review),solution-architect - External references: PostgreSQL, MySQL, SQL Server, MongoDB, Redis, Cassandra, DynamoDB official docs
Source: alex-voloshin-dev/ai-assets — distributed by TomeVault.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核