Files
ginframework/database/query/option_test.go
T
2026-11-28 03:10:18 -08:00

49 lines
1.5 KiB
Go

package query
import (
"strings"
"testing"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// TestForUpdateSQL 验证 MySQL 实际生成的 SQL 尊重布尔开关与显式锁强度,无需连接数据库。
func TestForUpdateSQL(t *testing.T) {
var (
db, err = gorm.Open(mysql.New(mysql.Config{
DSN: "test@tcp(localhost:3306)/test",
SkipInitializeWithVersion: true,
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
)
if err != nil {
t.Fatal(err)
}
for _, test := range []struct {
name string
options []SetOption
lock string
}{
{name: "read_only", options: []SetOption{WithForUpdate(false)}},
{name: "update", options: []SetOption{WithForUpdate(true)}, lock: "FOR UPDATE"},
{name: "explicit_share", options: []SetOption{WithLockingStrength(clause.LockingStrengthShare), WithForUpdate(true)}, lock: "FOR SHARE"},
{name: "false_preserves_explicit_lock", options: []SetOption{WithLockingStrength(clause.LockingStrengthShare), WithForUpdate(false)}, lock: "FOR SHARE"},
} {
t.Run(test.name, func(t *testing.T) {
var (
dao = &BaseDao[migrationRow, migrationColumns]{}
row migrationRow
statement = dao.setTxCondition(db, test.options...).Take(&row).Statement
sql = statement.SQL.String()
)
if test.lock == "" && strings.Contains(sql, "FOR ") || test.lock != "" && !strings.HasSuffix(sql, test.lock) {
t.Fatalf("SQL = %s, want lock %q", sql, test.lock)
}
})
}
}