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) {