Session

GORM 提供 Session 方法,這是一個 New Session Method,它允許使用設定檔建立新的 session 模式

// Session Configuration
type Session struct {
DryRun bool
PrepareStmt bool
NewDB bool
Initialized bool
SkipHooks bool
SkipDefaultTransaction bool
DisableNestedTransaction bool
AllowGlobalUpdate bool
FullSaveAssociations bool
QueryFields bool
Context context.Context
Logger logger.Interface
NowFunc func() time.Time
CreateBatchSize int
}

DryRun

產生 SQL 但不執行。它可用於準備或測試產生的 SQL,例如

// session mode
stmt := db.Session(&Session{DryRun: true}).First(&user, 1).Statement
stmt.SQL.String() //=> SELECT * FROM `users` WHERE `id` = $1 ORDER BY `id`
stmt.Vars //=> []interface{}{1}

// globally mode with DryRun
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{DryRun: true})

// different databases generate different SQL
stmt := db.Find(&user, 1).Statement
stmt.SQL.String() //=> SELECT * FROM `users` WHERE `id` = $1 // PostgreSQL
stmt.SQL.String() //=> SELECT * FROM `users` WHERE `id` = ? // MySQL
stmt.Vars //=> []interface{}{1}

若要產生最終的 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 在執行任何 SQL 時建立準備好的陳述式,並將它們快取以加快後續的呼叫,例如

// 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()

// prepared SQL for *current session*
stmtManger.PreparedSQL // => []string{}

// prepared statements for current database connection pool (all sessions)
stmtManger.Stmts // map[string]*sql.Stmt

for sql, stmt := range stmtManger.Stmts {
sql // prepared SQL
stmt // prepared statement
stmt.Close() // close the prepared statement
}

NewDB

使用選項 NewDB 建立一個沒有條件的新 DB,例如

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

// Without option `NewDB`
tx2 := db.Where("name = ?", "jinzhu").Session(&gorm.Session{})
tx2.First(&user)
// SELECT * FROM users WHERE name = "jinzhu" ORDER BY id

Initialized

建立一個新的已初始化的 DB,它不再是方法鏈/Goroutine 安全,請參閱 方法鏈

tx := db.Session(&gorm.Session{Initialized: true})

Skip Hooks

如果您想略過 Hooks 方法,可以使用 SkipHooks session 模式,例如

DB.Session(&gorm.Session{SkipHooks: true}).Create(&user)

DB.Session(&gorm.Session{SkipHooks: true}).Create(&users)

DB.Session(&gorm.Session{SkipHooks: true}).CreateInBatches(users, 100)

DB.Session(&gorm.Session{SkipHooks: true}).Find(&user)

DB.Session(&gorm.Session{SkipHooks: true}).Delete(&user)

DB.Session(&gorm.Session{SkipHooks: true}).Model(User{}).Where("age > ?", 18).Updates(&user)

DisableNestedTransaction

在 DB 交易中使用 Transaction 方法時,GORM 會使用 SavePoint(savedPointName)RollbackTo(savedPointName) 為您提供巢狀交易支援。您可以使用 DisableNestedTransaction 選項來停用它,例如

db.Session(&gorm.Session{
DisableNestedTransaction: true,
}).CreateInBatches(&users, 100)

AllowGlobalUpdate

GORM 預設不允許全域更新/刪除,會傳回 ErrMissingWhereClause 錯誤。您可以將此選項設定為 true 以啟用它,例如

db.Session(&gorm.Session{
AllowGlobalUpdate: true,
}).Model(&User{}).Update("name", "jinzhu")
// UPDATE users SET `name` = "jinzhu"

FullSaveAssociations

建立/更新記錄時,GORM 會使用 Upsert 自動儲存關聯和其參考。如果您想更新關聯資料,您應該使用 FullSaveAssociations 模式,例如

db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user)
// ...
// INSERT INTO "addresses" (address1) VALUES ("Billing Address - Address 1"), ("Shipping Address - Address 1") ON DUPLICATE KEY SET address1=VALUES(address1);
// INSERT INTO "users" (name,billing_address_id,shipping_address_id) VALUES ("jinzhu", 1, 2);
// INSERT INTO "emails" (user_id,email) VALUES (111, "jinzhu@example.com"), (111, "jinzhu-2@example.com") ON DUPLICATE KEY SET email=VALUES(email);
// ...

Context

使用 Context 選項,您可以設定後續 SQL 作業的 Context,例如

timeoutCtx, _ := context.WithTimeout(context.Background(), time.Second)
tx := db.Session(&Session{Context: timeoutCtx})

tx.First(&user) // query with context timeoutCtx
tx.Model(&user).Update("role", "admin") // update with context timeoutCtx

GORM 也提供捷徑方法 WithContext,以下是定義

func (db *DB) WithContext(ctx context.Context) *DB {
return db.Session(&Session{Context: ctx})
}

Logger

Gorm 允許使用 Logger 選項自訂內建記錄器,例如

newLogger := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
SlowThreshold: time.Second,
LogLevel: logger.Silent,
Colorful: false,
})
db.Session(&Session{Logger: newLogger})

db.Session(&Session{Logger: logger.Default.LogMode(logger.Silent)})

查看 記錄器 以取得更多詳細資訊。

NowFunc

NowFunc 允許變更 GORM 取得目前時間的函式,例如

db.Session(&Session{
NowFunc: func() time.Time {
return time.Now().Local()
},
})

Debug

Debug 是變更 session 的 Logger 至偵錯模式的捷徑方法,以下是定義

func (db *DB) Debug() (tx *DB) {
return db.Session(&Session{
Logger: db.Logger.LogMode(logger.Info),
})
}

QueryFields

依欄位選取

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

預設批次大小

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)

白金贊助商

金牌贊助商

白金贊助商

金牌贊助商