gorm/scope_private.go

624 lines
19 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"
)
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) {
id, _ := strconv.Atoi(value)
2015-02-11 22:14:34 +03:00
return scope.primaryCondition(scope.AddToVars(id))
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{}:
2014-01-28 12:22:41 +04: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 {
2014-01-28 12:22:41 +04:00
sqls = append(sqls, fmt.Sprintf("(%v = %v)", scope.Quote(key), scope.AddToVars(value)))
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})
values := reflect.ValueOf(arg)
2014-01-28 13:09:43 +04:00
var tempMarks []string
2014-01-26 10:55:41 +04:00
for i := 0; i < values.Len(); i++ {
2014-01-28 13:09:43 +04:00
tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
2014-01-26 10:55:41 +04:00
}
2014-01-28 13:09:43 +04:00
str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 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) {
2014-01-28 13:09:43 +04: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)
2014-01-26 10:55:41 +04:00
} else if regexp.MustCompile("(?i) (=|<>|>|<|LIKE|IS) ").MatchString(value) {
str = fmt.Sprintf(" NOT (%v) ", value)
2014-01-28 13:09:43 +04: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))
2014-01-28 13:09:43 +04: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 {
2014-01-28 12:22:41 +04:00
sqls = append(sqls, fmt.Sprintf("(%v <> %v)", scope.Quote(key), scope.AddToVars(value)))
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})
values := reflect.ValueOf(arg)
2014-01-28 13:09:43 +04:00
var tempMarks []string
2014-01-26 10:55:41 +04:00
for i := 0; i < values.Len(); i++ {
2014-01-28 13:09:43 +04:00
tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
2014-01-26 10:55:41 +04:00
}
2014-01-28 13:09:43 +04:00
str = strings.Replace(str, "?", strings.Join(tempMarks, ","), 1)
2014-01-26 10:55:41 +04:00
default:
if scanner, ok := interface{}(arg).(driver.Valuer); ok {
arg, _ = scanner.Value()
}
2014-01-28 13:09:43 +04: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()
}
2014-11-24 13:16:07 +03:00
str = strings.Replace(str, "?", scope.Dialect().Quote(fmt.Sprintf("%v", arg)), 1)
}
}
return
}
2014-01-26 10:55:41 +04:00
func (scope *Scope) whereSql() (sql string) {
2015-02-11 22:14:34 +03:00
var primaryConditions, andConditions, orConditions []string
2014-01-26 10:55:41 +04:00
2015-03-12 10:01:59 +03:00
if !scope.Search.Unscoped && scope.Fields()["deleted_at"] != nil {
sql := fmt.Sprintf("(%v.deleted_at IS NULL OR %v.deleted_at <= '0001-01-02')", scope.QuotedTableName(), scope.QuotedTableName())
2015-02-11 22:14:34 +03:00
primaryConditions = append(primaryConditions, sql)
2014-01-26 10:55:41 +04:00
}
if !scope.PrimaryKeyZero() {
2015-02-11 22:14:34 +03:00
primaryConditions = append(primaryConditions, scope.primaryCondition(scope.AddToVars(scope.PrimaryKeyValue())))
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
}
2014-01-28 13:09:43 +04: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 {
2014-01-28 13:09:43 +04: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 ")
2014-01-28 13:09:43 +04:00
if len(combinedSql) > 0 {
sql = sql + " AND (" + combinedSql + ")"
2014-01-26 10:55:41 +04:00
}
2014-01-28 13:09:43 +04:00
} else if len(combinedSql) > 0 {
sql = "WHERE " + combinedSql
2014-01-26 10:55:41 +04:00
}
return
}
2015-02-17 02:19:42 +03:00
func (scope *Scope) selectSql() string {
2015-03-12 08:52:29 +03:00
if len(scope.Search.selects) == 0 {
2014-01-26 10:55:41 +04:00
return "*"
}
2015-03-12 08:52:29 +03:00
return scope.buildSelectQuery(scope.Search.selects)
2014-01-26 10:55:41 +04:00
}
2015-02-17 02:19:42 +03:00
func (scope *Scope) orderSql() string {
2015-03-12 08:52:29 +03:00
if len(scope.Search.orders) == 0 {
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
}
2015-02-17 03:34:01 +03:00
func (scope *Scope) limitSql() string {
if !scope.Dialect().HasTop() {
2015-03-12 08:52:29 +03:00
if len(scope.Search.limit) == 0 {
return ""
}
2015-03-12 08:52:29 +03:00
return " LIMIT " + scope.Search.limit
}
2015-02-17 02:19:42 +03:00
return ""
}
2015-02-17 02:21:18 +03:00
func (scope *Scope) topSql() string {
2015-03-12 08:52:29 +03:00
if scope.Dialect().HasTop() && len(scope.Search.offset) == 0 {
if len(scope.Search.limit) == 0 {
return ""
}
2015-03-12 08:52:29 +03:00
return " TOP(" + scope.Search.limit + ")"
2014-01-26 10:55:41 +04:00
}
2015-02-17 02:21:18 +03:00
return ""
2014-01-26 10:55:41 +04:00
}
2015-02-17 02:21:18 +03:00
func (scope *Scope) offsetSql() string {
2015-03-12 08:52:29 +03:00
if len(scope.Search.offset) == 0 {
2014-01-26 10:55:41 +04:00
return ""
2015-02-17 03:34:01 +03:00
}
if scope.Dialect().HasTop() {
2015-03-12 08:52:29 +03:00
sql := " OFFSET " + scope.Search.offset + " ROW "
if len(scope.Search.limit) > 0 {
sql += "FETCH NEXT " + scope.Search.limit + " ROWS ONLY"
}
2015-02-17 03:34:01 +03:00
return sql
2014-01-26 10:55:41 +04:00
}
2015-03-12 08:52:29 +03:00
return " OFFSET " + scope.Search.offset
2014-01-26 10:55:41 +04:00
}
2015-02-17 02:21:18 +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
}
2015-02-17 02:21:18 +03:00
func (scope *Scope) havingSql() string {
if scope.Search.havingConditions == nil {
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)
}
}
combinedSql := strings.Join(andConditions, " AND ")
if len(combinedSql) == 0 {
return ""
}
return " HAVING " + combinedSql
2014-01-26 10:55:41 +04:00
}
2015-02-17 02:21:18 +03:00
func (scope *Scope) joinsSql() string {
2015-03-12 08:52:29 +03:00
return scope.Search.joins + " "
2014-01-26 10:55:41 +04:00
}
2014-01-28 07:37:32 +04: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 {
scope.Raw(fmt.Sprintf("SELECT %v %v FROM %v %v", scope.topSql(), 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{}, ignoreProtectedAttrs bool) (results map[string]interface{}, hasUpdate bool) {
2015-02-17 17:55:14 +03:00
if !scope.IndirectValue().CanAddr() {
2014-01-29 08:00:57 +04:00
return values, true
}
2015-02-24 17:06:35 +03:00
var hasExpr bool
2015-02-17 17:55:14 +03:00
fields := scope.Fields()
2014-01-29 08:00:57 +04:00
for key, value := range values {
2015-02-18 05:19:34 +03:00
if field, ok := fields[ToDBName(key)]; ok && field.Field.IsValid() {
2015-02-17 17:55:14 +03:00
if !reflect.DeepEqual(field.Field, reflect.ValueOf(value)) {
2015-02-24 17:06:35 +03:00
if _, ok := value.(*expr); ok {
hasExpr = true
} else if !equalAsString(field.Field.Interface(), value) {
2015-02-17 17:55:14 +03:00
hasUpdate = true
field.Set(value)
2014-01-29 08:00:57 +04:00
}
2015-02-17 17:55:14 +03:00
}
2014-01-29 08:00:57 +04:00
}
}
2015-02-24 17:06:35 +03:00
if hasExpr {
var updateMap = map[string]interface{}{}
for key, value := range fields {
if v, ok := values[key]; ok {
updateMap[key] = v
} else {
updateMap[key] = value.Field.Interface()
}
}
return updateMap, true
}
2014-01-29 08:00:57 +04:00
return
}
func (scope *Scope) row() *sql.Row {
defer scope.Trace(NowFunc())
2015-04-17 13:27:20 +03:00
scope.callCallbacks(scope.db.parent.callback.rowQueries)
2014-01-29 08:00:57 +04:00
scope.prepareQuerySql()
2015-02-26 07:35:33 +03:00
return scope.SqlDB().QueryRow(scope.Sql, scope.SqlVars...)
2014-01-29 08:00:57 +04:00
}
func (scope *Scope) rows() (*sql.Rows, error) {
defer scope.Trace(NowFunc())
2015-04-17 13:27:20 +03:00
scope.callCallbacks(scope.db.parent.callback.rowQueries)
2014-01-29 08:00:57 +04:00
scope.prepareQuerySql()
2015-02-26 07:35:33 +03:00
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 {
2014-01-29 08:00:57 +04:00
scope.updatedAttrsWithValues(convertInterfaceToMap(clause["query"]), false)
}
2015-03-12 08:52:29 +03:00
scope.updatedAttrsWithValues(convertInterfaceToMap(scope.Search.initAttrs), false)
scope.updatedAttrsWithValues(convertInterfaceToMap(scope.Search.assignAttrs), false)
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(*)")
2014-01-29 08:00:57 +04:00
scope.Err(scope.row().Scan(value))
return scope
}
func (scope *Scope) typeName() string {
2014-07-30 10:58:00 +04:00
value := scope.IndirectValue()
2014-01-29 08:00:57 +04:00
if value.Kind() == reflect.Slice {
return value.Type().Elem().Name()
}
2015-02-17 03:34:01 +03:00
return value.Type().Name()
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-02-17 12:40:21 +03:00
fromFields := scope.Fields()
toFields := toScope.Fields()
2014-01-29 08:00:57 +04:00
for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
var fromField, toField *Field
if field, ok := scope.FieldByName(foreignKey); ok {
fromField = field
} else {
fromField = fromFields[ToDBName(foreignKey)]
}
if field, ok := toScope.FieldByName(foreignKey); ok {
toField = field
} else {
toField = toFields[ToDBName(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-02-16 11:42:01 +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)
2015-03-04 07:16:16 +03:00
if !scope.Dialect().HasTable(scope, joinTable) {
toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}
var sqlTypes []string
for idx, fieldName := range relationship.ForeignFieldNames {
if field, ok := scope.Fields()[fieldName]; ok {
value := reflect.Indirect(reflect.New(field.Struct.Type))
primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false)
sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+primaryKeySqlType)
}
}
for idx, fieldName := range relationship.AssociationForeignFieldNames {
if field, ok := toScope.Fields()[fieldName]; ok {
value := reflect.Indirect(reflect.New(field.Struct.Type))
primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false)
sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+primaryKeySqlType)
}
}
scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v)", scope.Quote(joinTable), strings.Join(sqlTypes, ","))).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
for _, field := range scope.GetStructFields() {
if field.IsNormal {
sqlTag := scope.generateSqlTag(field)
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 {
primaryKeyStr = fmt.Sprintf(", PRIMARY KEY (%v)", strings.Join(primaryKeys, ","))
2014-01-29 08:00:57 +04:00
}
2015-03-11 12:05:58 +03:00
scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v %v)", scope.QuotedTableName(), strings.Join(tags, ","), primaryKeyStr)).Exec()
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 {
2015-02-28 12:01:27 +03:00
if scope.Dialect().HasTable(scope, scope.TableName()) {
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) {
2015-03-09 16:33:25 +03:00
if scope.Dialect().HasIndex(scope, scope.TableName(), indexName) {
return
}
2014-06-01 02:12:31 +04:00
var columns []string
for _, name := range column {
2015-08-01 04:25:06 +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"
}
scope.Raw(fmt.Sprintf("%s %v ON %v(%v);", sqlCreate, indexName, scope.QuotedTableName(), strings.Join(columns, ", "))).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) {
2015-02-17 03:34:01 +03:00
var table = scope.TableName()
var keyName = fmt.Sprintf("%s_%s_%s_foreign", table, field, regexp.MustCompile("[^a-zA-Z]").ReplaceAllString(dest, "_"))
keyName = regexp.MustCompile("_+").ReplaceAllString(keyName, "_")
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;`
2015-08-01 04:25:06 +03:00
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.QuoteIfPossible(keyName), scope.QuoteIfPossible(field), scope.QuoteIfPossible(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) {
scope.Dialect().RemoveIndex(scope, 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()
if !scope.Dialect().HasTable(scope, tableName) {
2014-01-29 08:00:57 +04:00
scope.createTable()
} else {
2015-02-16 11:42:01 +03:00
for _, field := range scope.GetStructFields() {
2014-07-02 07:56:37 +04:00
if !scope.Dialect().HasColumn(scope, tableName, field.DBName) {
2014-08-30 18:39:28 +04:00
if field.IsNormal {
2015-03-11 12:05:58 +03:00
sqlTag := scope.generateSqlTag(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
}
}
2015-03-09 12:22:16 +03:00
scope.autoIndex()
return scope
}
func (scope *Scope) autoIndex() *Scope {
var indexes = map[string][]string{}
var uniqueIndexes = map[string][]string{}
for _, field := range scope.GetStructFields() {
sqlSettings := parseTagSetting(field.Tag.Get("sql"))
if name, ok := sqlSettings["INDEX"]; ok {
if name == "INDEX" {
name = fmt.Sprintf("idx_%v_%v", scope.TableName(), field.DBName)
}
indexes[name] = append(indexes[name], field.DBName)
}
if name, ok := sqlSettings["UNIQUE_INDEX"]; ok {
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 {
2015-03-09 16:33:25 +03:00
scope.addIndex(false, name, columns...)
2015-03-09 12:22:16 +03:00
}
for name, columns := range uniqueIndexes {
2015-03-09 16:33:25 +03:00
scope.addIndex(true, name, columns...)
2015-03-09 12:22:16 +03:00
}
2014-01-29 08:00:57 +04:00
return scope
}