Skip to content

Commit afc9671

Browse files
duckbrainstanislas-m
authored andcommitted
Fixed column order (gobuffalo#430)
* Add test to demonstrate INSERT fails with a suffix on quoted column name gobuffalo#429 * Ensure columns are sorted the same way each time.
1 parent 8622069 commit afc9671

File tree

2 files changed

+38
-13
lines changed

2 files changed

+38
-13
lines changed

columns/columns.go

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -118,37 +118,41 @@ func (c Columns) Readable() *ReadableColumns {
118118
return w
119119
}
120120

121+
// colNames returns a slice of column names in a deterministic order
122+
func (c Columns) colNames() []string {
123+
var xs []string
124+
for _, t := range c.Cols {
125+
xs = append(xs, t.Name)
126+
}
127+
sort.Strings(xs)
128+
return xs
129+
}
130+
121131
type quoter interface {
122132
Quote(key string) string
123133
}
124134

125135
// QuotedString gives the columns list quoted with the given quoter function.
126136
func (c Columns) QuotedString(quoter quoter) string {
127-
var xs []string
128-
for _, t := range c.Cols {
129-
xs = append(xs, quoter.Quote(t.Name))
137+
xs := c.colNames()
138+
for i, n := range xs {
139+
xs[i] = quoter.Quote(n)
130140
}
131-
sort.Strings(xs)
132141
return strings.Join(xs, ", ")
133142
}
134143

135144
func (c Columns) String() string {
136-
var xs []string
137-
for _, t := range c.Cols {
138-
xs = append(xs, t.Name)
139-
}
140-
sort.Strings(xs)
145+
xs := c.colNames()
141146
return strings.Join(xs, ", ")
142147
}
143148

144149
// SymbolizedString returns a list of tokens (:token) to bind
145150
// a value to an INSERT query.
146151
func (c Columns) SymbolizedString() string {
147-
var xs []string
148-
for _, t := range c.Cols {
149-
xs = append(xs, ":"+t.Name)
152+
xs := c.colNames()
153+
for i, n := range xs {
154+
xs[i] = ":" + n
150155
}
151-
sort.Strings(xs)
152156
return strings.Join(xs, ", ")
153157
}
154158

columns/columns_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package columns_test
22

33
import (
4+
"fmt"
45
"testing"
56

67
"github.com/gobuffalo/pop/columns"
@@ -60,3 +61,23 @@ func Test_Columns_Remove(t *testing.T) {
6061
r.Equal(len(c.Cols), 3)
6162
}
6263
}
64+
65+
type fooWithSuffix struct {
66+
Amount float64 `db:"amount"`
67+
AmountUnits string `db:"amount_units"`
68+
}
69+
type fooQuoter struct{}
70+
71+
func (fooQuoter) Quote(key string) string {
72+
return fmt.Sprintf("`%v`", key)
73+
}
74+
75+
func Test_Columns_Sorted(t *testing.T) {
76+
r := require.New(t)
77+
78+
c := columns.ForStruct(fooWithSuffix{}, "fooWithSuffix")
79+
r.Equal(len(c.Cols), 2)
80+
r.Equal(c.SymbolizedString(), ":amount, :amount_units")
81+
r.Equal(c.String(), "amount, amount_units")
82+
r.Equal(c.QuotedString(fooQuoter{}), "`amount`, `amount_units`")
83+
}

0 commit comments

Comments
 (0)