Skip to content

Commit

Permalink
Merge pull request #9 from bogunenko/support-select-for-update
Browse files Browse the repository at this point in the history
FEATURE: support SELECT ... FOR UPDATE
  • Loading branch information
bgaifullin committed Dec 8, 2017
2 parents e42ff3f + 89f5d74 commit d8d1fc5
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
11 changes: 11 additions & 0 deletions select.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type SelectStmt struct {

LimitCount int64
OffsetCount int64
IsForUpdate bool
}

// Build builds `SELECT ...` in dialect
Expand Down Expand Up @@ -113,6 +114,10 @@ func (b *SelectStmt) Build(d Dialect, buf Buffer) error {
buf.WriteString(" ")
buf.WriteString(d.Limit(b.OffsetCount, b.LimitCount))
}

if b.IsForUpdate {
buf.WriteString(" FOR UPDATE")
}
return nil
}

Expand Down Expand Up @@ -203,6 +208,12 @@ func (b *SelectStmt) Offset(n uint64) *SelectStmt {
return b
}

// ForUpdate adds `FOR UPDATE`
func (b *SelectStmt) ForUpdate() *SelectStmt {
b.IsForUpdate = true
return b
}

// Join joins table on condition
func (b *SelectStmt) Join(table, on interface{}) *SelectStmt {
b.JoinTable = append(b.JoinTable, join(inner, table, on))
Expand Down
6 changes: 6 additions & 0 deletions select_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,9 @@ func (b *SelectBuilder) Where(query interface{}, value ...interface{}) *SelectBu
b.SelectStmt.Where(query, value...)
return b
}

// ForUpdate adds lock via FOR UPDATE
func (b *SelectBuilder) ForUpdate() *SelectBuilder {
b.SelectStmt.ForUpdate()
return b
}
5 changes: 3 additions & 2 deletions select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ func TestSelectStmt(t *testing.T) {
Having(Eq("e", 2)).
OrderAsc("f").
Limit(3).
Offset(4)
Offset(4).
ForUpdate()
err := builder.Build(dialect.MySQL, buf)
assert.NoError(t, err)
assert.Equal(t, "SELECT DISTINCT a, b FROM ? LEFT JOIN `table2` ON table.a1 = table.a2 WHERE (`c` = ?) GROUP BY d HAVING (`e` = ?) ORDER BY f ASC LIMIT 4,3", buf.String())
assert.Equal(t, "SELECT DISTINCT a, b FROM ? LEFT JOIN `table2` ON table.a1 = table.a2 WHERE (`c` = ?) GROUP BY d HAVING (`e` = ?) ORDER BY f ASC LIMIT 4,3 FOR UPDATE", buf.String())
// two functions cannot be compared
assert.Equal(t, 3, len(buf.Value()))
}
Expand Down

0 comments on commit d8d1fc5

Please sign in to comment.