一键导入
go-database
MySQL database patterns with sqlx. Connection pooling, query patterns, transactions, repository pattern, error handling. 100% Go-specific.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
MySQL database patterns with sqlx. Connection pooling, query patterns, transactions, repository pattern, error handling. 100% Go-specific.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Spec-driven development workflow. Main Claude acts as the lead — spawns critic/scout/architect/builder/tester/reviewer as subagents, enforces human-in-the-loop gates at every phase boundary via AskUserQuestion, records every decision in docs/specs/<slug>/group-log.md. Load this skill whenever the user invokes /define, /orchestrate, /plan, /build, or /ship; whenever a task spans multiple files, packages, or concerns; whenever design decisions need review before implementation; whenever an in-progress spec under docs/specs/<slug>/ needs to resume; or whenever you're about to coordinate critic/scout/architect/builder/tester/reviewer in a sequence. This is the correct skill for any multi-step engineering task that benefits from gated, auditable execution — do not try to coordinate specialists ad-hoc.
Artifact contract for docs/specs/<slug>/ — spec.md template, frontmatter schema (task/status/current_group/total_groups/created/updated), spec directory layout, contracts-trigger rules, and parallelization markers ([P]). Load this skill whenever you're creating a new docs/specs/<slug>/ directory, authoring or editing spec.md, checking whether an existing spec matches the template (e.g., during review, resumption, or session-start scan), validating frontmatter values, or deciding whether a task needs contracts.md. Pair with core/orchestration, which owns the workflow that populates these artifacts.
Author and maintain a project constitution at docs/constitution.md — the list of invariants that reviewer and critic enforce on every spec and every diff. Load this skill whenever you're creating a new constitution from scratch or from EXAMPLE_CONSTITUTION.md, proposing candidate invariants via /constitution-propose, adding or editing an invariant, sunsetting an obsolete rule, or promoting a recurring "don't do X" review comment into an enforced invariant. Also use when a post-incident review surfaces a rule that should have been caught mechanically. Reviewer and critic consume the registered invariants automatically via the project_constitution session-start field — you do not need this skill for enforcement, only for authoring.
Ground a task in the existing codebase before specification — grep for prior art, read similar features, surface inherited gotchas, write discovery.md. Load this skill whenever you're running scout during /define or /orchestrate, whenever a task touches an area of the codebase you have not read in this session, whenever the task mentions a feature name that might already exist, or whenever recent_learnings flags a gotcha or pattern near the task. Prevents specs built on phantom assumptions.
Decision tree for routing any task to the right agent and skill set. Loaded on session start and consulted whenever you're unsure which specialist applies, which skill combination to load for a given task, or when main Claude (running core/orchestration) needs to decide which subagent to spawn for a Phase 3 subtask. Also surfaces available CLI tools, MCP servers, and user-installed skills/agents/plugins so you can prefer what's actually on the machine.
Output compression for human-facing responses. Use when responding to users in a terminal, writing end-of-turn summaries, explaining diffs, producing status updates, or any non-artifact output addressed to a human reader. Specifies what to compress (articles, filler, pleasantries, hedging) and what to leave full-fidelity (SPEC files, agent-to-agent reports, commands, code blocks, paths, acceptance criteria, inline docstrings). Triggered automatically by the /compact slash command and loaded by all agents by default.
| name | go/database |
| description | MySQL database patterns with sqlx. Connection pooling, query patterns, transactions, repository pattern, error handling. 100% Go-specific. |
Always use context-aware methods. Close rows. Defer transaction rollback. Parameterize queries.
Use sqlx for production services. Reduced boilerplate and struct mapping outweigh the dependency.
func Connect(cfg Config) (*sqlx.DB, error) {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&charset=utf8mb4&collation=utf8mb4_unicode_ci",
cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Database)
db, err := sqlx.Connect("mysql", dsn)
if err != nil { return nil, fmt.Errorf("connect to mysql: %w", err) }
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
db.SetConnMaxIdleTime(10 * time.Minute)
return db, db.Ping()
}
Tag structs: db:"column_name". Method selection:
| Method | Use When |
|---|---|
GetContext | Single row (returns sql.ErrNoRows if missing) |
SelectContext | Multiple rows (empty slice if 0) |
ExecContext | INSERT/UPDATE/DELETE |
NamedExecContext | Mutations with many params |
Always use *Context variants. The non-context methods (Exec, Query, Get, Select) do not honor context cancellation or timeouts — a slow query keeps running even after the request is cancelled, holding a connection and a row-level lock. This is the most common Go database bug. Handle sql.ErrNoRows for single-row lookups. Use sqlx.In() + db.Rebind() for IN clauses.
// BAD — no timeout, no cancellation
rows, err := db.Query("SELECT * FROM users WHERE active = ?", true)
// GOOD — honors ctx deadline and cancellation
rows, err := db.QueryContext(ctx, "SELECT * FROM users WHERE active = ?", true)
Use a linter rule (e.g., sqlrows or a custom grep in CI) to prevent the non-context methods from being called at all.
tx, err := r.db.BeginTxx(ctx, nil)
if err != nil { return fmt.Errorf("begin transaction: %w", err) }
defer tx.Rollback() // No-op after commit
_, err = tx.ExecContext(ctx, "UPDATE accounts SET balance = balance - ? WHERE user_id = ?", amount, fromID)
if err != nil { return fmt.Errorf("deduct balance: %w", err) }
return tx.Commit()
type UserRepository struct { db *sqlx.DB }
func NewUserRepository(db *sqlx.DB) *UserRepository { return &UserRepository{db: db} }
// Interface defined at consumer side
type UserFinder interface { FindByID(ctx context.Context, id int64) (*User, error) }
var mysqlErr *mysql.MySQLError
if errors.As(err, &mysqlErr) {
switch mysqlErr.Number {
case 1062: return fmt.Errorf("duplicate entry: %w", err)
case 1452: return fmt.Errorf("foreign key violation: %w", err)
}
}
| Workload | MaxOpenConns | MaxIdleConns |
|---|---|---|
| Low traffic | 10-25 | 2-5 |
| High traffic | 50-100 | 10-20 |
| Background jobs | 5-10 | 2-5 |
Formula: MaxOpenConns <= MySQL max_connections / app instances
*Context method variants used everywhere (never Exec, Query, Get without context)defer tx.Rollback() present immediately after every BeginTxx call?) — no string concatenation of user inputSetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime)