Skip to content

Commit

Permalink
Fixed column order (#430)
Browse files Browse the repository at this point in the history
* Add test to demonstrate INSERT fails with a suffix on quoted column name #429

* Ensure columns are sorted the same way each time.
  • Loading branch information
duckbrain authored and stanislas-m committed Aug 27, 2019
1 parent 29f3fda commit 535a7bd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
30 changes: 17 additions & 13 deletions columns/columns.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,37 +118,41 @@ func (c Columns) Readable() *ReadableColumns {
return w
}

// colNames returns a slice of column names in a deterministic order
func (c Columns) colNames() []string {
var xs []string
for _, t := range c.Cols {
xs = append(xs, t.Name)
}
sort.Strings(xs)
return xs
}

type quoter interface {
Quote(key string) string
}

// QuotedString gives the columns list quoted with the given quoter function.
func (c Columns) QuotedString(quoter quoter) string {
var xs []string
for _, t := range c.Cols {
xs = append(xs, quoter.Quote(t.Name))
xs := c.colNames()
for i, n := range xs {
xs[i] = quoter.Quote(n)
}
sort.Strings(xs)
return strings.Join(xs, ", ")
}

func (c Columns) String() string {
var xs []string
for _, t := range c.Cols {
xs = append(xs, t.Name)
}
sort.Strings(xs)
xs := c.colNames()
return strings.Join(xs, ", ")
}

// SymbolizedString returns a list of tokens (:token) to bind
// a value to an INSERT query.
func (c Columns) SymbolizedString() string {
var xs []string
for _, t := range c.Cols {
xs = append(xs, ":"+t.Name)
xs := c.colNames()
for i, n := range xs {
xs[i] = ":" + n
}
sort.Strings(xs)
return strings.Join(xs, ", ")
}

Expand Down
21 changes: 21 additions & 0 deletions columns/columns_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package columns_test

import (
"fmt"
"testing"

"github.com/gobuffalo/pop/columns"
Expand Down Expand Up @@ -60,3 +61,23 @@ func Test_Columns_Remove(t *testing.T) {
r.Equal(len(c.Cols), 3)
}
}

type fooWithSuffix struct {
Amount float64 `db:"amount"`
AmountUnits string `db:"amount_units"`
}
type fooQuoter struct{}

func (fooQuoter) Quote(key string) string {
return fmt.Sprintf("`%v`", key)
}

func Test_Columns_Sorted(t *testing.T) {
r := require.New(t)

c := columns.ForStruct(fooWithSuffix{}, "fooWithSuffix")
r.Equal(len(c.Cols), 2)
r.Equal(c.SymbolizedString(), ":amount, :amount_units")
r.Equal(c.String(), "amount, amount_units")
r.Equal(c.QuotedString(fooQuoter{}), "`amount`, `amount_units`")
}

0 comments on commit 535a7bd

Please sign in to comment.