sqlc
根据 SQL 定义文件生成类型安全的 Go 数据库访问代码,自动创建多数据库引擎统一接口与共享数据模型,确保跨 SQLite PostgreSQL MySQL 的查询一致性,并通过自动化流程维护接口与模型代码的同步更新。
| name | sqlc |
| description | Working with sqlc and database queries |
SQLC Skill
This skill provides instructions for working with sqlc and database queries in the NCPS repository. NCPS supports multiple database engines (SQLite, PostgreSQL, MySQL), and sqlc is used to generate type-safe Go code from SQL queries for each engine.
Configuration
- SQLC Config:
sqlc.yml - Queries:
- SQLite:
db/query.sqlite.sql - PostgreSQL:
db/query.postgres.sql - MySQL:
db/query.mysql.sql
- SQLite:
- Output:
- SQLite:
pkg/database/sqlitedb - PostgreSQL:
pkg/database/postgresdb - MySQL:
pkg/database/mysqldb
- SQLite:
Workflow for Query Changes
Any time a query file (db/query.<engine>.sql) is updated, you MUST follow these steps:
1. Generate SQLC Code
Run the sqlc generate command to update the generated Go files for all engines.
▼bash复制代码sqlc generate
2. Regenerate Database Wrappers and Models
Run go generate for the pkg/database package. This command uses gen-db-wrappers to automatically:
- Extract the
Querierinterface from thepostgresdbbackend. - Generate the common
Querierinterface inpkg/database/querier.go. - Generate common domain models in
pkg/database/models.go. - Generate database wrappers (
wrapper_sqlite.go,wrapper_postgres.go,wrapper_mysql.go).
▼bash复制代码go generate ./pkg/database
[!IMPORTANT] Do NOT manually edit
pkg/database/querier.goorpkg/database/models.go. They are fully automated.
Best Practices
-
Consistency: Ensure that equivalent queries exist for all supported engines unless the feature is engine-specific.
-
Linting: Use
sqlfluffto lint and format SQL files before runningsqlc generate.▼bash复制代码sqlfluff lint db/query.*.sql sqlfluff format db/query.*.sql









