Replace For with Locking

This commit is contained in:
Jinzhu 2020-06-06 21:35:28 +08:00
parent 52b763aab3
commit 38d1cd2bf1
2 changed files with 17 additions and 42 deletions

View File

@ -1,9 +1,5 @@
package clause package clause
type For struct {
Lockings []Locking
}
type Locking struct { type Locking struct {
Strength string Strength string
Table Table Table Table
@ -11,18 +7,12 @@ type Locking struct {
} }
// Name where clause name // Name where clause name
func (f For) Name() string { func (locking Locking) Name() string {
return "FOR" return "FOR"
} }
// Build build where clause // Build build where clause
func (f For) Build(builder Builder) { func (locking Locking) Build(builder Builder) {
for idx, locking := range f.Lockings {
if idx > 0 {
builder.WriteByte(' ')
}
builder.WriteString("FOR ")
builder.WriteString(locking.Strength) builder.WriteString(locking.Strength)
if locking.Table.Name != "" { if locking.Table.Name != "" {
builder.WriteString(" OF ") builder.WriteString(" OF ")
@ -33,16 +23,9 @@ func (f For) Build(builder Builder) {
builder.WriteByte(' ') builder.WriteByte(' ')
builder.WriteString(locking.Options) builder.WriteString(locking.Options)
} }
}
} }
// MergeClause merge order by clauses // MergeClause merge order by clauses
func (f For) MergeClause(clause *Clause) { func (locking Locking) MergeClause(clause *Clause) {
clause.Name = "" clause.Expression = locking
if v, ok := clause.Expression.(For); ok {
f.Lockings = append(v.Lockings, f.Lockings...)
}
clause.Expression = f
} }

View File

@ -14,24 +14,16 @@ func TestFor(t *testing.T) {
Vars []interface{} Vars []interface{}
}{ }{
{ {
[]clause.Interface{clause.Select{}, clause.From{}, clause.For{ []clause.Interface{clause.Select{}, clause.From{}, clause.Locking{Strength: "UPDATE"}},
Lockings: []clause.Locking{{Strength: "UPDATE"}},
}},
"SELECT * FROM `users` FOR UPDATE", nil, "SELECT * FROM `users` FOR UPDATE", nil,
}, },
{ {
[]clause.Interface{clause.Select{}, clause.From{}, clause.For{ []clause.Interface{clause.Select{}, clause.From{}, clause.Locking{Strength: "SHARE", Table: clause.Table{Name: clause.CurrentTable}}},
Lockings: []clause.Locking{{Strength: "UPDATE"}, {Strength: "SHARE", Table: clause.Table{Name: clause.CurrentTable}}}, "SELECT * FROM `users` FOR SHARE OF `users`", nil,
}},
"SELECT * FROM `users` FOR UPDATE FOR SHARE OF `users`", nil,
}, },
{ {
[]clause.Interface{clause.Select{}, clause.From{}, clause.For{ []clause.Interface{clause.Select{}, clause.From{}, clause.Locking{Strength: "UPDATE"}, clause.Locking{Strength: "UPDATE", Options: "NOWAIT"}},
Lockings: []clause.Locking{{Strength: "UPDATE"}, {Strength: "SHARE", Table: clause.Table{Name: clause.CurrentTable}}}, "SELECT * FROM `users` FOR UPDATE NOWAIT", nil,
}, clause.For{
Lockings: []clause.Locking{{Strength: "UPDATE", Options: "NOWAIT"}},
}},
"SELECT * FROM `users` FOR UPDATE FOR SHARE OF `users` FOR UPDATE NOWAIT", nil,
}, },
} }