From cc3ebd34de7b6b9032fb2b706c921415045617de Mon Sep 17 00:00:00 2001 From: Paolo Galeone Date: Mon, 28 Apr 2014 22:37:45 +0200 Subject: [PATCH] Add support to fields with double quotes --- main_test.go | 21 ++++++++++++++++----- search.go | 3 ++- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/main_test.go b/main_test.go index 732ba55f..ac47372f 100644 --- a/main_test.go +++ b/main_test.go @@ -7,9 +7,10 @@ import ( "fmt" _ "github.com/go-sql-driver/mysql" - "github.com/jinzhu/gorm" + // "github.com/jinzhu/gorm" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" + "github.com/nerdzeu/gorm" "os" "reflect" @@ -130,6 +131,7 @@ type Product struct { type Animal struct { Counter int64 `primaryKey:"yes"` Name string + From string //test reserverd sql keyword as field name CreatedAt time.Time UpdatedAt time.Time } @@ -223,10 +225,10 @@ func init() { db.Save(&User{Name: "3", Age: 24, Birthday: t4}) db.Save(&User{Name: "5", Age: 26, Birthday: t4}) - db.Save(&Animal{Name: "First"}) - db.Save(&Animal{Name: "Amazing"}) - db.Save(&Animal{Name: "Horse"}) - db.Save(&Animal{Name: "Last"}) + db.Save(&Animal{Name: "First", From: "hello"}) + db.Save(&Animal{Name: "Amazing", From: "nerdz"}) + db.Save(&Animal{Name: "Horse", From: "gorm"}) + db.Save(&Animal{Name: "Last", From: "epic"}) } func TestFirstAndLast(t *testing.T) { @@ -1998,3 +2000,12 @@ func BenchmarkRawSql(b *testing.B) { db.Exec(delete_sql, id) } } + +func TestSelectWithEscapedFieldName(t *testing.T) { + var names []string + db.Model(Animal{}).Where(&Animal{From: "nerdz"}).Pluck("\"name\"", &names) + + if len(names) != 1 { + t.Errorf("Expected one name, but got: %d", len(names)) + } +} diff --git a/search.go b/search.go index 833208ca..ec47bee2 100644 --- a/search.go +++ b/search.go @@ -141,7 +141,8 @@ func (s *search) getInterfaceAsSql(value interface{}) (str string) { s.db.err(InvalidSql) } - if !regexp.MustCompile("^\\s*[\\w\\s,.*\\+\\-()]*\\s*$").MatchString(str) { + // Support field name with and without double quotes (useful when a field has a sql reserved word name) + if !regexp.MustCompile("^(\\s*\"[\\w\\s,.*\\+\\-()]*\"\\s*)$|^(\\s*\"?[\\w\\s,.*\\+\\-()]*\"?\\s*)$").MatchString(str) { s.db.err(InvalidSql) } return