From 5330572c258c16742c3052af3f82f67031112f2e Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 20 Jan 2015 12:15:24 +0800 Subject: [PATCH] Fix Exec with raw string --- main.go | 5 ++++- mysql.go | 2 +- scope_private.go | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 3fd42ff2..11929ce1 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "reflect" + "strings" "time" ) @@ -287,7 +288,9 @@ func (s *DB) Raw(sql string, values ...interface{}) *DB { func (s *DB) Exec(sql string, values ...interface{}) *DB { scope := s.clone().NewScope(nil) - scope.Raw(scope.buildWhereCondition(map[string]interface{}{"query": sql, "args": values})) + generatedSql := scope.buildWhereCondition(map[string]interface{}{"query": sql, "args": values}) + generatedSql = strings.TrimSuffix(strings.TrimPrefix(generatedSql, "("), ")") + scope.Raw(generatedSql) return scope.Exec().db } diff --git a/mysql.go b/mysql.go index 666bb0aa..9635507e 100644 --- a/mysql.go +++ b/mysql.go @@ -38,7 +38,7 @@ func (d *mysql) SqlTag(value reflect.Value, size int) string { } case reflect.Struct: if value.Type() == timeType { - return "timestamp" + return "timestamp NULL" } default: if _, ok := value.Interface().([]byte); ok { diff --git a/scope_private.go b/scope_private.go index 2d5f3ff4..b3439c57 100644 --- a/scope_private.go +++ b/scope_private.go @@ -23,7 +23,7 @@ func (scope *Scope) buildWhereCondition(clause map[string]interface{}) (str stri if regexp.MustCompile("^\\s*\\d+\\s*$").MatchString(value) { id, _ := strconv.Atoi(value) return scope.primaryCondiation(scope.AddToVars(id)) - } else { + } else if value != "" { str = fmt.Sprintf("(%v)", value) } case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: @@ -300,7 +300,7 @@ func (s *Scope) joinsSql() string { func (scope *Scope) prepareQuerySql() { if scope.Search.Raw { - scope.Raw(strings.TrimLeft(scope.CombinedConditionSql(), "WHERE ")) + scope.Raw(strings.TrimRight(strings.TrimLeft(scope.CombinedConditionSql(), "WHERE ("), ")")) } else { scope.Raw(fmt.Sprintf("SELECT %v %v FROM %v %v", scope.topSql(), scope.selectSql(), scope.QuotedTableName(), scope.CombinedConditionSql())) }