gorm/scope_private.go

731 lines
21 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{}:
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})
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-01-03 15:23:37 +03:00
} else {
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)
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()
}
2015-08-01 06:49:34 +03:00
str = strings.Replace(str, "?", scope.AddToVars(arg), 1)
}
}
return
}
2014-01-26 10:55:41 +04: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
}
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
}
var hasCountRegexp = regexp.MustCompile(`(?i)count\(.+\)`)
2015-08-05 10:58:11 +03:00
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 {
2015-10-01 02:43:38 +03:00
if scope.Search.joins != "" {
return fmt.Sprintf("%v.*", scope.QuotedTableName())
}
2014-01-26 10:55:41 +04:00
return "*"
}
2015-08-05 10:58:11 +03:00
sql := scope.buildSelectQuery(scope.Search.selects)
2015-09-17 16:39:16 +03:00
scope.Search.countingQuery = (len(scope.Search.group) == 0) && hasCountRegexp.MatchString(sql)
return sql
2014-01-26 10:55:41 +04:00
}
2015-02-17 02:19:42 +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
}
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
2014-01-29 08:00:57 +04:00
for key, value := range values {
2016-01-04 16:49:04 +03:00
if field, ok := scope.FieldByName(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
}
}
2016-01-04 16:49:04 +03:00
2015-02-24 17:06:35 +03:00
if hasExpr {
var updateMap = map[string]interface{}{}
2016-01-04 16:49:04 +03:00
for key, field := range scope.Fields() {
if field.IsNormal {
if v, ok := values[key]; ok {
updateMap[key] = v
} else {
updateMap[key] = field.Field.Interface()
}
2015-02-24 17:06:35 +03:00
}
}
return updateMap, true
}
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())
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) {
2016-01-13 09:58:30 +03:00
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 {
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) {
if len(scope.Sql) > 0 {
scope.db.slog(scope.Sql, t, scope.SqlVars...)
}
}
func (scope *Scope) changeableDBColumn(column string) bool {
selectAttrs := scope.SelectAttrs()
omitAttrs := scope.OmitAttrs()
if len(selectAttrs) > 0 {
for _, attr := range selectAttrs {
if column == ToDBName(attr) {
return true
}
}
return false
}
for _, attr := range omitAttrs {
if column == ToDBName(attr) {
return false
}
}
return true
}
func (scope *Scope) changeableField(field *Field) bool {
selectAttrs := scope.SelectAttrs()
omitAttrs := scope.OmitAttrs()
if len(selectAttrs) > 0 {
for _, attr := range selectAttrs {
if field.Name == attr || field.DBName == attr {
return true
}
}
return false
}
for _, attr := range omitAttrs {
if field.Name == attr || field.DBName == attr {
return false
}
}
return !field.IsIgnored
}
func (scope *Scope) shouldSaveAssociations() bool {
saveAssociations, ok := scope.Get("gorm:save_associations")
if ok && !saveAssociations.(bool) {
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-02-17 12:40:21 +03:00
fromFields := scope.Fields()
toFields := toScope.Fields()
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") {
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-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)
}
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, primaryKeys []string
for idx, fieldName := range relationship.ForeignFieldNames {
if field, ok := scope.Fields()[fieldName]; ok {
value := reflect.Indirect(reflect.New(field.Struct.Type))
primaryKeySqlType := field.TagSettings["TYPE"]
if primaryKeySqlType == "" {
primaryKeySqlType = scope.Dialect().SqlTag(value, 255, false)
}
sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+primaryKeySqlType)
primaryKeys = append(primaryKeys, scope.Quote(relationship.ForeignDBNames[idx]))
}
}
for idx, fieldName := range relationship.AssociationForeignFieldNames {
if field, ok := toScope.Fields()[fieldName]; ok {
value := reflect.Indirect(reflect.New(field.Struct.Type))
primaryKeySqlType := field.TagSettings["TYPE"]
if primaryKeySqlType == "" {
primaryKeySqlType = scope.Dialect().SqlTag(value, 255, false)
}
sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+primaryKeySqlType)
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
var primaryKeyInColumnType bool = false
2015-03-11 12:05:58 +03:00
for _, field := range scope.GetStructFields() {
if field.IsNormal {
sqlTag := scope.generateSqlTag(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 {
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"
}
2015-10-01 01:53:15 +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, "_")
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(), 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) {
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
}
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
}