gorm/scope_private.go

671 lines
20 KiB
Go
Raw Normal View History

2014-01-26 10:55:41 +04:00
package gorm
import (
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
2016-01-13 09:58:30 +03:00
"time"
2014-01-26 10:55:41 +04:00
)
2015-02-11 22:14:34 +03:00
func (scope *Scope) primaryCondition(value interface{}) string {
2014-01-28 12:22:41 +04:00
return fmt.Sprintf("(%v = %v)", scope.Quote(scope.PrimaryKey()), value)
2014-01-26 10:55:41 +04:00
}
func (scope *Scope) buildWhereCondition(clause map[string]interface{}) (str string) {
switch value := clause["query"].(type) {
case string:
// if string is number
if regexp.MustCompile("^\\s*\\d+\\s*$").MatchString(value) {
return scope.primaryCondition(scope.AddToVars(value))
2015-01-20 07:15:24 +03:00
} else if value != "" {
2015-01-20 06:16:41 +03:00
str = fmt.Sprintf("(%v)", value)
2014-01-26 10:55:41 +04:00
}
2015-02-17 17:55:14 +03:00
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, sql.NullInt64:
2015-02-11 22:14:34 +03:00
return scope.primaryCondition(scope.AddToVars(value))
case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []string, []interface{}:
2016-02-08 14:22:46 +03:00
str = fmt.Sprintf("(%v IN (?))", scope.Quote(scope.PrimaryKey()))
2014-01-26 10:55:41 +04:00
clause["args"] = []interface{}{value}
case map[string]interface{}:
var sqls []string
for key, value := range value {
if value != nil {
sqls = append(sqls, fmt.Sprintf("(%v = %v)", scope.Quote(key), scope.AddToVars(value)))
} else {
sqls = append(sqls, fmt.Sprintf("(%v IS NULL)", scope.Quote(key)))
}
2014-01-26 10:55:41 +04:00
}
return strings.Join(sqls, " AND ")
case interface{}:
var sqls []string
2014-01-28 05:25:30 +04:00
for _, field := range scope.New(value).Fields() {
if !field.IsIgnored && !field.IsBlank {
2014-09-02 15:03:01 +04:00
sqls = append(sqls, fmt.Sprintf("(%v = %v)", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
2014-01-28 05:25:30 +04:00
}
2014-01-26 10:55:41 +04:00
}
return strings.Join(sqls, " AND ")
}
args := clause["args"].([]interface{})
for _, arg := range args {
2015-03-06 05:48:13 +03:00
switch reflect.ValueOf(arg).Kind() {
2014-01-26 10:55:41 +04:00
case reflect.Slice: // For where("id in (?)", []int64{1,2})
2016-01-03 15:23:37 +03:00
if bytes, ok := arg.([]byte); ok {
2016-01-03 15:29:46 +03:00
str = strings.Replace(str, "?", scope.AddToVars(bytes), 1)
2016-02-08 14:22:46 +03:00
} else if values := reflect.ValueOf(arg); values.Len() > 0 {
2016-01-03 15:23:37 +03:00
var tempMarks []string
for i := 0; i < values.Len(); i++ {
tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
}
str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 1)
2016-02-08 14:22:46 +03:00
} else {
str = strings.Replace(str, "?", scope.AddToVars(Expr("NULL")), 1)
2014-01-26 10:55:41 +04:00
}
default:
if valuer, ok := interface{}(arg).(driver.Valuer); ok {
arg, _ = valuer.Value()
}
str = strings.Replace(str, "?", scope.AddToVars(arg), 1)
}
}
return
}
func (scope *Scope) buildNotCondition(clause map[string]interface{}) (str string) {
2016-03-07 09:54:20 +03:00
var notEqualSQL string
2015-02-17 17:55:14 +03:00
var primaryKey = scope.PrimaryKey()
2014-01-26 10:55:41 +04:00
switch value := clause["query"].(type) {
case string:
2015-02-17 17:55:14 +03:00
// is number
2014-01-26 10:55:41 +04:00
if regexp.MustCompile("^\\s*\\d+\\s*$").MatchString(value) {
id, _ := strconv.Atoi(value)
2015-02-17 17:55:14 +03:00
return fmt.Sprintf("(%v <> %v)", scope.Quote(primaryKey), id)
2016-02-08 14:22:46 +03:00
} else if regexp.MustCompile("(?i) (=|<>|>|<|LIKE|IS|IN) ").MatchString(value) {
2014-01-26 10:55:41 +04:00
str = fmt.Sprintf(" NOT (%v) ", value)
2016-03-07 09:54:20 +03:00
notEqualSQL = fmt.Sprintf("NOT (%v)", value)
2014-01-26 10:55:41 +04:00
} else {
2014-01-28 12:22:41 +04:00
str = fmt.Sprintf("(%v NOT IN (?))", scope.Quote(value))
2016-03-07 09:54:20 +03:00
notEqualSQL = fmt.Sprintf("(%v <> ?)", scope.Quote(value))
2014-01-26 10:55:41 +04:00
}
2015-02-17 17:55:14 +03:00
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, sql.NullInt64:
return fmt.Sprintf("(%v <> %v)", scope.Quote(primaryKey), value)
case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []string:
2014-01-26 10:55:41 +04:00
if reflect.ValueOf(value).Len() > 0 {
2015-02-17 17:55:14 +03:00
str = fmt.Sprintf("(%v NOT IN (?))", scope.Quote(primaryKey))
2014-01-26 10:55:41 +04:00
clause["args"] = []interface{}{value}
}
2015-02-17 17:55:14 +03:00
return ""
2014-01-26 10:55:41 +04:00
case map[string]interface{}:
var sqls []string
for key, value := range value {
if value != nil {
sqls = append(sqls, fmt.Sprintf("(%v <> %v)", scope.Quote(key), scope.AddToVars(value)))
} else {
sqls = append(sqls, fmt.Sprintf("(%v IS NOT NULL)", scope.Quote(key)))
}
2014-01-26 10:55:41 +04:00
}
return strings.Join(sqls, " AND ")
case interface{}:
var sqls []string
2014-01-28 05:25:30 +04:00
for _, field := range scope.New(value).Fields() {
if !field.IsBlank {
2014-09-02 15:03:01 +04:00
sqls = append(sqls, fmt.Sprintf("(%v <> %v)", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
2014-01-28 05:25:30 +04:00
}
2014-01-26 10:55:41 +04:00
}
return strings.Join(sqls, " AND ")
}
args := clause["args"].([]interface{})
for _, arg := range args {
2015-03-06 05:48:13 +03:00
switch reflect.ValueOf(arg).Kind() {
2014-01-26 10:55:41 +04:00
case reflect.Slice: // For where("id in (?)", []int64{1,2})
2016-02-08 14:22:46 +03:00
if bytes, ok := arg.([]byte); ok {
str = strings.Replace(str, "?", scope.AddToVars(bytes), 1)
} else if values := reflect.ValueOf(arg); values.Len() > 0 {
var tempMarks []string
for i := 0; i < values.Len(); i++ {
tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
}
str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 1)
} else {
str = strings.Replace(str, "?", scope.AddToVars(Expr("NULL")), 1)
2014-01-26 10:55:41 +04:00
}
default:
if scanner, ok := interface{}(arg).(driver.Valuer); ok {
arg, _ = scanner.Value()
}
2016-03-07 09:54:20 +03:00
str = strings.Replace(notEqualSQL, "?", scope.AddToVars(arg), 1)
2014-01-26 10:55:41 +04:00
}
}
return
}
func (scope *Scope) buildSelectQuery(clause map[string]interface{}) (str string) {
switch value := clause["query"].(type) {
case string:
str = value
case []string:
str = strings.Join(value, ", ")
}
args := clause["args"].([]interface{})
for _, arg := range args {
2015-03-06 05:48:13 +03:00
switch reflect.ValueOf(arg).Kind() {
case reflect.Slice:
values := reflect.ValueOf(arg)
var tempMarks []string
for i := 0; i < values.Len(); i++ {
tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
}
str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 1)
default:
if valuer, ok := interface{}(arg).(driver.Valuer); ok {
arg, _ = valuer.Value()
}
2015-08-01 06:49:34 +03:00
str = strings.Replace(str, "?", scope.AddToVars(arg), 1)
}
}
return
}
2016-03-07 09:54:20 +03:00
func (scope *Scope) whereSQL() (sql string) {
var (
quotedTableName = scope.QuotedTableName()
primaryConditions, andConditions, orConditions []string
)
2014-01-26 10:55:41 +04:00
if !scope.Search.Unscoped && scope.HasColumn("deleted_at") {
sql := fmt.Sprintf("%v.deleted_at IS NULL", quotedTableName)
2015-02-11 22:14:34 +03:00
primaryConditions = append(primaryConditions, sql)
2014-01-26 10:55:41 +04:00
}
if !scope.PrimaryKeyZero() {
for _, field := range scope.PrimaryFields() {
sql := fmt.Sprintf("%v.%v = %v", quotedTableName, scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))
primaryConditions = append(primaryConditions, sql)
}
2014-01-26 10:55:41 +04:00
}
2015-03-12 08:52:29 +03:00
for _, clause := range scope.Search.whereConditions {
if sql := scope.buildWhereCondition(clause); sql != "" {
andConditions = append(andConditions, sql)
}
2014-01-26 10:55:41 +04:00
}
2015-03-12 08:52:29 +03:00
for _, clause := range scope.Search.orConditions {
if sql := scope.buildWhereCondition(clause); sql != "" {
orConditions = append(orConditions, sql)
}
2014-01-26 10:55:41 +04:00
}
2015-03-12 08:52:29 +03:00
for _, clause := range scope.Search.notConditions {
if sql := scope.buildNotCondition(clause); sql != "" {
andConditions = append(andConditions, sql)
}
2014-01-26 10:55:41 +04:00
}
2016-03-07 09:54:20 +03:00
orSQL := strings.Join(orConditions, " OR ")
combinedSQL := strings.Join(andConditions, " AND ")
if len(combinedSQL) > 0 {
if len(orSQL) > 0 {
combinedSQL = combinedSQL + " OR " + orSQL
2014-01-26 10:55:41 +04:00
}
} else {
2016-03-07 09:54:20 +03:00
combinedSQL = orSQL
2014-01-26 10:55:41 +04:00
}
2015-02-11 22:14:34 +03:00
if len(primaryConditions) > 0 {
sql = "WHERE " + strings.Join(primaryConditions, " AND ")
2016-03-07 09:54:20 +03:00
if len(combinedSQL) > 0 {
sql = sql + " AND (" + combinedSQL + ")"
2014-01-26 10:55:41 +04:00
}
2016-03-07 09:54:20 +03:00
} else if len(combinedSQL) > 0 {
sql = "WHERE " + combinedSQL
2014-01-26 10:55:41 +04:00
}
return
}
2016-03-07 09:54:20 +03:00
func (scope *Scope) selectSQL() string {
2015-03-12 08:52:29 +03:00
if len(scope.Search.selects) == 0 {
2016-02-16 17:48:26 +03:00
if len(scope.Search.joinConditions) > 0 {
2015-10-01 02:43:38 +03:00
return fmt.Sprintf("%v.*", scope.QuotedTableName())
}
2014-01-26 10:55:41 +04:00
return "*"
}
return scope.buildSelectQuery(scope.Search.selects)
2014-01-26 10:55:41 +04:00
}
2016-03-07 09:54:20 +03:00
func (scope *Scope) orderSQL() string {
2015-08-05 10:58:11 +03:00
if len(scope.Search.orders) == 0 || scope.Search.countingQuery {
2014-01-26 10:55:41 +04:00
return ""
}
2015-03-12 08:52:29 +03:00
return " ORDER BY " + strings.Join(scope.Search.orders, ",")
2014-01-26 10:55:41 +04:00
}
2016-03-07 09:54:20 +03:00
func (scope *Scope) limitAndOffsetSQL() string {
2016-01-18 15:32:52 +03:00
return scope.Dialect().LimitAndOffsetSQL(scope.Search.limit, scope.Search.offset)
2014-01-26 10:55:41 +04:00
}
2016-03-07 09:54:20 +03:00
func (scope *Scope) groupSQL() string {
2015-03-12 08:52:29 +03:00
if len(scope.Search.group) == 0 {
2014-01-26 10:55:41 +04:00
return ""
}
2015-03-12 08:52:29 +03:00
return " GROUP BY " + scope.Search.group
2014-01-26 10:55:41 +04:00
}
2016-03-07 09:54:20 +03:00
func (scope *Scope) havingSQL() string {
2016-02-16 17:48:26 +03:00
if len(scope.Search.havingConditions) == 0 {
2014-01-26 10:55:41 +04:00
return ""
}
var andConditions []string
for _, clause := range scope.Search.havingConditions {
if sql := scope.buildWhereCondition(clause); sql != "" {
andConditions = append(andConditions, sql)
}
}
2016-03-07 09:54:20 +03:00
combinedSQL := strings.Join(andConditions, " AND ")
if len(combinedSQL) == 0 {
return ""
}
2016-03-07 09:54:20 +03:00
return " HAVING " + combinedSQL
2014-01-26 10:55:41 +04:00
}
2016-03-07 09:54:20 +03:00
func (scope *Scope) joinsSQL() string {
2016-02-16 17:48:26 +03:00
var joinConditions []string
for _, clause := range scope.Search.joinConditions {
if sql := scope.buildWhereCondition(clause); sql != "" {
joinConditions = append(joinConditions, strings.TrimSuffix(strings.TrimPrefix(sql, "("), ")"))
}
}
return strings.Join(joinConditions, " ") + " "
2014-01-26 10:55:41 +04:00
}
2014-01-28 07:37:32 +04:00
2016-03-07 09:54:20 +03:00
func (scope *Scope) prepareQuerySQL() {
2015-03-12 08:52:29 +03:00
if scope.Search.raw {
2015-01-23 03:59:05 +03:00
scope.Raw(strings.TrimSuffix(strings.TrimPrefix(scope.CombinedConditionSql(), " WHERE ("), ")"))
2014-01-28 07:37:32 +04:00
} else {
2016-03-07 09:54:20 +03:00
scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql()))
2014-01-28 07:37:32 +04:00
}
return
}
2014-01-28 08:28:44 +04:00
func (scope *Scope) inlineCondition(values ...interface{}) *Scope {
2014-01-28 07:37:32 +04:00
if len(values) > 0 {
2015-03-12 08:52:29 +03:00
scope.Search.Where(values[0], values[1:]...)
2014-01-28 07:37:32 +04:00
}
return scope
}
2014-01-29 08:00:57 +04:00
func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
for _, f := range funcs {
(*f)(scope)
if scope.skipLeft {
break
}
}
return scope
}
func (scope *Scope) updatedAttrsWithValues(values map[string]interface{}) (results map[string]interface{}, hasUpdate bool) {
if scope.IndirectValue().Kind() != reflect.Struct {
2014-01-29 08:00:57 +04:00
return values, true
}
results = map[string]interface{}{}
2014-01-29 08:00:57 +04:00
for key, value := range values {
if field, ok := scope.FieldByName(key); ok && scope.changeableField(field) {
2015-02-17 17:55:14 +03:00
if !reflect.DeepEqual(field.Field, reflect.ValueOf(value)) {
if _, ok := value.(*expr); ok {
hasUpdate = true
results[field.DBName] = value
} else if !equalAsString(field.Field.Interface(), value) {
field.Set(value)
if field.IsNormal {
hasUpdate = true
results[field.DBName] = field.Field.Interface()
}
2016-01-04 16:49:04 +03:00
}
} else {
field.Set(value)
2015-02-24 17:06:35 +03:00
}
}
}
2014-01-29 08:00:57 +04:00
return
}
func (scope *Scope) row() *sql.Row {
2016-01-13 09:58:30 +03:00
defer scope.trace(NowFunc())
2016-01-16 14:20:52 +03:00
scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
2016-03-07 09:54:20 +03:00
scope.prepareQuerySQL()
return scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...)
2014-01-29 08:00:57 +04:00
}
func (scope *Scope) rows() (*sql.Rows, error) {
2016-01-13 09:58:30 +03:00
defer scope.trace(NowFunc())
2016-01-16 14:20:52 +03:00
scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
2016-03-07 09:54:20 +03:00
scope.prepareQuerySQL()
return scope.SQLDB().Query(scope.SQL, scope.SQLVars...)
2014-01-29 08:00:57 +04:00
}
func (scope *Scope) initialize() *Scope {
2015-03-12 08:52:29 +03:00
for _, clause := range scope.Search.whereConditions {
scope.updatedAttrsWithValues(convertInterfaceToMap(clause["query"]))
2014-01-29 08:00:57 +04:00
}
scope.updatedAttrsWithValues(convertInterfaceToMap(scope.Search.initAttrs))
scope.updatedAttrsWithValues(convertInterfaceToMap(scope.Search.assignAttrs))
2014-01-29 08:00:57 +04:00
return scope
}
func (scope *Scope) pluck(column string, value interface{}) *Scope {
dest := reflect.Indirect(reflect.ValueOf(value))
2015-03-12 10:50:38 +03:00
scope.Search.Select(column)
2014-01-29 08:00:57 +04:00
if dest.Kind() != reflect.Slice {
scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind()))
2014-01-29 08:00:57 +04:00
return scope
}
rows, err := scope.rows()
if scope.Err(err) == nil {
defer rows.Close()
for rows.Next() {
elem := reflect.New(dest.Type().Elem()).Interface()
scope.Err(rows.Scan(elem))
dest.Set(reflect.Append(dest, reflect.ValueOf(elem).Elem()))
}
}
return scope
}
func (scope *Scope) count(value interface{}) *Scope {
2015-03-12 10:50:38 +03:00
scope.Search.Select("count(*)")
scope.Search.countingQuery = true
2014-01-29 08:00:57 +04:00
scope.Err(scope.row().Scan(value))
return scope
}
func (scope *Scope) typeName() string {
2015-12-25 06:50:27 +03:00
typ := scope.IndirectValue().Type()
for typ.Kind() == reflect.Slice || typ.Kind() == reflect.Ptr {
typ = typ.Elem()
2014-01-29 08:00:57 +04:00
}
2015-02-17 03:34:01 +03:00
2015-12-25 06:50:27 +03:00
return typ.Name()
2014-01-29 08:00:57 +04:00
}
2016-01-13 09:58:30 +03:00
// trace print sql log
func (scope *Scope) trace(t time.Time) {
2016-03-07 09:54:20 +03:00
if len(scope.SQL) > 0 {
scope.db.slog(scope.SQL, t, scope.SQLVars...)
2016-01-13 09:58:30 +03:00
}
}
func (scope *Scope) changeableField(field *Field) bool {
2016-01-17 13:38:18 +03:00
if selectAttrs := scope.SelectAttrs(); len(selectAttrs) > 0 {
2016-01-13 09:58:30 +03:00
for _, attr := range selectAttrs {
if field.Name == attr || field.DBName == attr {
return true
}
}
return false
}
2016-01-17 13:38:18 +03:00
for _, attr := range scope.OmitAttrs() {
2016-01-13 09:58:30 +03:00
if field.Name == attr || field.DBName == attr {
return false
}
}
return true
2016-01-13 09:58:30 +03:00
}
func (scope *Scope) shouldSaveAssociations() bool {
2016-01-17 13:38:18 +03:00
if saveAssociations, ok := scope.Get("gorm:save_associations"); ok && !saveAssociations.(bool) {
2016-01-13 09:58:30 +03:00
return false
}
return true && !scope.HasError()
}
2014-01-29 08:00:57 +04:00
func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
2014-03-26 04:48:40 +04:00
toScope := scope.db.NewScope(value)
2015-12-25 06:50:27 +03:00
2014-01-29 08:00:57 +04:00
for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
2016-03-07 07:15:15 +03:00
fromField, _ := scope.FieldByName(foreignKey)
toField, _ := toScope.FieldByName(foreignKey)
2015-02-17 12:40:21 +03:00
if fromField != nil {
if relationship := fromField.Relationship; relationship != nil {
if relationship.Kind == "many_to_many" {
2015-03-18 06:47:11 +03:00
joinTableHandler := relationship.JoinTableHandler
2015-06-19 06:32:11 +03:00
scope.Err(joinTableHandler.JoinWith(joinTableHandler, toScope.db, scope.Value).Find(value).Error)
2015-02-17 12:40:21 +03:00
} else if relationship.Kind == "belongs_to" {
2015-07-30 12:58:49 +03:00
query := toScope.db
for idx, foreignKey := range relationship.ForeignDBNames {
2015-07-30 13:56:05 +03:00
if field, ok := scope.FieldByName(foreignKey); ok {
query = query.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.AssociationForeignDBNames[idx])), field.Field.Interface())
2015-07-30 12:58:49 +03:00
}
}
scope.Err(query.Find(value).Error)
2015-02-17 12:40:21 +03:00
} else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
2015-07-30 12:58:49 +03:00
query := toScope.db
for idx, foreignKey := range relationship.ForeignDBNames {
if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
query = query.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
}
}
2015-02-18 07:30:09 +03:00
if relationship.PolymorphicType != "" {
query = query.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), scope.TableName())
}
2015-02-17 12:40:21 +03:00
scope.Err(query.Find(value).Error)
}
2015-02-17 12:40:21 +03:00
} else {
sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey()))
scope.Err(toScope.db.Where(sql, fromField.Field.Interface()).Find(value).Error)
2014-07-30 16:48:36 +04:00
}
2015-02-17 12:40:21 +03:00
return scope
} else if toField != nil {
sql := fmt.Sprintf("%v = ?", scope.Quote(toField.DBName))
scope.Err(toScope.db.Where(sql, scope.PrimaryKeyValue()).Find(value).Error)
return scope
2014-01-29 08:00:57 +04:00
}
}
2015-02-17 12:40:21 +03:00
2014-07-30 16:59:52 +04:00
scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
2014-01-29 08:00:57 +04:00
return scope
}
/**
2015-08-05 10:58:11 +03:00
Return the table options string or an empty string if the table options does not exist
*/
2015-08-05 10:58:11 +03:00
func (scope *Scope) getTableOptions() string {
tableOptions, ok := scope.Get("gorm:table_options")
if !ok {
return ""
}
return tableOptions.(string)
}
2016-02-14 11:17:02 +03:00
func (scope *Scope) createJoinTable(field *StructField) {
2015-03-18 06:47:11 +03:00
if relationship := field.Relationship; relationship != nil && relationship.JoinTableHandler != nil {
2015-03-18 13:14:28 +03:00
joinTableHandler := relationship.JoinTableHandler
joinTable := joinTableHandler.Table(scope.db)
2016-02-15 09:09:24 +03:00
if !scope.Dialect().HasTable(joinTable) {
toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}
var sqlTypes, primaryKeys []string
for idx, fieldName := range relationship.ForeignFieldNames {
2016-03-07 07:15:15 +03:00
if field, ok := scope.FieldByName(fieldName); ok {
2016-02-14 11:17:02 +03:00
foreignKeyStruct := field.clone()
2016-02-13 18:51:36 +03:00
foreignKeyStruct.IsPrimaryKey = false
foreignKeyStruct.TagSettings["IS_JOINTABLE_FOREIGNKEY"] = "true"
sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
primaryKeys = append(primaryKeys, scope.Quote(relationship.ForeignDBNames[idx]))
}
}
for idx, fieldName := range relationship.AssociationForeignFieldNames {
2016-03-07 07:15:15 +03:00
if field, ok := toScope.FieldByName(fieldName); ok {
2016-02-14 11:17:02 +03:00
foreignKeyStruct := field.clone()
2016-02-13 18:51:36 +03:00
foreignKeyStruct.IsPrimaryKey = false
foreignKeyStruct.TagSettings["IS_JOINTABLE_FOREIGNKEY"] = "true"
sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
primaryKeys = append(primaryKeys, scope.Quote(relationship.AssociationForeignDBNames[idx]))
}
}
scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v, PRIMARY KEY (%v)) %s", scope.Quote(joinTable), strings.Join(sqlTypes, ","), strings.Join(primaryKeys, ","), scope.getTableOptions())).Error)
2014-07-30 10:20:38 +04:00
}
2015-03-18 13:14:28 +03:00
scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler)
2014-07-30 10:20:38 +04:00
}
}
2014-01-29 08:00:57 +04:00
func (scope *Scope) createTable() *Scope {
2015-03-11 12:05:58 +03:00
var tags []string
var primaryKeys []string
2016-01-15 16:03:35 +03:00
var primaryKeyInColumnType = false
2016-02-14 11:17:02 +03:00
for _, field := range scope.GetModelStruct().StructFields {
2015-03-11 12:05:58 +03:00
if field.IsNormal {
2016-02-14 11:17:02 +03:00
sqlTag := scope.Dialect().DataTypeOf(field)
// Check if the primary key constraint was specified as
// part of the column type. If so, we can only support
// one column as the primary key.
if strings.Contains(strings.ToLower(sqlTag), "primary key") {
primaryKeyInColumnType = true
}
2015-03-11 12:05:58 +03:00
tags = append(tags, scope.Quote(field.DBName)+" "+sqlTag)
}
if field.IsPrimaryKey {
2015-05-22 06:13:14 +03:00
primaryKeys = append(primaryKeys, scope.Quote(field.DBName))
2014-01-29 08:00:57 +04:00
}
2015-03-11 12:05:58 +03:00
scope.createJoinTable(field)
}
var primaryKeyStr string
if len(primaryKeys) > 0 && !primaryKeyInColumnType {
2015-03-11 12:05:58 +03:00
primaryKeyStr = fmt.Sprintf(", PRIMARY KEY (%v)", strings.Join(primaryKeys, ","))
2014-01-29 08:00:57 +04:00
}
scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v %v) %s", scope.QuotedTableName(), strings.Join(tags, ","), primaryKeyStr, scope.getTableOptions())).Exec()
scope.autoIndex()
2014-01-29 08:00:57 +04:00
return scope
}
func (scope *Scope) dropTable() *Scope {
2014-06-03 13:15:05 +04:00
scope.Raw(fmt.Sprintf("DROP TABLE %v", scope.QuotedTableName())).Exec()
2014-01-29 08:00:57 +04:00
return scope
}
2014-08-05 18:14:40 +04:00
func (scope *Scope) dropTableIfExists() *Scope {
2016-02-15 09:09:24 +03:00
if scope.Dialect().HasTable(scope.TableName()) {
2015-02-28 12:01:27 +03:00
scope.dropTable()
}
2014-08-05 18:14:40 +04:00
return scope
}
2014-01-29 08:00:57 +04:00
func (scope *Scope) modifyColumn(column string, typ string) {
2014-06-03 13:15:05 +04:00
scope.Raw(fmt.Sprintf("ALTER TABLE %v MODIFY %v %v", scope.QuotedTableName(), scope.Quote(column), typ)).Exec()
2014-01-29 08:00:57 +04:00
}
func (scope *Scope) dropColumn(column string) {
2014-06-03 13:15:05 +04:00
scope.Raw(fmt.Sprintf("ALTER TABLE %v DROP COLUMN %v", scope.QuotedTableName(), scope.Quote(column))).Exec()
2014-01-29 08:00:57 +04:00
}
2014-06-01 02:35:56 +04:00
func (scope *Scope) addIndex(unique bool, indexName string, column ...string) {
2016-02-15 09:09:24 +03:00
if scope.Dialect().HasIndex(scope.TableName(), indexName) {
2015-03-09 16:33:25 +03:00
return
}
2014-06-01 02:12:31 +04:00
var columns []string
for _, name := range column {
2016-01-17 11:37:17 +03:00
columns = append(columns, scope.quoteIfPossible(name))
2014-01-29 08:00:57 +04:00
}
2014-06-01 02:35:56 +04:00
sqlCreate := "CREATE INDEX"
if unique {
sqlCreate = "CREATE UNIQUE INDEX"
}
2016-03-07 09:54:20 +03:00
scope.Raw(fmt.Sprintf("%s %v ON %v(%v) %v", sqlCreate, indexName, scope.QuotedTableName(), strings.Join(columns, ", "), scope.whereSQL())).Exec()
2014-01-29 08:00:57 +04:00
}
2015-02-07 14:04:10 +03:00
func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) {
var keyName = fmt.Sprintf("%s_%s_%s_foreign", scope.TableName(), field, dest)
2016-01-05 03:34:17 +03:00
keyName = regexp.MustCompile("(_*[^a-zA-Z]+_*|_+)").ReplaceAllString(keyName, "_")
if scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
return
}
2015-02-17 17:55:14 +03:00
var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;`
2016-01-17 11:37:17 +03:00
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
2015-02-07 14:04:10 +03:00
}
2014-01-29 08:00:57 +04:00
func (scope *Scope) removeIndex(indexName string) {
2016-02-15 09:09:24 +03:00
scope.Dialect().RemoveIndex(scope.TableName(), indexName)
2014-01-29 08:00:57 +04:00
}
func (scope *Scope) autoMigrate() *Scope {
2014-07-02 07:56:37 +04:00
tableName := scope.TableName()
quotedTableName := scope.QuotedTableName()
2016-02-15 09:09:24 +03:00
if !scope.Dialect().HasTable(tableName) {
2014-01-29 08:00:57 +04:00
scope.createTable()
} else {
2016-02-14 11:17:02 +03:00
for _, field := range scope.GetModelStruct().StructFields {
2016-02-15 09:09:24 +03:00
if !scope.Dialect().HasColumn(tableName, field.DBName) {
2014-08-30 18:39:28 +04:00
if field.IsNormal {
2016-02-14 11:17:02 +03:00
sqlTag := scope.Dialect().DataTypeOf(field)
scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, scope.Quote(field.DBName), sqlTag)).Exec()
}
2014-01-29 08:00:57 +04:00
}
2014-07-30 10:20:38 +04:00
scope.createJoinTable(field)
2014-01-29 08:00:57 +04:00
}
scope.autoIndex()
2014-01-29 08:00:57 +04:00
}
2015-03-09 12:22:16 +03:00
return scope
}
func (scope *Scope) autoIndex() *Scope {
var indexes = map[string][]string{}
var uniqueIndexes = map[string][]string{}
for _, field := range scope.GetStructFields() {
2016-01-03 05:00:18 +03:00
if name, ok := field.TagSettings["INDEX"]; ok {
2015-03-09 12:22:16 +03:00
if name == "INDEX" {
name = fmt.Sprintf("idx_%v_%v", scope.TableName(), field.DBName)
}
indexes[name] = append(indexes[name], field.DBName)
}
2016-01-03 05:00:18 +03:00
if name, ok := field.TagSettings["UNIQUE_INDEX"]; ok {
2015-03-09 12:22:16 +03:00
if name == "UNIQUE_INDEX" {
name = fmt.Sprintf("uix_%v_%v", scope.TableName(), field.DBName)
}
uniqueIndexes[name] = append(uniqueIndexes[name], field.DBName)
2015-03-09 12:22:16 +03:00
}
}
for name, columns := range indexes {
2016-01-12 08:44:16 +03:00
scope.NewDB().Model(scope.Value).AddIndex(name, columns...)
2015-03-09 12:22:16 +03:00
}
for name, columns := range uniqueIndexes {
2016-01-12 08:44:16 +03:00
scope.NewDB().Model(scope.Value).AddUniqueIndex(name, columns...)
2015-03-09 12:22:16 +03:00
}
2014-01-29 08:00:57 +04:00
return scope
}