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"
|
2014-11-19 06:44:57 +03:00
|
|
|
"go/ast"
|
2014-01-26 10:55:41 +04:00
|
|
|
"reflect"
|
|
|
|
"regexp"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (scope *Scope) primaryCondiation(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)
|
|
|
|
return scope.primaryCondiation(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
|
|
|
}
|
2014-10-22 19:33:13 +04:00
|
|
|
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
|
2014-01-26 10:55:41 +04:00
|
|
|
return scope.primaryCondiation(scope.AddToVars(value))
|
|
|
|
case sql.NullInt64:
|
|
|
|
return scope.primaryCondiation(scope.AddToVars(value.Int64))
|
2015-02-11 08:43:53 +03:00
|
|
|
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
|
2014-01-26 10:55:41 +04:00
|
|
|
|
|
|
|
switch value := clause["query"].(type) {
|
|
|
|
case string:
|
|
|
|
if regexp.MustCompile("^\\s*\\d+\\s*$").MatchString(value) {
|
|
|
|
id, _ := strconv.Atoi(value)
|
2014-01-28 12:22:41 +04:00
|
|
|
return fmt.Sprintf("(%v <> %v)", scope.Quote(scope.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
|
|
|
}
|
2014-10-22 19:33:13 +04:00
|
|
|
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
|
2014-01-28 12:22:41 +04:00
|
|
|
return fmt.Sprintf("(%v <> %v)", scope.Quote(scope.PrimaryKey()), value)
|
2014-10-22 19:33:13 +04:00
|
|
|
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 {
|
2014-01-28 12:22:41 +04:00
|
|
|
str = fmt.Sprintf("(%v not in (?))", scope.Quote(scope.PrimaryKey()))
|
2014-01-26 10:55:41 +04:00
|
|
|
clause["args"] = []interface{}{value}
|
|
|
|
} else {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2014-11-17 15:12:32 +03:00
|
|
|
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)
|
2014-11-17 15:12:32 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-01-26 10:55:41 +04:00
|
|
|
func (scope *Scope) where(where ...interface{}) {
|
|
|
|
if len(where) > 0 {
|
|
|
|
scope.Search = scope.Search.clone().where(where[0], where[1:]...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (scope *Scope) whereSql() (sql string) {
|
2014-01-28 13:09:43 +04:00
|
|
|
var primaryCondiations, andConditions, orConditions []string
|
2014-01-26 10:55:41 +04:00
|
|
|
|
2014-01-28 12:56:51 +04:00
|
|
|
if !scope.Search.Unscope && scope.HasColumn("DeletedAt") {
|
2015-01-12 00:49:36 +03:00
|
|
|
sql := fmt.Sprintf("(%v.deleted_at IS NULL OR %v.deleted_at <= '0001-01-02')", scope.QuotedTableName(), scope.QuotedTableName())
|
|
|
|
primaryCondiations = append(primaryCondiations, sql)
|
2014-01-26 10:55:41 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
if !scope.PrimaryKeyZero() {
|
2014-01-28 13:09:43 +04:00
|
|
|
primaryCondiations = append(primaryCondiations, scope.primaryCondiation(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 {
|
2015-01-04 15:47:25 +03:00
|
|
|
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 {
|
2015-01-04 15:47:25 +03:00
|
|
|
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 {
|
2015-01-04 15:47:25 +03:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2014-01-28 13:09:43 +04:00
|
|
|
if len(primaryCondiations) > 0 {
|
|
|
|
sql = "WHERE " + strings.Join(primaryCondiations, " AND ")
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) selectSql() string {
|
2014-11-17 15:12:32 +03:00
|
|
|
if len(s.Search.Selects) == 0 {
|
2014-01-26 10:55:41 +04:00
|
|
|
return "*"
|
|
|
|
}
|
2014-11-17 15:12:32 +03:00
|
|
|
|
|
|
|
var selectQueries []string
|
|
|
|
|
|
|
|
for _, clause := range s.Search.Selects {
|
|
|
|
selectQueries = append(selectQueries, s.buildSelectQuery(clause))
|
|
|
|
}
|
|
|
|
|
|
|
|
return strings.Join(selectQueries, ", ")
|
|
|
|
|
2014-01-26 10:55:41 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) orderSql() string {
|
2014-01-28 12:56:51 +04:00
|
|
|
if len(s.Search.Orders) == 0 {
|
2014-01-26 10:55:41 +04:00
|
|
|
return ""
|
|
|
|
} else {
|
2014-01-28 12:56:51 +04:00
|
|
|
return " ORDER BY " + strings.Join(s.Search.Orders, ",")
|
2014-01-26 10:55:41 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) limitSql() string {
|
2014-09-16 00:03:14 +04:00
|
|
|
if !s.Dialect().HasTop() {
|
|
|
|
if len(s.Search.Limit) == 0 {
|
|
|
|
return ""
|
|
|
|
} else {
|
|
|
|
return " LIMIT " + s.Search.Limit
|
|
|
|
}
|
2014-09-16 19:32:35 +04:00
|
|
|
} else {
|
2014-09-16 00:03:14 +04:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-09-16 19:32:35 +04:00
|
|
|
func (s *Scope) topSql() string {
|
2014-09-16 00:03:14 +04:00
|
|
|
if s.Dialect().HasTop() && len(s.Search.Offset) == 0 {
|
|
|
|
if len(s.Search.Limit) == 0 {
|
|
|
|
return ""
|
2014-09-16 19:32:35 +04:00
|
|
|
} else {
|
2014-09-16 00:03:14 +04:00
|
|
|
return " TOP(" + s.Search.Limit + ")"
|
|
|
|
}
|
2014-09-16 19:32:35 +04:00
|
|
|
} else {
|
2014-01-26 10:55:41 +04:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) offsetSql() string {
|
2014-01-28 12:56:51 +04:00
|
|
|
if len(s.Search.Offset) == 0 {
|
2014-01-26 10:55:41 +04:00
|
|
|
return ""
|
|
|
|
} else {
|
2014-09-16 19:32:35 +04:00
|
|
|
if s.Dialect().HasTop() {
|
|
|
|
sql := " OFFSET " + s.Search.Offset + " ROW "
|
|
|
|
if len(s.Search.Limit) > 0 {
|
2014-09-16 00:03:14 +04:00
|
|
|
sql += "FETCH NEXT " + s.Search.Limit + " ROWS ONLY"
|
|
|
|
}
|
|
|
|
return sql
|
2014-09-16 19:32:35 +04:00
|
|
|
} else {
|
2014-09-16 00:03:14 +04:00
|
|
|
return " OFFSET " + s.Search.Offset
|
|
|
|
}
|
2014-01-26 10:55:41 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) groupSql() string {
|
2014-01-28 12:56:51 +04:00
|
|
|
if len(s.Search.Group) == 0 {
|
2014-01-26 10:55:41 +04:00
|
|
|
return ""
|
|
|
|
} else {
|
2014-01-28 12:56:51 +04:00
|
|
|
return " GROUP BY " + s.Search.Group
|
2014-01-26 10:55:41 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) havingSql() string {
|
2014-01-28 12:56:51 +04:00
|
|
|
if s.Search.HavingCondition == nil {
|
2014-01-26 10:55:41 +04:00
|
|
|
return ""
|
|
|
|
} else {
|
2014-01-28 12:56:51 +04:00
|
|
|
return " HAVING " + s.buildWhereCondition(s.Search.HavingCondition)
|
2014-01-26 10:55:41 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Scope) joinsSql() string {
|
2014-01-28 12:56:51 +04:00
|
|
|
return s.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 {
|
2014-09-16 00:03:14 +04:00
|
|
|
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) {
|
2014-07-30 10:58:00 +04:00
|
|
|
data := scope.IndirectValue()
|
2014-01-29 08:00:57 +04:00
|
|
|
if !data.CanAddr() {
|
|
|
|
return values, true
|
|
|
|
}
|
|
|
|
|
|
|
|
for key, value := range values {
|
2014-09-02 15:03:01 +04:00
|
|
|
if field, ok := scope.FieldByName(SnakeToUpperCamel(key)); ok && field.Field.IsValid() {
|
2014-01-30 12:41:10 +04:00
|
|
|
func() {
|
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
|
|
|
hasUpdate = true
|
2014-09-02 15:03:01 +04:00
|
|
|
field.Set(value)
|
2014-01-29 08:00:57 +04:00
|
|
|
}
|
2014-01-30 12:41:10 +04:00
|
|
|
}()
|
|
|
|
|
2014-09-02 15:03:01 +04:00
|
|
|
if field.Field.Interface() != value {
|
|
|
|
switch field.Field.Kind() {
|
2014-01-30 12:41:10 +04:00
|
|
|
case reflect.Int, reflect.Int32, reflect.Int64:
|
|
|
|
if s, ok := value.(string); ok {
|
|
|
|
i, err := strconv.Atoi(s)
|
|
|
|
if scope.Err(err) == nil {
|
|
|
|
value = i
|
|
|
|
}
|
|
|
|
}
|
2014-01-29 08:00:57 +04:00
|
|
|
|
2014-09-02 15:03:01 +04:00
|
|
|
if field.Field.Int() != reflect.ValueOf(value).Int() {
|
2014-01-30 12:41:10 +04:00
|
|
|
hasUpdate = true
|
2014-09-02 15:03:01 +04:00
|
|
|
field.Set(value)
|
2014-01-30 12:41:10 +04:00
|
|
|
}
|
|
|
|
default:
|
2014-01-29 08:00:57 +04:00
|
|
|
hasUpdate = true
|
2014-09-02 15:03:01 +04:00
|
|
|
field.Set(value)
|
2014-01-29 08:00:57 +04:00
|
|
|
}
|
|
|
|
}
|
2014-01-30 12:41:10 +04:00
|
|
|
}()
|
2014-01-29 08:00:57 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-07-29 13:52:23 +04:00
|
|
|
func (scope *Scope) sqlTagForField(field *Field) (typ string) {
|
2014-07-31 07:08:26 +04:00
|
|
|
if scope.db == nil {
|
|
|
|
return ""
|
|
|
|
}
|
2014-07-29 13:52:23 +04:00
|
|
|
var size = 255
|
2014-01-29 08:00:57 +04:00
|
|
|
|
2014-07-29 13:52:23 +04:00
|
|
|
fieldTag := field.Tag.Get(scope.db.parent.tagIdentifier)
|
|
|
|
var setting = parseTagSetting(fieldTag)
|
|
|
|
|
|
|
|
if value, ok := setting["SIZE"]; ok {
|
|
|
|
if i, err := strconv.Atoi(value); err == nil {
|
|
|
|
size = i
|
|
|
|
} else {
|
|
|
|
size = 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if value, ok := setting["TYPE"]; ok {
|
|
|
|
typ = value
|
|
|
|
}
|
|
|
|
|
|
|
|
additionalType := setting["NOT NULL"] + " " + setting["UNIQUE"]
|
|
|
|
if value, ok := setting["DEFAULT"]; ok {
|
|
|
|
additionalType = additionalType + "DEFAULT " + value
|
|
|
|
}
|
|
|
|
|
2014-09-02 15:03:01 +04:00
|
|
|
value := field.Field.Interface()
|
|
|
|
reflectValue := field.Field
|
2015-02-09 16:14:48 +03:00
|
|
|
if reflectValue.Kind() == reflect.Ptr {
|
|
|
|
reflectValue = reflect.New(reflectValue.Type().Elem()).Elem()
|
|
|
|
}
|
2014-01-29 08:00:57 +04:00
|
|
|
|
|
|
|
switch reflectValue.Kind() {
|
|
|
|
case reflect.Slice:
|
|
|
|
if _, ok := value.([]byte); !ok {
|
2015-01-05 03:43:01 +03:00
|
|
|
return typ + " " + additionalType
|
2014-01-29 08:00:57 +04:00
|
|
|
}
|
|
|
|
case reflect.Struct:
|
2014-03-16 05:28:43 +04:00
|
|
|
if field.IsScanner() {
|
2014-08-04 10:37:51 +04:00
|
|
|
var getScannerValue func(reflect.Value)
|
|
|
|
getScannerValue = func(value reflect.Value) {
|
|
|
|
reflectValue = value
|
|
|
|
if _, isScanner := reflect.New(reflectValue.Type()).Interface().(sql.Scanner); isScanner {
|
|
|
|
getScannerValue(reflectValue.Field(0))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
getScannerValue(reflectValue.Field(0))
|
2014-03-16 05:28:43 +04:00
|
|
|
} else if !field.IsTime() {
|
2015-01-05 03:43:01 +03:00
|
|
|
return typ + " " + additionalType
|
2014-01-29 08:00:57 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-29 13:52:23 +04:00
|
|
|
if len(typ) == 0 {
|
2014-07-31 07:08:26 +04:00
|
|
|
if field.IsPrimaryKey {
|
2014-07-29 13:52:23 +04:00
|
|
|
typ = scope.Dialect().PrimaryKeyTag(reflectValue, size)
|
2014-01-29 08:00:57 +04:00
|
|
|
} else {
|
2014-07-29 13:52:23 +04:00
|
|
|
typ = scope.Dialect().SqlTag(reflectValue, size)
|
2014-01-29 08:00:57 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-05 03:43:01 +03:00
|
|
|
return typ + " " + additionalType
|
2014-01-29 08:00:57 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (scope *Scope) row() *sql.Row {
|
2014-08-23 12:00:04 +04:00
|
|
|
defer scope.Trace(NowFunc())
|
2014-01-29 08:00:57 +04:00
|
|
|
scope.prepareQuerySql()
|
|
|
|
return scope.DB().QueryRow(scope.Sql, scope.SqlVars...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (scope *Scope) rows() (*sql.Rows, error) {
|
2014-08-23 12:00:04 +04:00
|
|
|
defer scope.Trace(NowFunc())
|
2014-01-29 08:00:57 +04:00
|
|
|
scope.prepareQuerySql()
|
|
|
|
return scope.DB().Query(scope.Sql, scope.SqlVars...)
|
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
|
|
|
scope.Search = scope.Search.clone().selects("count(*)")
|
|
|
|
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()
|
|
|
|
} else {
|
|
|
|
return value.Type().Name()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
|
2014-03-26 04:48:40 +04:00
|
|
|
toScope := scope.db.NewScope(value)
|
2014-09-08 07:19:05 +04:00
|
|
|
fromScopeType := scope.typeName()
|
|
|
|
toScopeType := toScope.typeName()
|
|
|
|
scopeType := ""
|
2014-01-29 08:00:57 +04:00
|
|
|
|
|
|
|
for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
|
2014-09-08 07:19:05 +04:00
|
|
|
if keys := strings.Split(foreignKey, "."); len(keys) > 1 {
|
|
|
|
scopeType = keys[0]
|
|
|
|
foreignKey = keys[1]
|
|
|
|
}
|
|
|
|
|
2014-11-26 08:23:43 +03:00
|
|
|
var relationship *relationship
|
|
|
|
var field *Field
|
|
|
|
var scopeHasField bool
|
|
|
|
if field, scopeHasField = scope.FieldByName(foreignKey); scopeHasField {
|
|
|
|
relationship = field.Relationship
|
|
|
|
}
|
|
|
|
|
2014-09-08 07:19:05 +04:00
|
|
|
if scopeType == "" || scopeType == fromScopeType {
|
2014-11-26 08:23:43 +03:00
|
|
|
if scopeHasField {
|
2014-09-08 07:19:05 +04:00
|
|
|
if relationship != nil && relationship.ForeignKey != "" {
|
|
|
|
foreignKey = relationship.ForeignKey
|
2014-11-26 08:23:43 +03:00
|
|
|
}
|
2014-09-08 07:19:05 +04:00
|
|
|
|
2014-11-26 08:23:43 +03:00
|
|
|
if relationship != nil && relationship.Kind == "many_to_many" {
|
|
|
|
if relationship.ForeignType != "" {
|
|
|
|
scope.Err(fmt.Errorf("gorm does not support polymorphic many-to-many associations"))
|
2014-09-08 07:19:05 +04:00
|
|
|
}
|
2014-11-26 08:23:43 +03:00
|
|
|
joinSql := fmt.Sprintf(
|
|
|
|
"INNER JOIN %v ON %v.%v = %v.%v",
|
|
|
|
scope.Quote(relationship.JoinTable),
|
|
|
|
scope.Quote(relationship.JoinTable),
|
|
|
|
scope.Quote(ToSnake(relationship.AssociationForeignKey)),
|
|
|
|
toScope.QuotedTableName(),
|
|
|
|
scope.Quote(toScope.PrimaryKey()))
|
|
|
|
whereSql := fmt.Sprintf("%v.%v = ?", scope.Quote(relationship.JoinTable), scope.Quote(ToSnake(relationship.ForeignKey)))
|
|
|
|
toScope.db.Joins(joinSql).Where(whereSql, scope.PrimaryKeyValue()).Find(value)
|
|
|
|
return scope
|
2014-07-30 16:48:36 +04:00
|
|
|
}
|
|
|
|
|
2014-11-26 08:23:43 +03:00
|
|
|
// has many or has one
|
|
|
|
if toScope.HasColumn(foreignKey) {
|
|
|
|
toScope.inlineCondition(fmt.Sprintf("%v = ?", scope.Quote(ToSnake(foreignKey))), scope.PrimaryKeyValue())
|
|
|
|
if relationship != nil && relationship.ForeignType != "" && toScope.HasColumn(relationship.ForeignType) {
|
|
|
|
toScope.inlineCondition(fmt.Sprintf("%v = ?", scope.Quote(ToSnake(relationship.ForeignType))), scope.TableName())
|
|
|
|
}
|
|
|
|
toScope.callCallbacks(scope.db.parent.callback.queries)
|
|
|
|
return scope
|
|
|
|
}
|
|
|
|
|
|
|
|
// belongs to
|
2014-10-01 17:58:13 +04:00
|
|
|
if foreignValue, err := scope.FieldValueByName(foreignKey); err == nil {
|
2014-11-12 05:23:51 +03:00
|
|
|
sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey()))
|
2014-11-26 08:23:43 +03:00
|
|
|
if relationship != nil && relationship.ForeignType != "" && scope.HasColumn(relationship.ForeignType) {
|
|
|
|
scope.Err(fmt.Errorf("gorm does not support polymorphic belongs_to associations"))
|
|
|
|
return scope
|
|
|
|
}
|
2014-10-28 03:29:33 +03:00
|
|
|
toScope.inlineCondition(sql, foreignValue).callCallbacks(scope.db.parent.callback.queries)
|
2014-09-08 07:19:05 +04:00
|
|
|
return scope
|
|
|
|
}
|
2014-07-30 16:48:36 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-09-08 07:19:05 +04:00
|
|
|
if scopeType == "" || scopeType == toScopeType {
|
2014-11-26 08:23:43 +03:00
|
|
|
// has many or has one in foreign scope
|
2014-09-08 07:19:05 +04:00
|
|
|
if toScope.HasColumn(foreignKey) {
|
|
|
|
sql := fmt.Sprintf("%v = ?", scope.Quote(ToSnake(foreignKey)))
|
|
|
|
return toScope.inlineCondition(sql, scope.PrimaryKeyValue()).callCallbacks(scope.db.parent.callback.queries)
|
|
|
|
}
|
2014-01-29 08:00:57 +04: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
|
|
|
|
}
|
|
|
|
|
2014-07-30 10:20:38 +04:00
|
|
|
func (scope *Scope) createJoinTable(field *Field) {
|
2014-07-31 07:08:26 +04:00
|
|
|
if field.Relationship != nil && field.Relationship.JoinTable != "" {
|
|
|
|
if !scope.Dialect().HasTable(scope, field.Relationship.JoinTable) {
|
2014-07-30 10:20:38 +04:00
|
|
|
newScope := scope.db.NewScope("")
|
|
|
|
primaryKeySqlType := scope.Dialect().SqlTag(reflect.ValueOf(scope.PrimaryKeyValue()), 255)
|
|
|
|
newScope.Raw(fmt.Sprintf("CREATE TABLE %v (%v)",
|
2014-07-31 07:08:26 +04:00
|
|
|
field.Relationship.JoinTable,
|
2014-07-30 10:20:38 +04:00
|
|
|
strings.Join([]string{
|
2014-07-31 07:08:26 +04:00
|
|
|
scope.Quote(ToSnake(field.Relationship.ForeignKey)) + " " + primaryKeySqlType,
|
|
|
|
scope.Quote(ToSnake(field.Relationship.AssociationForeignKey)) + " " + primaryKeySqlType}, ",")),
|
2014-07-30 10:20:38 +04:00
|
|
|
).Exec()
|
|
|
|
scope.Err(newScope.db.Error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-29 08:00:57 +04:00
|
|
|
func (scope *Scope) createTable() *Scope {
|
|
|
|
var sqls []string
|
2014-11-16 07:31:00 +03:00
|
|
|
fields := scope.Fields()
|
|
|
|
scopeType := scope.IndirectValue().Type()
|
|
|
|
for i := 0; i < scopeType.NumField(); i++ {
|
2014-11-19 06:44:57 +03:00
|
|
|
if !ast.IsExported(scopeType.Field(i).Name) {
|
|
|
|
continue
|
|
|
|
}
|
2014-11-16 07:31:00 +03:00
|
|
|
for _, field := range scope.fieldFromStruct(scopeType.Field(i), false) {
|
2015-02-05 12:42:24 +03:00
|
|
|
name := field.Name
|
|
|
|
for _, field := range fields {
|
|
|
|
if field.Name == name {
|
|
|
|
if field.IsNormal {
|
|
|
|
sqlTag := scope.sqlTagForField(field)
|
|
|
|
sqls = append(sqls, scope.Quote(field.DBName)+" "+sqlTag)
|
|
|
|
}
|
|
|
|
scope.createJoinTable(field)
|
|
|
|
}
|
2014-11-16 07:31:00 +03:00
|
|
|
}
|
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 {
|
|
|
|
scope.Raw(fmt.Sprintf("DROP TABLE IF EXISTS %v", scope.QuotedTableName())).Exec()
|
|
|
|
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"
|
|
|
|
}
|
|
|
|
|
2014-06-03 12:52:55 +04:00
|
|
|
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) {
|
|
|
|
var table string = scope.TableName()
|
|
|
|
var keyName string = fmt.Sprintf("%s_%s_foreign", table, field)
|
|
|
|
var query string = `
|
|
|
|
ALTER TABLE %s
|
|
|
|
ADD CONSTRAINT %s
|
|
|
|
FOREIGN KEY (%s)
|
|
|
|
REFERENCES %s
|
|
|
|
ON DELETE %s
|
|
|
|
ON UPDATE %s;
|
|
|
|
`
|
|
|
|
scope.Raw(fmt.Sprintf(query, table, keyName, field, dest, onDelete, onUpdate)).Exec()
|
|
|
|
}
|
|
|
|
|
2014-01-29 08:00:57 +04:00
|
|
|
func (scope *Scope) removeIndex(indexName string) {
|
2014-07-29 08:02:03 +04:00
|
|
|
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 {
|
|
|
|
for _, field := range scope.Fields() {
|
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 {
|
|
|
|
sqlTag := scope.sqlTagForField(field)
|
|
|
|
scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, field.DBName, sqlTag)).Exec()
|
2014-04-25 05:08:48 +04:00
|
|
|
}
|
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
|
|
|
|
}
|