GEN Guides
GEN: Friendly & Safer GORM powered by Code Generation.
Overview
- Idiomatic & Reusable API from Dynamic Raw SQL
- 100% Type-safe DAO API without
interface{} - Database To Struct follows GORM conventions
- GORM under the hood, supports all features, plugins, DBMS that GORM supports
Install
go get -u gorm.io/gen |
Quick start
It is quite straightforward to use gen for your application, here is how it works:
1. Write the configuration in golang (skeleton — substitute your own model
package, DSN and import paths):
package main |
2. Generate Code
go run main.go
3. Use the generated code in your project (usage skeleton — the
prerequisites shown in main are required for the snippets below: open your
application’s *gorm.DB and register it with query.SetDefault(db) before anyquery.User-style default-variable call; results are consumed via err/the
returned values)
import ( |
NOTE:
g.UseDB(db)must be called in the generator program beforeGenerateModel/GenerateModelAs— those read the database schema through the
connection and fail withUseDB() is necessary to generate model struct [...] from database table [...]
when it is missing.GenerateAllTableequally requires a real database
connection (it lists the tables through the DB), but does not carry that
specific guard — withoutUseDBit fails later, at listing the tables.
(GenerateModelFromandApplyBasicapplied to existing structs do not query
the database schema and are exempt.) In the default (context-aware) mode,
generated methods are reached through the model’sWithContext, e.g.query.User.WithContext(ctx).FilterWithNameAndRole("modi", "admin").