From 8a88d665d5a7c7b6a03e8cf8b6b300aa57e70be1 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 1 Aug 2015 09:25:06 +0800 Subject: [PATCH] Add QuoteIfPossible for Scope --- scope.go | 8 ++++++++ scope_private.go | 8 ++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/scope.go b/scope.go index cd6b235d..104a3728 100644 --- a/scope.go +++ b/scope.go @@ -3,6 +3,7 @@ package gorm import ( "errors" "fmt" + "regexp" "strings" "time" @@ -87,6 +88,13 @@ func (scope *Scope) Quote(str string) string { } } +func (scope *Scope) QuoteIfPossible(str string) string { + if regexp.MustCompile("^[a-zA-Z]+(.[a-zA-Z]+)*$").MatchString(str) { + return scope.Quote(str) + } + return str +} + // Dialect get dialect func (scope *Scope) Dialect() Dialect { return scope.db.parent.dialect diff --git a/scope_private.go b/scope_private.go index e440f7a4..e22a726a 100644 --- a/scope_private.go +++ b/scope_private.go @@ -531,11 +531,7 @@ func (scope *Scope) addIndex(unique bool, indexName string, column ...string) { var columns []string for _, name := range column { - if regexp.MustCompile("^[a-zA-Z]+$").MatchString(name) { - columns = append(columns, scope.Quote(name)) - } else { - columns = append(columns, name) - } + columns = append(columns, scope.QuoteIfPossible(name)) } sqlCreate := "CREATE INDEX" @@ -550,7 +546,7 @@ func (scope *Scope) addForeignKey(field string, dest string, onDelete string, on var table = scope.TableName() var keyName = fmt.Sprintf("%s_%s_foreign", table, field) var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;` - scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.Quote(keyName), scope.Quote(field), scope.Quote(dest), onDelete, onUpdate)).Exec() + scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.QuoteIfPossible(keyName), scope.QuoteIfPossible(field), scope.QuoteIfPossible(dest), onDelete, onUpdate)).Exec() } func (scope *Scope) removeIndex(indexName string) {