Add QuoteIfPossible for Scope

This commit is contained in:
Jinzhu 2015-08-01 09:25:06 +08:00
parent fa86433142
commit 8a88d665d5
2 changed files with 10 additions and 6 deletions

View File

@ -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

View File

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