Change to IdentQuote, add IdentQuote to Select QM

This commit is contained in:
Patrick O'brien 2016-08-02 13:25:02 +10:00
parent b171fd42ba
commit fb8540af1a
5 changed files with 16 additions and 8 deletions

View file

@ -1 +1 @@
SELECT "count(*) as ab, thing as bd","stuff" FROM "t";
SELECT count(*) as ab, thing as bd, "stuff" FROM "t";

View file

@ -5,6 +5,8 @@ import (
"database/sql"
"fmt"
"strings"
"github.com/nullbio/sqlboiler/strmangle"
)
type where struct {
@ -71,7 +73,7 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
buf.WriteString("COUNT(")
}
if len(q.selectCols) > 0 {
buf.WriteString(`"` + strings.Join(q.selectCols, `","`) + `"`)
buf.WriteString(strings.Join(q.selectCols, `, `))
} else {
buf.WriteByte('*')
}
@ -177,6 +179,10 @@ func SetExecutor(q *Query, exec Executor) {
// SetSelect on the query.
func SetSelect(q *Query, columns ...string) {
for i := 0; i < len(columns); i++ {
columns[i] = strmangle.IdentQuote(columns[i])
}
q.selectCols = append(q.selectCols, columns...)
}

View file

@ -29,7 +29,7 @@ func TestBuildQuery(t *testing.T) {
{&Query{from: "t"}, nil},
{&Query{from: "q", limit: 5, offset: 6}, nil},
{&Query{from: "q", orderBy: []string{"a ASC", "b DESC"}}, nil},
{&Query{from: "t", selectCols: []string{"count(*) as ab, thing as bd", "stuff"}}, nil},
{&Query{from: "t", selectCols: []string{"count(*) as ab, thing as bd", `"stuff"`}}, nil},
}
for i, test := range tests {
@ -252,7 +252,7 @@ func TestSetSelect(t *testing.T) {
t.Errorf("Expected selectCols len 2, got %d", len(q.selectCols))
}
if q.selectCols[0] != "col1" && q.selectCols[1] != "col2" {
if q.selectCols[0] != `"col1"` && q.selectCols[1] != `"col2"` {
t.Errorf("select cols value mismatch: %#v", q.selectCols)
}
}

View file

@ -19,8 +19,8 @@ var (
smartQuoteRgx = regexp.MustCompile(`^(?i)"?[a-z_][_a-z0-9]*"?(\."?[_a-z][_a-z0-9]*"?)*$`)
)
// SmartQuote intelligently quotes identifiers in sql statements
func SmartQuote(s string) string {
// IdentQuote attempts to quote simple identifiers in SQL tatements
func IdentQuote(s string) string {
if s == "null" {
return s
}

View file

@ -5,7 +5,7 @@ import (
"testing"
)
func TestSmartQuote(t *testing.T) {
func TestIdentQuote(t *testing.T) {
t.Parallel()
tests := []struct {
@ -16,14 +16,16 @@ func TestSmartQuote(t *testing.T) {
{In: `null`, Out: `null`},
{In: `"thing"`, Out: `"thing"`},
{In: `*`, Out: `*`},
{In: ``, Out: ``},
{In: `thing.thing`, Out: `"thing"."thing"`},
{In: `"thing"."thing"`, Out: `"thing"."thing"`},
{In: `thing.thing.thing.thing`, Out: `"thing"."thing"."thing"."thing"`},
{In: `thing."thing".thing."thing"`, Out: `"thing"."thing"."thing"."thing"`},
{In: `count(*) as ab, thing as bd`, Out: `count(*) as ab, thing as bd`},
}
for _, test := range tests {
if got := SmartQuote(test.In); got != test.Out {
if got := IdentQuote(test.In); got != test.Out {
t.Errorf("want: %s, got: %s", test.Out, got)
}
}