DAO Overview
Gen follows the Configuration As Code practice to generate the DAO interface, here is the introduction to the configuration.
Configuration
You need to write the configuration as a runnable golang program, usually, the program will be organized in a sub-directory of your application.
// configuration.go
package main
import (
"gorm.io/gen"
"gorm.io/gorm"
"gorm.io/driver/sqlite"
)
func main() {
// Initialize the generator with configuration
g := gen.NewGenerator(gen.Config{
OutPath: "../dal", // output directory, default value is ./query
Mode: gen.WithDefaultQuery | gen.WithQueryInterface,
FieldNullable: true,
})
// Initialize a *gorm.DB instance
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
// Use the above `*gorm.DB` instance to initialize the generator,
// which is required to generate structs from db when using `GenerateModel/GenerateModelAs`
g.UseDB(db)
// Generate default DAO interface for those specified structs
g.ApplyBasic(model.Customer{}, model.CreditCard{}, model.Bank{}, model.Passport{})
// Generate default DAO interface for those generated structs from database
companyGenerator := g.GenerateModelAs("company", "MyCompany"),
g.ApplyBasic(
g.GenerateModel("users"),
companyGenerator,
g.GenerateModelAs("people", "Person",
gen.FieldIgnore("deleted_at"),
gen.FieldNewTag("age", `json:"-"`),
),
)
// Execute the generator
g.Execute()
}Run the above program, it will generate codes into directory ../dal, you can import the dal package in your application and use its interface to query data
gen.Config
type Config struct {
OutPath string // query code path
OutFile string // query code file name, default: gen.go
ModelPkgPath string // generated model code's package name
WithUnitTest bool // generate unit test for query code
FieldNullable bool // generate pointer when field is nullable
FieldCoverable bool // generate pointer when field has default value, to fix problem zero value cannot be assign: https://gorm.io/docs/create.html#Default-Values
FieldSignable bool // detect integer field's unsigned type, adjust generated data type
FieldWithIndexTag bool // generate with gorm index tag
FieldWithTypeTag bool // generate with gorm column type tag
Mode GenerateMode // generator modes
}Output Options
| Option Name | Description | | FieldNullable | Generate pointer as field's type if column is nullable in database | | FieldCoverable | Generate pointer as field's type if column has default value in database, to avoid zero-value issue, e.g: https://gorm.io/docs/create.html#Default-Values | | FieldSignable | Use signable type as field's type based on column's data type in database | | FieldWithIndexTag | Generate with gorm index tag | , for example: gorm:"index:idx_name", default value: false | FieldWithTypeTag | Generate with gorm type tag, for example: gorm:"type:varchar(12)", default value: false |
Refer Database To Structs for more options
Generator Modes
| Tag Name | Description |
