gorm/scope_private.go

537 lines
16 KiB
Go
Raw Normal View History

2014-01-26 10:55:41 +04:00
package gorm
import (
"database/sql"
"database/sql/driver"
2014-01-29 08:00:57 +04:00
"errors"
2014-01-26 10:55:41 +04:00
"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.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 {
switch reflect.TypeOf(arg).Kind() {
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 {
switch reflect.TypeOf(arg).Kind() {
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 {
switch reflect.TypeOf(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-02-17 17:55:14 +03:00
if !scope.Search.Unscope && 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
}
2014-01-28 12:56:51 +04: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
}
2014-01-28 12:56:51 +04: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
}
2014-01-28 12:56:51 +04: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 {
if len(scope.Search.Selects) == 0 {
2014-01-26 10:55:41 +04:00
return "*"
}
2015-02-23 03:58:52 +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 {
if len(scope.Search.Orders) == 0 {
2014-01-26 10:55:41 +04:00
return ""
}
2015-02-17 03:34:01 +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() {
if len(scope.Search.Limit) == 0 {
return ""
}
2015-02-17 03:34:01 +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 {
if scope.Dialect().HasTop() && len(scope.Search.Offset) == 0 {
if len(scope.Search.Limit) == 0 {
return ""
}
2015-02-17 03:34:01 +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 {
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() {
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-02-17 03:34:01 +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 {
if len(scope.Search.Group) == 0 {
2014-01-26 10:55:41 +04:00
return ""
}
2015-02-17 03:34:01 +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.HavingCondition == nil {
2014-01-26 10:55:41 +04:00
return ""
}
2015-02-17 03:34:01 +03:00
return " HAVING " + scope.buildWhereCondition(scope.Search.HavingCondition)
2014-01-26 10:55:41 +04:00
}
2015-02-17 02:21:18 +03:00
func (scope *Scope) joinsSql() string {
return scope.Search.Joins + " "
2014-01-26 10:55:41 +04:00
}
2014-01-28 07:37:32 +04:00
func (scope *Scope) prepareQuerySql() {
2014-01-28 12:56:51 +04: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 {
scope.Search = scope.Search.clone().where(values[0], values[1:]...)
}
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())
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())
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 {
for _, clause := range scope.Search.WhereConditions {
scope.updatedAttrsWithValues(convertInterfaceToMap(clause["query"]), false)
}
scope.updatedAttrsWithValues(convertInterfaceToMap(scope.Search.InitAttrs), false)
scope.updatedAttrsWithValues(convertInterfaceToMap(scope.Search.AssignAttrs), false)
return scope
}
func (scope *Scope) pluck(column string, value interface{}) *Scope {
dest := reflect.Indirect(reflect.ValueOf(value))
scope.Search = scope.Search.clone().selects(column)
if dest.Kind() != reflect.Slice {
2014-07-30 10:58:00 +04:00
scope.Err(errors.New("results should be a slice"))
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-02-23 03:58:52 +03:00
scope.Search = scope.Search.clone().selects("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") {
2015-02-18 05:19:34 +03:00
fromField := fromFields[ToDBName(foreignKey)]
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-04 07:16:16 +03:00
joinTableHandler := scope.db.GetJoinTableHandler(relationship.JoinTable)
quotedJoinTable := scope.Quote(joinTableHandler.Table(scope.db, relationship))
joinSql := fmt.Sprintf(
"INNER JOIN %v ON %v.%v = %v.%v",
2015-03-04 07:16:16 +03:00
quotedJoinTable,
quotedJoinTable,
2015-02-17 12:40:21 +03:00
scope.Quote(relationship.AssociationForeignDBName),
toScope.QuotedTableName(),
scope.Quote(toScope.PrimaryKey()))
2015-03-04 07:16:16 +03:00
whereSql := fmt.Sprintf("%v.%v = ?", quotedJoinTable, scope.Quote(relationship.ForeignDBName))
2015-02-17 12:40:21 +03:00
scope.Err(toScope.db.Joins(joinSql).Where(whereSql, scope.PrimaryKeyValue()).Find(value).Error)
} else if relationship.Kind == "belongs_to" {
2014-11-12 05:23:51 +03:00
sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey()))
2015-03-02 10:55:24 +03:00
foreignKeyValue := fromFields[relationship.ForeignDBName].Field.Interface()
scope.Err(toScope.db.Where(sql, foreignKeyValue).Find(value).Error)
2015-02-17 12:40:21 +03:00
} else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
sql := fmt.Sprintf("%v = ?", scope.Quote(relationship.ForeignDBName))
query := toScope.db.Where(sql, scope.PrimaryKeyValue())
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-02-28 09:16:51 +03:00
if relationship := field.Relationship; relationship != nil && relationship.JoinTable != "" {
2015-03-04 07:16:16 +03:00
joinTableHandler := scope.db.GetJoinTableHandler(relationship.JoinTable)
joinTable := joinTableHandler.Table(scope.db, relationship)
if !scope.Dialect().HasTable(scope, joinTable) {
2015-02-17 17:55:14 +03:00
primaryKeySqlType := scope.Dialect().SqlTag(scope.PrimaryKeyField().Field, 255)
2015-02-28 09:16:51 +03:00
scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v)",
2015-03-04 07:16:16 +03:00
scope.Quote(joinTable),
2014-07-30 10:20:38 +04:00
strings.Join([]string{
2015-02-28 09:16:51 +03:00
scope.Quote(relationship.ForeignDBName) + " " + primaryKeySqlType,
scope.Quote(relationship.AssociationForeignDBName) + " " + primaryKeySqlType}, ",")),
).Error)
2014-07-30 10:20:38 +04:00
}
2015-03-04 07:16:16 +03:00
scope.NewDB().Table(joinTable).AutoMigrate()
2014-07-30 10:20:38 +04:00
}
}
2014-01-29 08:00:57 +04:00
func (scope *Scope) createTable() *Scope {
var sqls []string
2015-02-15 18:01:09 +03:00
for _, structField := range scope.GetStructFields() {
if structField.IsNormal {
sqls = append(sqls, scope.Quote(structField.DBName)+" "+structField.SqlTag)
2014-01-29 08:00:57 +04:00
}
2015-02-15 18:01:09 +03:00
scope.createJoinTable(structField)
2014-01-29 08:00:57 +04:00
}
2014-06-03 13:15:05 +04:00
scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v)", scope.QuotedTableName(), strings.Join(sqls, ","))).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) {
2014-06-01 02:12:31 +04:00
var columns []string
for _, name := range column {
columns = append(columns, scope.Quote(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_foreign", table, field)
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;`
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), keyName, 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) {
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-02-16 11:42:01 +03:00
scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, field.DBName, field.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
}
}
return scope
}