Skip to content
This repository has been archived by the owner on Jun 14, 2019. It is now read-only.

Commit

Permalink
fix insert sort (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
lunny authored Oct 26, 2018
1 parent ef80bec commit 03eb88f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
23 changes: 20 additions & 3 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,23 @@ func (b *Builder) Or(cond Cond) *Builder {
return b
}

type insertColsSorter struct {
cols []string
vals []interface{}
}

func (s insertColsSorter) Len() int {
return len(s.cols)
}
func (s insertColsSorter) Swap(i, j int) {
s.cols[i], s.cols[j] = s.cols[j], s.cols[i]
s.vals[i], s.vals[j] = s.vals[j], s.vals[i]
}

func (s insertColsSorter) Less(i, j int) bool {
return s.cols[i] < s.cols[j]
}

// Insert sets insert SQL
func (b *Builder) Insert(eq ...interface{}) *Builder {
if len(eq) > 0 {
Expand Down Expand Up @@ -275,10 +292,10 @@ func (b *Builder) Insert(eq ...interface{}) *Builder {
}

if len(b.insertCols) == len(b.insertVals) {
sort.Slice(b.insertVals, func(i, j int) bool {
return b.insertCols[i] < b.insertCols[j]
sort.Sort(insertColsSorter{
cols: b.insertCols,
vals: b.insertVals,
})
sort.Strings(b.insertCols)
}
b.optype = insertType
return b
Expand Down
4 changes: 4 additions & 0 deletions builder_insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ func TestBuilderInsert(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, "INSERT INTO table1 (c,d) Values (1,2)", sql)

sql, err = Insert(Eq{"e": 3}, Eq{"c": 1}, Eq{"d": 2}).Into("table1").ToBoundSQL()
assert.NoError(t, err)
assert.EqualValues(t, "INSERT INTO table1 (c,d,e) Values (1,2,3)", sql)

sql, err = Insert(Eq{"c": 1, "d": Expr("SELECT b FROM t WHERE d=? LIMIT 1", 2)}).Into("table1").ToBoundSQL()
assert.NoError(t, err)
assert.EqualValues(t, "INSERT INTO table1 (c,d) Values (1,(SELECT b FROM t WHERE d=2 LIMIT 1))", sql)
Expand Down

0 comments on commit 03eb88f

Please sign in to comment.