Greptimedb Perses Dashboard
GreptimeTeam/dashboard
Generate Perses dashboards or single panels for GreptimeDB. An agent skill from GreptimeTeam/dashboard.
GORM v2 最佳实践与性能优化。适用于:代码审查、慢查询优化、N+1、连接池、 事务管理、分库分表、Prometheus/OTel监控、Session安全、Clause/Upsert、 缓存集成、BaseModel脚手架、SQL→struct生成、多租户隔离。
$ npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills gorm-expert --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/gorm-expert-skill .claude/skills/gorm-expert && rm -rf skills-srcUse ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.
Claude Code skills documentation · loads skills from .claude/skills/
Install the "gorm-expert" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/gorm-expert-skill into .claude/skills/gorm-expert/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "gorm-expert", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/gorm-expert-skillType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills gorm-expert --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .agents/skills && cp -r skills-src/skills/gorm-expert-skill .agents/skills/gorm-expert && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "gorm-expert" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/gorm-expert-skill into .agents/skills/gorm-expert/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "gorm-expert", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills gorm-expert --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/skills/gorm-expert-skill .cursor/skills/gorm-expert && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "gorm-expert" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/gorm-expert-skill into .cursor/skills/gorm-expert/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "gorm-expert", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/LeoYeAI/openclaw-master-skills.git --path skills/gorm-expert-skill--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills gorm-expert --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/skills/gorm-expert-skill .gemini/skills/gorm-expert && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "gorm-expert" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/gorm-expert-skill into .gemini/skills/gorm-expert/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "gorm-expert", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install LeoYeAI/openclaw-master-skills gorm-expertInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .github/skills && cp -r skills-src/skills/gorm-expert-skill .github/skills/gorm-expert && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "gorm-expert" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/gorm-expert-skill into .github/skills/gorm-expert/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "gorm-expert", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills gorm-expert --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/skills/gorm-expert-skill .opencode/skills/gorm-expert && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "gorm-expert" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/gorm-expert-skill into .opencode/skills/gorm-expert/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "gorm-expert", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
gorm-expertGORM v2 最佳实践与性能优化。适用于:代码审查、慢查询优化、N+1、连接池、 事务管理、分库分表、Prometheus/OTel监控、Session安全、Clause/Upsert、 缓存集成、BaseModel脚手架、SQL→struct生成、多租户隔离。
Gorm Expert is an agent skill from LeoYeAI/openclaw-master-skills. GORM v2 最佳实践与性能优化。适用于:代码审查、慢查询优化、N+1、连接池、 事务管理、分库分表、Prometheus/OTel监控、Session安全、Clause/Upsert、 缓存集成、BaseModel脚手架、SQL→struct生成、多租户隔离。 触发词:GORM、数据库慢、加索引、写struct、分库分表、Preload、FOR UPDATE、 Session累积、goroutine db、缓存、多租户、迁移。
Its SKILL.md is about 3.4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 38 other files, including scripts, reference files and assets (for example `CHANGELOG.md`, `README.md` and `_meta.json`).
It sits in DevOps & Cloud, covering Async programming, Monitoring and alerting and SQL. It works with SQL, OpenTelemetry, Prometheus and Pydantic. The repository describes itself as: 🧠 Curated collection of 1209+ best OpenClaw skills — weekly updated by MyClaw.ai. The licence is MIT.
12 steps, taken from the step headings in SKILL.md.
Read from SKILL.md and the folder at commit e5199b5. It shows what the files ask for, not the result of running them.
Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.
From allowed-tools in the SKILL.md frontmatter.
Ships 1 file in scripts/ (Go, from the files we listed), which the agent can run.
Shell commands in SKILL.md call:
python3From the folder's file list and the shell code blocks in SKILL.md.
No URLs in SKILL.md.
From URLs in SKILL.md, links to its own repository left out.
Names no API keys, tokens, secrets or passwords.
From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Gorm Expert loads about 3.4k tokens when it runs, and up to ~30k if it reads all its reference files. Until then it costs about 57 tokens; SKILL.md has 394 words of instructions outside code blocks.
Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.
The automated check found no risky patterns in SKILL.md.
Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.
The full file from LeoYeAI/openclaw-master-skills at commit e5199b5, republished under its MIT licence (© LeoYeAI). 394 words, ~3,373 tokens.
.claude/skills/gorm-expert/SKILL.md (or your agent's skills folder). This skill also uses 35 other files; get the full folder from GitHub.用户提供代码/SQL/参数时,先跑脚本,只输出脚本结果 + 针对性说明。 所有脚本仅依赖 Python 3.8+,不调用任何外部 API 或凭证。
| 场景 | 脚本 | 用法示例 |
|---|---|---|
| Go 代码审查 | scripts/analyze_gorm.py | python3 scripts/analyze_gorm.py - <<< "代码"(R1–R27;CI 用 --format json) |
| CREATE TABLE → struct | scripts/gen_model.py | echo "CREATE TABLE..." | python3 scripts/gen_model.py -(PG 加 --dialect pg) |
| 连接池计算 | scripts/pool_advisor.py | python3 scripts/pool_advisor.py --qps 500 --avg-latency-ms 20 --app-instances 4 |
| SQL 性能分析 | scripts/query_explain.py | python3 scripts/query_explain.py "SELECT * FROM ..." |
| 迁移 SQL 生成 | scripts/migration_gen.py | python3 scripts/migration_gen.py old.go new.go --table users |
| Scope 生成 | scripts/scope_gen.py | python3 scripts/scope_gen.py model.go --tenant --paginate |
| Benchmark 模板 | scripts/bench_template.py | 默认 stdout;写文件加 --output bench_test.go |
| 项目初始化 | scripts/init_project.py | 先 --dry-run 预览,再 --output ./internal/dbcore 写入 |
gorm.Config 必须设置 DisableForeignKeyConstraintWhenMigrating: true;若已有 foreignKey tag 必须加 constraint:falsedb.Debug() 或自定义 Logger 定位慢 SQLdb, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{
SkipDefaultTransaction: true, // 写性能 +30%
PrepareStmt: true, // SQL 编译缓存
DisableForeignKeyConstraintWhenMigrating: true, // 禁物理 FK
Logger: logger.New(writer, logger.Config{
SlowThreshold: 200 * time.Millisecond,
LogLevel: logger.Warn,
}),
})
sqlDB, _ := db.DB()
sqlDB.SetMaxOpenConns(100)
sqlDB.SetMaxIdleConns(20) // MaxOpen 的 20%
sqlDB.SetConnMaxLifetime(time.Hour)
sqlDB.SetConnMaxIdleTime(10 * time.Minute)连接池参数建议:
python3 scripts/pool_advisor.py --qps 500 --avg-latency-ms 20
ID 生成策略(使用 dbcore 脚手架时配置):
// Snowflake(默认,零依赖)
dbcore.SetIDGenerator(dbcore.NewSnowflakeGenerator(nodeID))
// Leaf-Segment(高并发推荐,严格递增,需 MySQL 号段表)
dbcore.SetIDGenerator(dbcore.NewLeafSegmentGenerator(db, "order"))
// UUID(无需协调,不可排序)
dbcore.SetIDGenerator(dbcore.NewUUIDGenerator())策略选型、时钟回拨保护、K8s nodeID 管理详见
references/id-generation.md
多租户配置(按需开启,默认关闭):
dbcore.SetConfig(dbcore.Config{
TenantEnabled: true, // 开启多租户隔离
TenantField: "tenant_id", // 租户字段名
TenantStrict: true, // 严格模式:无租户时拒绝查询
TenantExtractor: func(ctx context.Context) string {
if tid, ok := ctx.Value("tenant_id").(string); ok { return tid }
return ""
},
})
// 开启后所有 BaseModel CRUD 自动注入 tenant_id 条件,无需手动拼接
// 不需要多租户时,不调用 SetConfig 即可(TenantEnabled 默认 false)脚手架初始化:
python3 scripts/init_project.py --output ./internal/dbcore # 写入
python3 scripts/init_project.py --output ./internal/dbcore --dry-run # 仅预览
python3 scripts/init_project.py --output ./internal/dbcore --example # 含示例// ❌ SELECT *
db.Find(&users)
// ✅ SELECT id, name, email
db.Select("id", "name", "email").Find(&users)
// ✅ 投影到小 struct
db.Model(&User{}).Select("id", "name").Scan(&dtos)// ❌ N+1:循环内查 DB
for _, u := range users { db.Where("user_id=?", u.ID).Find(&u.Orders) }
// ✅ Preload:两次查询
db.Preload("Orders").Find(&users)
// ✅ Joins:一次 JOIN,按关联字段过滤
db.Joins("JOIN orders ON orders.user_id=users.id AND orders.status=?","paid").Find(&users)
// ✅ 带条件 Preload
db.Preload("Orders", "status=?", "paid").Preload("Orders.Items").Find(&users)Preload vs Joins 选型详见
references/association.md
// ✅ FindInBatches:每批 500 条
db.Model(&User{}).FindInBatches(&batch, 500, func(tx *gorm.DB, n int) error {
process(batch); return nil
})
// ✅ 游标分页(大表推荐,避免 OFFSET 退化)
var lastID uint
for {
var users []User
db.Where("id > ?", lastID).Order("id").Limit(500).Find(&users)
if len(users) == 0 { break }
lastID = users[len(users)-1].ID
}// 分组统计
db.Model(&Order{}).Select("user_id, SUM(amount) as total").
Group("user_id").Having("SUM(amount) > ?", 1000).Scan(&results)
// 去重
db.Distinct("status").Model(&Order{}).Pluck("status", &statuses)
// 子查询
subQuery := db.Model(&Order{}).Select("user_id").Where("amount > ?", 1000)
db.Where("id IN (?)", subQuery).Find(&users)// 流式读取(超大数据集,逐行处理)
rows, _ := db.Model(&User{}).Where("status = ?", "active").Rows()
defer rows.Close()
for rows.Next() { var u User; db.ScanRows(rows, &u); process(u) }
// 索引提示
db.Clauses(hints.UseIndex("idx_user_name")).Find(&users)
db.Clauses(hints.ForceIndex("idx_created_at").ForOrderBy()).Find(&orders)// ❌ 逐条 INSERT(N 次 Round-trip)
for _, u := range users { db.Create(&u) }
// ✅ 批量插入
db.CreateInBatches(&users, 200)// ❌ struct Updates 忽略零值(int=0, bool=false)
db.Model(&user).Updates(User{Name: "new", Age: 0}) // Age=0 被忽略!
// ✅ map 明确指定字段
db.Model(&user).Updates(map[string]any{"name": "new", "age": 0})
// ✅ Select 限制 / Omit 排除
db.Model(&user).Select("name", "email").Updates(&user)
db.Model(&user).Omit("password").Updates(&user)result := db.Model(&User{}).Where("id = ?", id).Update("status", "banned")
if result.Error != nil { return result.Error }
if result.RowsAffected == 0 { return fmt.Errorf("user %d not found", id) }db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "email"}},
DoUpdates: clause.AssignmentColumns([]string{"name", "updated_at"}),
}).Create(&user)
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&users) // 忽略冲突// 标准事务
err := db.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&order).Error; err != nil { return err }
return tx.Model(&stock).Update("qty", gorm.Expr("qty - ?", 1)).Error
})
// 嵌套事务(GORM 自动 SavePoint)
tx.Transaction(func(tx2 *gorm.DB) error { return tx2.Create(&log).Error })
// 悲观锁(FOR UPDATE)
db.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id=?", id).First(&stock)乐观锁、CAS、Savepoint、事务陷阱详见
references/concurrency.md
db.Use(dbresolver.Register(dbresolver.Config{
Sources: []gorm.Dialector{mysql.Open(writeDSN)},
Replicas: []gorm.Dialector{mysql.Open(read1DSN), mysql.Open(read2DSN)},
Policy: dbresolver.RandomPolicy{},
}).SetMaxOpenConns(50).SetMaxIdleConns(10))
// GORM 自动路由:Find/First → Replica;Create/Update/Delete → Source
db.Clauses(dbresolver.Write).Find(&user) // 强制走主库// 可复用 Scope
func ActiveUser(db *gorm.DB) *gorm.DB { return db.Where("status = ?", "active") }
func AgeOver(age int) func(*gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB { return db.Where("age > ?", age) }
}
db.Scopes(ActiveUser, AgeOver(18)).Find(&users)多租户隔离(两种方式,按需选择):
// 方式 1(推荐):通过 dbcore.Config 全局开关,BaseModel 自动注入
// 开启:dbcore.SetConfig(dbcore.Config{TenantEnabled: true, ...})
// 关闭:不调用 SetConfig 或 TenantEnabled: false(默认)
// 详见 §1 初始化配置
// 方式 2:手动 Scope(不使用 dbcore 时适用)
func TenantScope(ctx context.Context) func(*gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if tid, ok := ctx.Value("tenant_id").(string); ok && tid != "" {
return db.Where("tenant_id = ?", tid)
}
return db.Where("1 = 0")
}
}自动生成:
python3 scripts/scope_gen.py model.go --tenant --paginate完整示例详见references/scopes.md
type Order struct {
gorm.Model
UserID uint `gorm:"not null;index"` // 逻辑外键:只加索引,不建 FK
Status string `gorm:"type:varchar(20);index"`
Amount int64 `gorm:"not null;default:0"`
}逻辑外键规范(核心原则 #1):
// ❌ 物理外键:会在 AutoMigrate 时创建 FK CONSTRAINT
User User `gorm:"foreignKey:UserID"`
// ❌ 有 references 但没有 constraint:false
User User `gorm:"foreignKey:UserID;references:ID"`
// ✅ 逻辑外键:显式禁止约束
User User `gorm:"foreignKey:UserID;constraint:false"`
// ✅ 全局禁止(必须写在 gorm.Config 中)
db, _ := gorm.Open(dsn, &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})物理外键的问题:分库分表不兼容、级联不可控、高并发性能瓶颈、导入迁移困难。 详见
references/base-model-pattern.md
db.Debug().Find(&users) // 单次打印 SQL
// ToSQL(不执行,只生成 SQL)
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Where("id > ?", 100).Limit(10).Find(&users)
})pprof / Benchmark 详见
references/observability.md
| 问题 | 错误写法 | 正确做法 |
|---|---|---|
| 忘记传 Context | db.Find(&u) | db.WithContext(ctx).Find(&u) |
| struct Updates 丢零值 | db.Updates(User{Age:0}) | db.Updates(map[string]any{"age":0}) |
| 大 OFFSET 分页 | db.Offset(100000).Limit(20) | 游标分页 WHERE id > lastID |
| 前导通配 Like | LIKE '%foo%' | 前缀匹配 LIKE 'foo%' 或全文索引 |
| 事务内耗时操作 | 事务 + HTTP 调用 | HTTP 移到事务外 |
| 未检查 Error | db.Find(&u); use u | if err := db.Find(&u).Error; err != nil |
| 物理外键 | 未加 constraint:false | 加 constraint:false 或全局禁止 |
| Save 全量更新 | db.Save(&user) | db.Model(&u).Updates(map[string]any{...}) |
| 忽略 RowsAffected | 不检查影响行数 | if result.RowsAffected == 0 { ... } |
func (r *UserRepo) GetUser(ctx context.Context, id uint) (*User, error) {
key := fmt.Sprintf("user:%d", id)
if val, err := r.rdb.Get(ctx, key).Bytes(); err == nil {
var u User; json.Unmarshal(val, &u); return &u, nil
}
// singleflight 防击穿
res, err, _ := r.group.Do(key, func() (any, error) {
var u User
if err := r.db.WithContext(ctx).First(&u, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
r.rdb.Set(ctx, key, "null", time.Minute) // 防穿透
}
return nil, err
}
ttl := 30*time.Minute + time.Duration(rand.Int63n(int64(6*time.Minute))) // 抖动防雪崩
data, _ := json.Marshal(u)
r.rdb.Set(ctx, key, data, ttl)
return &u, nil
})
// 写操作:更新 DB → 删缓存(不更新缓存)
}布隆过滤器防穿透、延迟双删、列表缓存详见
references/caching.md
db.Use(sharding.Register(sharding.Config{
ShardingKey: "user_id", NumberOfShards: 64,
PrimaryKeyGenerator: sharding.PKSnowflake,
}, "orders"))
db.Where("user_id = ?", userID).Find(&orders) // 携带分片键 → 自动路由分片算法、双写迁移、跨分片查询详见
references/sharding.md
db.Use(prometheus.New(prometheus.Config{DBName: "myapp", RefreshInterval: 15}))
db.Use(otelgorm.NewPlugin(otelgorm.WithDBName("myapp"))) // OpenTelemetryPrometheus 告警、Grafana 仪表盘、pprof 详见
references/observability.md
// ❌ 条件累积 + goroutine 数据竞争
base := db.Where("tenant_id = ?", tid)
go func() { base.Find(&list1) }() // 危险!
// ✅ Session 隔离
go func() { base.Session(&gorm.Session{NewDB: true}).Find(&list1) }()Session 配置项、8 种陷阱详见
references/session.md
db.Clauses(clause.Locking{Strength: "UPDATE"}).First(&stock) // FOR UPDATE
db.Clauses(clause.Locking{Strength: "UPDATE", Options: "SKIP LOCKED"}).Find(&tasks) // 任务抢占
db.Clauses(clause.Returning{}).Create(&user) // RETURNING(PostgreSQL)完整 Clause 用法、自定义表达式详见
references/clause.md
db.Preload("Orders", "status = ?", "paid").Find(&users)
db.Preload(clause.Associations).Find(&users) // 预加载所有关联
db.Omit(clause.Associations).Create(&user) // 跳过关联写入
db.Model(&user).Association("Orders").Append(&order) // 添加关联Preload vs Joins、级联控制、多对多详见
references/association.md
type User struct {
Tags []string `gorm:"type:json;serializer:json"` // JSON 自动序列化
Phone string `gorm:"serializer:encrypted"` // 自定义加密
}完整实现、GormDataType 接口详见
references/serializer.md
errors.Is(err, gorm.ErrRecordNotFound) // ✅ v2 正确写法
// ❌ gorm.IsRecordNotFoundError(err) — v1 API,v2 已移除
// 注意:Find 不触发 ErrRecordNotFound;First/Take/Last 触发详细专题见 references/ 目录(按需加载,不要全量读入):
| 文件 | 内容 | 触发时机 |
|---|---|---|
base-model-pattern.md | BaseModel Bug 修复、游标分页、多租户隔离 | BaseModel、QueryBuilder、分页 |
session.md | Session 机制、goroutine 安全、条件累积 | Session、db 复用、DryRun |
clause.md | Clause 系统(Upsert/FOR UPDATE/RETURNING) | FOR UPDATE、Upsert |
association.md | Preload/Joins、级联控制 | 关联加载、多对多 |
serializer.md | Serializer、自定义类型(枚举/Money/加密) | 字段序列化 |
hooks.md | Hook 执行顺序、性能陷阱 | Hook 使用 |
raw-sql.md | Raw SQL / Scan / Rows | 原生 SQL |
indexing.md | 索引设计、EXPLAIN 验证 | 索引、慢查询 |
concurrency.md | 乐观锁、悲观锁、CAS | 并发冲突、超卖 |
testing.md | sqlmock、SQLite 集成测试 | GORM 测试 |
migration.md | golang-migrate、大表在线 DDL | 数据库迁移 |
sharding.md | 分库分表、分片算法 | 水平拆分 |
observability.md | Prometheus、OTel、Grafana | 监控 |
scopes.md | Scope、分页、多租户 | Scope 用法 |
caching.md | Cache-Aside、防击穿/雪崩/穿透 | Redis 缓存 |
soft-delete.md | 软删除、唯一约束兼容、归档清理 | 软删除 |
id-generation.md | Snowflake/Leaf-Segment/UUID、时钟回拨 | 分布式 ID |
© LeoYeAI, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
SKILL.md and 35 other files (scripts, references, assets) in skills/gorm-expert-skill of LeoYeAI/openclaw-master-skills.
Open the folder on GitHubat commit e5199b5
Gorm Expert next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Gorm Expert this skillLeoYeAI/openclaw-master-skills | 2.2k | — | ~3.4k | Automated safety check: Pass | MIT | |
| Greptimedb Perses DashboardGreptimeTeam/dashboard | 111 | — | ~3.9k | Automated safety check: Pass | Apache-2.0 | |
| Python Observability Patternsaiskillstore/marketplace | 430 | 1 repos | ~1.3k | Automated safety check: Pass | None | |
| Qdrant Advisorqdrant/skills | 254 | — | ~1.7k | Automated safety check: Pass | Apache-2.0 | |
| Database Observabilitygrafana/skills | 281 | — | ~1.1k | Automated safety check: Pass | Apache-2.0 | |
| Signozqjoly/GitOps | 112 | — | ~6.1k | Automated safety check: Pass | WTFPL |
GreptimeTeam/dashboard
Generate Perses dashboards or single panels for GreptimeDB. An agent skill from GreptimeTeam/dashboard.
aiskillstore/marketplace
Observability patterns for Python applications. An agent skill from aiskillstore/marketplace.
qdrant/skills
Diagnose, troubleshoot, and advise on any Qdrant deployment by loading the latest official Qdrant skills live from skills.qdrant.tech.
grafana/skills
Set up Grafana Cloud Database Observability for MySQL and PostgreSQL — enables pgstatstatements / Performance Schema, creates a least-privilege monitoring user, configures the…
qjoly/GitOps
Manage the self-hosted SigNoz observability stack in this GitOps repo.
basicmachines-co/basic-memory
Adds Pydantic Logfire tracing, logging and metrics to Python, JavaScript or TypeScript and Rust projects, with the correct setup order and library extras.
LeoYeAI/openclaw-master-skills
Manages pipelines on a DevOps quality and efficiency platform through its OpenAPI: list workspaces and templates, create, update, run and cancel pipelines, and read run records.
LeoYeAI/openclaw-master-skills
Patches OpenClaw's Feishu extension so an edited document triggers an isolated agent session that reads the doc and replies inline, turning it into a live chat space.
LeoYeAI/openclaw-master-skills
Multi-context memory management system for OpenClaw agents with group-isolated storage, global shared memory, workspace organization, and group-specific skills isolation.
LeoYeAI/openclaw-master-skills
Runs a brand's AI-search visibility work end to end: diagnosing how AI platforms represent it, repositioning it, producing AI-optimized content and monitoring ongoing mentions.
LeoYeAI/openclaw-master-skills
Installs and authenticates the gws CLI, then automates Gmail, Drive, Sheets, Calendar, Docs, Chat and Tasks with ready-made recipes, persona bundles and security audits.
LeoYeAI/openclaw-master-skills
Runs four advisor roles, a fitness coach, nutritionist, data analyst and TCM practitioner, to build a health profile and track workouts, diet and wellness over time.
Works with
Categories
GORM v2 最佳实践与性能优化。适用于:代码审查、慢查询优化、N+1、连接池、 事务管理、分库分表、Prometheus/OTel监控、Session安全、Clause/Upsert、 缓存集成、BaseModel脚手架、SQL→struct生成、多租户隔离。. Gorm Expert is an agent skill from LeoYeAI/openclaw-master-skills.
Gorm Expert fits situations like: tasks that involve Async programming; tasks that involve Monitoring and alerting; tasks that involve SQL.
Run `npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a claude-code`. Or copy the skill folder (skills/gorm-expert-skill in LeoYeAI/openclaw-master-skills) into .claude/skills/gorm-expert in your project. Claude Code loads it when a task matches its description.
Run `npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a codex`. Or copy the skill folder (skills/gorm-expert-skill in LeoYeAI/openclaw-master-skills) into .agents/skills/gorm-expert in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add LeoYeAI/openclaw-master-skills --skill gorm-expert -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/gorm-expert, .gemini/skills/gorm-expert, .github/skills/gorm-expert and .opencode/skills/gorm-expert in your project.
Going by SKILL.md and its folder, Gorm Expert needs Go for the scripts in its folder and the command-line tools its instructions call (python3). Our summary lists: Python 3.
SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.
Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.
Gorm Expert is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.
About 3.4k tokens (SKILL.md is roughly 13k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 27k tokens, read only when the agent opens those files.
Skills that share tags, products or a category with Gorm Expert: Greptimedb Perses Dashboard (GreptimeTeam/dashboard, 111 stars), Python Observability Patterns (aiskillstore/marketplace, 430 stars), Qdrant Advisor (qdrant/skills, 254 stars) and Database Observability (grafana/skills, 281 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
LeoYeAI (a GitHub user) maintains it in LeoYeAI/openclaw-master-skills, which has 2,160 GitHub stars. The repository holds 1,235 skills in this directory. The repository was last updated on July 20, 2026.
Source: LeoYeAI/openclaw-master-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.