GORM 提供的配置可以在初始化时使用
源码路径 gorm.io/gorm/gorm.go
// Config GORM config
type Config struct {
// GORM perform single create, update, delete operations in transactions by default to ensure database data integrity
// You can disable it by setting `SkipDefaultTransaction` to true
SkipDefaultTransaction bool
// NamingStrategy tables, columns naming strategy
NamingStrategy schema.Namer
// FullSaveAssociations full save associations
FullSaveAssociations bool
// Logger
Logger logger.Interface
// NowFunc the function to be used when creating a new timestamp
NowFunc func() time.Time
// DryRun generate sql without execute
DryRun bool
// PrepareStmt executes the given query in cached statement
PrepareStmt bool
// DisableAutomaticPing
DisableAutomaticPing bool
// DisableForeignKeyConstraintWhenMigrating
DisableForeignKeyConstraintWhenMigrating bool
// AllowGlobalUpdate allow global update
AllowGlobalUpdate bool
// QueryFields executes the SQL query with all fields of the table
QueryFields bool
// CreateBatchSize default create batch size
CreateBatchSize int
// ClauseBuilders clause builder
ClauseBuilders map[string]clause.ClauseBuilder
// ConnPool db conn pool
ConnPool ConnPool
// Dialector database dialector
Dialector
// Plugins registered plugins
Plugins map[string]Plugin
callbacks *callbacks
cacheStore *sync.Map
}
跳过默认事务
为了确保数据一致性,GORM 会在事务里执行写入操作(创建、更新、删除)。如果没有这方面的要求,您可以在初始化时禁用它。
db, err := gorm.Open(sqlite.Open(“gorm.db”), &gorm.Config{ SkipDefaultTransaction: true,}) |
---|
命名策略
GORM 允许用户通过覆盖默认的命名策略
更改默认的命名约定,这需要实现接口 Namer
type Namer interface { TableName(table string) string ColumnName(table, column string) string JoinTableName(table string) string RelationshipFKName(Relationship) string CheckerName(table, column string) string IndexName(table, column string) string} |
---|
默认 NamingStrategy
也提供了几个选项,如:
db, err := gorm.Open(sqlite.Open(“gorm.db”), &gorm.Config{ NamingStrategy: schema.NamingStrategy{ TablePrefix: “t_”, // 表名前缀,User 的表名应该是 t_users SingularTable: true, // 使用单数表名,启用该选项,此时,User 的表名应该是 t_user },}) |
---|
Logger
允许通过覆盖此选项更改 GORM 的默认 logger,参考 Logger 获取详情
NowFunc
更改创建时间使用的函数
db, err := gorm.Open(sqlite.Open(“gorm.db”), &gorm.Config{ NowFunc: func() time.Time { return time.Now().Local() },}) |
---|
DryRun
生成 SQL
但不执行,可以用于准备或测试生成的 SQL,参考 会话 获取详情
db, err := gorm.Open(sqlite.Open(“gorm.db”), &gorm.Config{ DryRun: false,}) |
---|
PrepareStmt
PreparedStmt
在执行任何 SQL 时都会创建一个 prepared statement 并将其缓存,以提高后续的效率,参考 会话 获取详情
db, err := gorm.Open(sqlite.Open(“gorm.db”), &gorm.Config{ PrepareStmt: false,}) |
---|
AllowGlobalUpdate
DisableAutomaticPing
在完成初始化后,GORM 会自动 ping 数据库以检查数据库的可用性,若要禁用该特性,可将其设置为 true
db, err := gorm.Open(sqlite.Open(“gorm.db”), &gorm.Config{ DisableAutomaticPing: true,}) |
---|
DisableForeignKeyConstraintWhenMigrating
在 AutoMigrate
或 CreateTable
时,GORM 会自动创建外键约束,若要禁用该特性,可将其设置为 true
,参考 迁移 获取详情。
db, err := gorm.Open(sqlite.Open(“gorm.db”), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true,}) |
---|