Generates SQL without executing. It can be used to prepare or test generated SQL, for example:
生成SQL而不执行。它可以用于准备或测试生成的SQL,例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
// 会话模式 session mode
stmt:=db.Session(&Session{DryRun:true}).First(&user,1).Statementstmt.SQL.String()//=> SELECT * FROM `users` WHERE `id` = $1 ORDER BY `id`
stmt.Vars//=> []interface{}{1}
// 全局模式下的DryRun globally mode with DryRun
db,err:=gorm.Open(sqlite.Open("gorm.db"),&gorm.Config{DryRun:true})// 不同的数据库生成不同的SQL different databases generate different SQL
stmt:=db.Find(&user,1).Statementstmt.SQL.String()//=> SELECT * FROM `users` WHERE `id` = $1 // PostgreSQL
stmt.SQL.String()//=> SELECT * FROM `users` WHERE `id` = ? // MySQL
stmt.Vars//=> []interface{}{1}
To generate the final SQL, you could use following code:
要生成最终的SQL,可以使用以下代码:
1
2
3
// 注意:SQL并不总是安全的执行,GORM仅用于日志记录,它可能导致SQL注入 NOTE: the SQL is not always safe to execute, GORM only uses it for logs, it might cause SQL injection
db.Dialector.Explain(stmt.SQL.String(),stmt.Vars...)// SELECT * FROM `users` WHERE `id` = 1
PrepareStmt
PreparedStmt creates prepared statements when executing any SQL and caches them to speed up future calls, for example:
// 全局模式下,所有数据库操作将创建预处理语句并缓存它们 globally mode, all DB operations will create prepared statements and cache them
db,err:=gorm.Open(sqlite.Open("gorm.db"),&gorm.Config{PrepareStmt:true,})// 会话模式 session mode
tx:=db.Session(&Session{PrepareStmt:true})tx.First(&user,1)tx.Find(&users)tx.Model(&user).Update("Age",18)// 返回预处理语句管理器 returns prepared statements manager
stmtManger,ok:=tx.ConnPool.(*PreparedStmtDB)// 关闭当前会话的预处理语句 close prepared statements for *current session*
stmtManger.Close()// 当前会话的预处理SQL prepared SQL for *current session*
stmtManger.PreparedSQL// => []string{}
// 当前数据库连接池(所有会话)的预处理语句 prepared statements for current database connection pool (all sessions)
stmtManger.Stmts// map[string]*sql.Stmt
forsql,stmt:=rangestmtManger.Stmts{sql// 预处理SQL prepared SQL
stmt// 预处理语句 prepared statement
stmt.Close()// 关闭预处理语句 close the prepared statement
}
NewDB
Create a new DB without conditions with option NewDB, for example:
创建一个没有条件的新DB,使用选项NewDB,例如:
1
2
3
4
5
6
7
8
9
10
11
12
tx:=db.Where("name = ?","jinzhu").Session(&gorm.Session{NewDB:true})tx.First(&user)// SELECT * FROM users ORDER BY id LIMIT 1
tx.First(&user,"id = ?",10)// SELECT * FROM users WHERE id = 10 ORDER BY id
// 不使用选项`NewDB` Without option `NewDB`
tx2:=db.Where("name = ?","jinzhu").Session(&gorm.Session{})tx2.First(&user)// SELECT * FROM users WHERE name = "jinzhu" ORDER BY id
Initialized
Create a new initialized DB, which is not Method Chain/Goroutine Safe anymore, refer Method Chaining
When using Transaction method inside a DB transaction, GORM will use SavePoint(savedPointName), RollbackTo(savedPointName) to give you the nested transaction support. You can disable it by using the DisableNestedTransaction option, for example:
GORM doesn’t allow global update/delete by default, will return ErrMissingWhereClause error. You can set this option to true to enable it, for example:
db.Session(&gorm.Session{AllowGlobalUpdate:true,}).Model(&User{}).Update("name","jinzhu")// UPDATE users SET `name` = "jinzhu"
FullSaveAssociations
GORM will auto-save associations and its reference using Upsert when creating/updating a record. If you want to update associations’ data, you should use the FullSaveAssociations mode, for example:
db.Session(&gorm.Session{QueryFields:true}).Find(&user)// SELECT `users`.`name`, `users`.`age`, ... FROM `users` // with this option
// SELECT * FROM `users` // without this option
CreateBatchSize
Default batch size
默认批处理大小
1
2
3
4
5
users=[5000]User{{Name:"jinzhu",Pets:[]Pet{pet1,pet2,pet3}}...}db.Session(&gorm.Session{CreateBatchSize:1000}).Create(&users)// INSERT INTO users xxx (5 batches)
// INSERT INTO pets xxx (15 batches)