1

本文主要研究一下gorm的Locking

Locking

gorm.io/gorm@v1.20.11/clause/locking.go

type Locking struct {
    Strength string
    Table    Table
    Options  string
}

// Name where clause name
func (locking Locking) Name() string {
    return "FOR"
}

// Build build where clause
func (locking Locking) Build(builder Builder) {
    builder.WriteString(locking.Strength)
    if locking.Table.Name != "" {
        builder.WriteString(" OF ")
        builder.WriteQuoted(locking.Table)
    }

    if locking.Options != "" {
        builder.WriteByte(' ')
        builder.WriteString(locking.Options)
    }
}

// MergeClause merge order by clauses
func (locking Locking) MergeClause(clause *Clause) {
    clause.Expression = locking
}
Locking定义了Strength、Table、Options属性;Build方法先追加Strength,后面根据Table、Options属性追加语句

实例

func TestLocking(t *testing.T) {
    results := []struct {
        Clauses []clause.Interface
        Result  string
        Vars    []interface{}
    }{
        {
            []clause.Interface{clause.Select{}, clause.From{}, clause.Locking{Strength: "UPDATE"}},
            "SELECT * FROM `users` FOR UPDATE", nil,
        },
        {
            []clause.Interface{clause.Select{}, clause.From{}, clause.Locking{Strength: "SHARE", Table: clause.Table{Name: clause.CurrentTable}}},
            "SELECT * FROM `users` FOR SHARE OF `users`", nil,
        },
        {
            []clause.Interface{clause.Select{}, clause.From{}, clause.Locking{Strength: "UPDATE"}, clause.Locking{Strength: "UPDATE", Options: "NOWAIT"}},
            "SELECT * FROM `users` FOR UPDATE NOWAIT", nil,
        },
    }

    for idx, result := range results {
        t.Run(fmt.Sprintf("case #%v", idx), func(t *testing.T) {
            checkBuildClauses(t, result.Clauses, result.Result, result.Vars)
        })
    }
}

小结

Locking定义了Strength、Table、Options属性;Build方法先追加Strength,后面根据Table、Options属性追加语句;Strength支持SHARE、UPDATE;Options支持NOWAIT。

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...