From 03eb88feccce3e477c318ce7f6f1b386544ab20b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 26 Oct 2018 13:37:58 +0800 Subject: [PATCH] fix insert sort (#42) --- builder.go | 23 ++++++++++++++++++++--- builder_insert_test.go | 4 ++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/builder.go b/builder.go index 14e79de..ffe86d4 100644 --- a/builder.go +++ b/builder.go @@ -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 { @@ -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 diff --git a/builder_insert_test.go b/builder_insert_test.go index 5ea8662..ef3db52 100644 --- a/builder_insert_test.go +++ b/builder_insert_test.go @@ -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)