3.2 KiB
3.2 KiB
gormcol
Type-safe GORM column descriptors and model generation utilities.
Library
Define struct-like variables mapping Go field names to table.column pairs:
var PsAccess = struct {
IDProfile gormcol.Field
IDAuthorizationRole gormcol.Field
}{
IDProfile: gormcol.Field{Table: "ps_access", Column: "id_profile"},
IDAuthorizationRole: gormcol.Field{Table: "ps_access", Column: "id_authorization_role"},
}
Use the three accessor functions to extract column and table names without string literals:
gormcol.Column(PsAccess.IDAuthorizationRole) // "id_authorization_role"
gormcol.ColumnOnTable(PsAccess.IDAuthorizationRole) // "ps_access.id_authorization_role"
gormcol.TableField(PsAccess.IDAuthorizationRole) // "ps_access"
CLI
The cmd/ directory contains a standalone tool that generates GORM model files with column descriptors.
Install
go install git.ma-al.com/goc_marek/gormcol/cmd@latest
Usage
gormcol-gen --dsn <connection-string> [options]
| Flag | Default | Description |
|---|---|---|
--dsn |
(required) | MySQL/MariaDB DSN, e.g. user:pass@tcp(localhost:3306)/dbname |
--filter |
(ps_|b2b_).* |
Regex matching table names to generate |
--out |
./app/model/dbmodel |
Output directory for generated files |
--pkg |
dbmodel |
Go package name for generated files |
Example
./gormcol-gen --dsn "user:pass@tcp(localhost:3306)/mydb" --filter "ps_.*" --out ./internal/model --pkg model
This connects to the database, generates a .go model file for each matching table, and appends <Model>Cols variables with typed gormcol.Field descriptors to each file.
Using generated models
After generation, each model file contains a struct and a Cols variable:
// model/product.go
type Product struct {
ID uint `gorm:"column:id_product;primaryKey"`
Name string `gorm:"column:name"`
Price float32 `gorm:"column:price;type:decimal(20,6)"`
}
var ProductCols = struct {
ID Field
Name Field
Price Field
}{
ID: Field{Table: "ps_product", Column: "id_product"},
Name: Field{Table: "ps_product", Column: "name"},
Price: Field{Table: "ps_product", Column: "price"},
}
GORM queries with type-safe columns
Use ColumnOnTable for table-qualified column references in GORM clauses:
import "git.ma-al.com/goc_marek/gormcol"
// Where clauses
db.Where(
gormcol.ColumnOnTable(model.ProductCols.Price) + " > ?",
100.0,
).Find(&products)
// Order
db.Order(gormcol.ColumnOnTable(model.ProductCols.Name) + " ASC").Find(&products)
// Joins
db.Joins("JOIN ps_category ON " +
gormcol.ColumnOnTable(model.ProductCols.ID) + " = ps_category.id_product",
).Find(&products)
Unqualified column names
Use Column when the table is already scoped:
db.Select(gormcol.Column(model.ProductCols.Name)).Find(&products)
// Raw queries
db.Raw("SELECT " + gormcol.Column(model.ProductCols.Name) + " FROM ps_product").Scan(&names)
Table name
Use TableField to get the table name from a column descriptor:
table := gormcol.TableField(model.ProductCols.ID) // "ps_product"
Dependencies
gorm.io/gormgorm.io/gengorm.io/driver/mysql