gorm/scope.go

468 lines
11 KiB
Go
Raw Normal View History

2014-01-26 08:41:37 +04:00
package gorm
2014-01-26 09:51:23 +04:00
import (
"errors"
"fmt"
2015-08-01 04:25:06 +03:00
"regexp"
2014-01-26 10:18:21 +04:00
"strings"
2014-01-26 13:10:33 +04:00
"time"
2014-01-26 09:51:23 +04:00
"reflect"
)
2014-01-26 08:41:37 +04:00
type Scope struct {
Search *search
2015-03-12 08:52:29 +03:00
Value interface{}
Sql string
SqlVars []interface{}
db *DB
2015-03-12 08:52:29 +03:00
indirectValue *reflect.Value
instanceId string
2015-03-12 08:52:29 +03:00
primaryKeyField *Field
skipLeft bool
fields map[string]*Field
selectAttrs *[]string
2014-07-30 10:58:00 +04:00
}
func (scope *Scope) IndirectValue() reflect.Value {
if scope.indirectValue == nil {
value := reflect.Indirect(reflect.ValueOf(scope.Value))
2015-02-17 18:36:23 +03:00
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
2014-07-30 10:58:00 +04:00
scope.indirectValue = &value
}
return *scope.indirectValue
2014-01-26 08:41:37 +04:00
}
func (scope *Scope) NeedPtr() *Scope {
reflectKind := reflect.ValueOf(scope.Value).Kind()
if !((reflectKind == reflect.Invalid) || (reflectKind == reflect.Ptr)) {
2015-02-17 02:15:34 +03:00
err := fmt.Errorf("%v %v\n", fileWithLineNum(), "using unaddressable value")
scope.Err(err)
fmt.Printf(err.Error())
}
return scope
}
2014-01-29 15:14:37 +04:00
// New create a new Scope without search information
2014-01-27 04:26:59 +04:00
func (scope *Scope) New(value interface{}) *Scope {
2015-02-26 07:35:33 +03:00
return &Scope{db: scope.NewDB(), Search: &search{}, Value: value}
2014-01-27 04:26:59 +04:00
}
2014-01-29 15:14:37 +04:00
// NewDB create a new DB without search information
2014-01-27 04:26:59 +04:00
func (scope *Scope) NewDB() *DB {
2015-02-26 07:35:33 +03:00
if scope.db != nil {
db := scope.db.clone()
db.search = nil
db.Value = nil
2015-02-26 07:35:33 +03:00
return db
}
return nil
2014-01-27 04:26:59 +04:00
}
func (scope *Scope) DB() *DB {
return scope.db
}
2015-02-26 07:35:33 +03:00
// SqlDB return *sql.DB
func (scope *Scope) SqlDB() sqlCommon {
2014-01-26 08:41:37 +04:00
return scope.db.db
}
2014-01-29 15:14:37 +04:00
// SkipLeft skip remaining callbacks
2014-01-29 08:00:57 +04:00
func (scope *Scope) SkipLeft() {
scope.skipLeft = true
}
2014-01-29 15:14:37 +04:00
// Quote used to quote database column name according to database dialect
2014-01-29 08:00:57 +04:00
func (scope *Scope) Quote(str string) string {
2015-02-24 13:02:22 +03:00
if strings.Index(str, ".") != -1 {
newStrs := []string{}
2015-02-26 07:35:33 +03:00
for _, str := range strings.Split(str, ".") {
2015-02-24 13:02:22 +03:00
newStrs = append(newStrs, scope.Dialect().Quote(str))
}
return strings.Join(newStrs, ".")
} else {
return scope.Dialect().Quote(str)
}
2014-01-29 08:00:57 +04:00
}
2015-08-01 04:25:06 +03:00
func (scope *Scope) QuoteIfPossible(str string) string {
if regexp.MustCompile("^[a-zA-Z]+(.[a-zA-Z]+)*$").MatchString(str) {
return scope.Quote(str)
}
return str
}
2014-01-29 15:14:37 +04:00
// Dialect get dialect
func (scope *Scope) Dialect() Dialect {
2014-01-26 08:41:37 +04:00
return scope.db.parent.dialect
}
2014-01-29 15:14:37 +04:00
// Err write error
2014-01-26 08:41:37 +04:00
func (scope *Scope) Err(err error) error {
if err != nil {
2015-08-13 11:42:13 +03:00
scope.db.AddError(err)
2014-01-26 08:41:37 +04:00
}
return err
}
2014-01-29 15:14:37 +04:00
// Log print log message
func (scope *Scope) Log(v ...interface{}) {
scope.db.log(v...)
}
2014-01-29 15:14:37 +04:00
// HasError check if there are any error
2014-01-26 08:41:37 +04:00
func (scope *Scope) HasError() bool {
2014-01-28 12:29:42 +04:00
return scope.db.Error != nil
2014-01-26 08:41:37 +04:00
}
2015-06-29 13:04:15 +03:00
func (scope *Scope) PrimaryFields() []*Field {
var fields = []*Field{}
for _, field := range scope.GetModelStruct().PrimaryFields {
fields = append(fields, scope.Fields()[field.DBName])
}
return fields
}
2015-03-11 06:28:30 +03:00
func (scope *Scope) PrimaryField() *Field {
if primaryFields := scope.GetModelStruct().PrimaryFields; len(primaryFields) > 0 {
if len(primaryFields) > 1 {
if field, ok := scope.Fields()["id"]; ok {
return field
}
}
return scope.Fields()[primaryFields[0].DBName]
2015-02-17 09:30:37 +03:00
}
return nil
}
// PrimaryKey get the primary key's column name
func (scope *Scope) PrimaryKey() string {
2015-03-11 06:28:30 +03:00
if field := scope.PrimaryField(); field != nil {
return field.DBName
}
2015-02-17 02:15:34 +03:00
return ""
2014-01-26 08:41:37 +04:00
}
2014-01-29 15:14:37 +04:00
// PrimaryKeyZero check the primary key is blank or not
2014-01-26 13:10:33 +04:00
func (scope *Scope) PrimaryKeyZero() bool {
2015-03-11 06:28:30 +03:00
field := scope.PrimaryField()
2015-02-17 17:55:14 +03:00
return field == nil || field.IsBlank
2014-01-26 13:10:33 +04:00
}
2014-01-29 15:14:37 +04:00
// PrimaryKeyValue get the primary key's value
2014-01-26 13:10:33 +04:00
func (scope *Scope) PrimaryKeyValue() interface{} {
2015-03-11 06:28:30 +03:00
if field := scope.PrimaryField(); field != nil && field.Field.IsValid() {
return field.Field.Interface()
2014-01-26 13:10:33 +04:00
}
2015-02-17 02:15:34 +03:00
return 0
2014-01-26 13:10:33 +04:00
}
2014-01-29 15:14:37 +04:00
// HasColumn to check if has column
2015-01-19 11:23:33 +03:00
func (scope *Scope) HasColumn(column string) bool {
2015-02-17 12:40:21 +03:00
for _, field := range scope.GetStructFields() {
2015-02-17 17:55:14 +03:00
if field.IsNormal && (field.Name == column || field.DBName == column) {
return true
2015-02-17 12:40:21 +03:00
}
}
2015-02-17 12:40:21 +03:00
return false
2014-01-28 08:28:44 +04:00
}
2014-01-29 15:14:37 +04:00
// SetColumn to set the column's value
func (scope *Scope) SetColumn(column interface{}, value interface{}) error {
2014-09-02 15:03:01 +04:00
if field, ok := column.(*Field); ok {
return field.Set(value)
} else if name, ok := column.(string); ok {
if field, ok := scope.Fields()[name]; ok {
2015-01-16 05:02:04 +03:00
return field.Set(value)
}
dbName := ToDBName(name)
if field, ok := scope.Fields()[dbName]; ok {
return field.Set(value)
2014-08-30 18:39:28 +04:00
}
if field, ok := scope.FieldByName(name); ok {
return field.Set(value)
}
2014-08-30 18:39:28 +04:00
}
return errors.New("could not convert column to field")
2014-01-26 08:41:37 +04:00
}
2015-02-24 11:28:15 +03:00
func (scope *Scope) CallMethod(name string, checkError bool) {
2015-04-21 06:24:48 +03:00
if scope.Value == nil || (checkError && scope.HasError()) {
2014-01-27 18:36:08 +04:00
return
}
2014-01-28 05:25:30 +04:00
call := func(value interface{}) {
if fm := reflect.ValueOf(value).MethodByName(name); fm.IsValid() {
switch f := fm.Interface().(type) {
2014-10-07 18:33:57 +04:00
case func():
f()
case func(s *Scope):
f(scope)
case func(s *DB):
newDB := scope.NewDB()
f(newDB)
scope.Err(newDB.Error)
2014-10-07 18:33:57 +04:00
case func() error:
scope.Err(f())
case func(s *Scope) error:
scope.Err(f(scope))
case func(s *DB) error:
2015-08-17 11:38:01 +03:00
newDB := scope.NewDB()
scope.Err(f(newDB))
scope.Err(newDB.Error)
2014-10-07 18:33:57 +04:00
default:
2015-02-17 02:15:34 +03:00
scope.Err(fmt.Errorf("unsupported function %v", name))
2014-01-28 05:25:30 +04:00
}
2014-01-26 09:51:23 +04:00
}
}
2014-01-28 05:25:30 +04:00
2014-07-30 10:58:00 +04:00
if values := scope.IndirectValue(); values.Kind() == reflect.Slice {
2014-01-28 05:25:30 +04:00
for i := 0; i < values.Len(); i++ {
value := values.Index(i).Addr().Interface()
if values.Index(i).Kind() == reflect.Ptr {
value = values.Index(i).Interface()
}
call(value)
2014-01-28 05:25:30 +04:00
}
} else {
if scope.IndirectValue().CanAddr() {
call(scope.IndirectValue().Addr().Interface())
} else {
call(scope.IndirectValue().Interface())
}
2014-01-28 05:25:30 +04:00
}
2014-01-26 08:41:37 +04:00
}
2015-02-24 11:28:15 +03:00
func (scope *Scope) CallMethodWithErrorCheck(name string) {
scope.CallMethod(name, true)
}
2014-01-29 15:14:37 +04:00
// AddToVars add value as sql's vars, gorm will escape them
2014-01-26 08:41:37 +04:00
func (scope *Scope) AddToVars(value interface{}) string {
2015-02-24 17:06:35 +03:00
if expr, ok := value.(*expr); ok {
exp := expr.expr
for _, arg := range expr.args {
exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
}
return exp
} else {
scope.SqlVars = append(scope.SqlVars, value)
return scope.Dialect().BinVar(len(scope.SqlVars))
}
2014-01-26 08:41:37 +04:00
}
2015-04-08 06:36:01 +03:00
type tabler interface {
TableName() string
}
type dbTabler interface {
TableName(*DB) string
}
2014-01-29 15:14:37 +04:00
// TableName get table name
2014-01-26 08:41:37 +04:00
func (scope *Scope) TableName() string {
if strTableName, ok := scope.Value.(string); ok {
return strTableName
}
2015-03-12 08:52:29 +03:00
if scope.Search != nil && len(scope.Search.tableName) > 0 {
return scope.Search.tableName
2015-02-17 03:34:01 +03:00
}
2015-04-08 06:36:01 +03:00
if tabler, ok := scope.Value.(tabler); ok {
return tabler.TableName()
}
if tabler, ok := scope.Value.(dbTabler); ok {
return tabler.TableName(scope.db)
}
2015-06-30 05:39:29 +03:00
return scope.GetModelStruct().TableName(scope.db.Model(scope.Value))
2014-01-26 10:18:21 +04:00
}
func (scope *Scope) QuotedTableName() (name string) {
2015-03-12 08:52:29 +03:00
if scope.Search != nil && len(scope.Search.tableName) > 0 {
2015-05-19 05:43:32 +03:00
if strings.Index(scope.Search.tableName, " ") != -1 {
return scope.Search.tableName
}
2015-03-12 08:52:29 +03:00
return scope.Quote(scope.Search.tableName)
} else {
return scope.Quote(scope.TableName())
2014-06-03 13:15:05 +04:00
}
}
2014-01-29 15:14:37 +04:00
// CombinedConditionSql get combined condition sql
2014-01-29 04:55:45 +04:00
func (scope *Scope) CombinedConditionSql() string {
return scope.joinsSql() + scope.whereSql() + scope.groupSql() +
scope.havingSql() + scope.orderSql() + scope.limitSql() + scope.offsetSql()
2014-01-26 10:55:41 +04:00
}
2014-07-31 07:08:26 +04:00
func (scope *Scope) FieldByName(name string) (field *Field, ok bool) {
2014-09-02 15:03:01 +04:00
for _, field := range scope.Fields() {
2015-06-04 07:10:09 +03:00
if field.Name == name || field.DBName == name {
2014-09-02 15:03:01 +04:00
return field, true
2014-07-31 07:08:26 +04:00
}
}
2014-08-28 13:21:43 +04:00
return nil, false
2014-07-31 07:08:26 +04:00
}
2014-01-29 15:14:37 +04:00
// Raw set sql
2014-01-28 11:54:19 +04:00
func (scope *Scope) Raw(sql string) *Scope {
2014-01-26 10:18:21 +04:00
scope.Sql = strings.Replace(sql, "$$", "?", -1)
2014-01-28 11:54:19 +04:00
return scope
2014-01-26 08:41:37 +04:00
}
2014-01-29 15:14:37 +04:00
// Exec invoke sql
2014-01-28 06:23:31 +04:00
func (scope *Scope) Exec() *Scope {
defer scope.Trace(NowFunc())
2014-01-28 11:54:19 +04:00
2014-01-26 10:18:21 +04:00
if !scope.HasError() {
2015-02-26 07:35:33 +03:00
if result, err := scope.SqlDB().Exec(scope.Sql, scope.SqlVars...); scope.Err(err) == nil {
if count, err := result.RowsAffected(); scope.Err(err) == nil {
2014-06-05 13:58:14 +04:00
scope.db.RowsAffected = count
}
}
2014-01-26 10:18:21 +04:00
}
2014-01-28 06:23:31 +04:00
return scope
2014-01-26 08:41:37 +04:00
}
2014-01-26 13:10:33 +04:00
2014-01-29 15:14:37 +04:00
// Set set value by name
func (scope *Scope) Set(name string, value interface{}) *Scope {
2014-08-25 13:10:46 +04:00
scope.db.InstantSet(name, value)
return scope
2014-01-27 07:56:04 +04:00
}
2014-01-29 15:14:37 +04:00
// Get get value by name
2014-08-20 12:25:01 +04:00
func (scope *Scope) Get(name string) (interface{}, bool) {
return scope.db.Get(name)
2014-01-29 15:14:37 +04:00
}
// InstanceId get InstanceId for scope
func (scope *Scope) InstanceId() string {
if scope.instanceId == "" {
2015-01-26 12:59:31 +03:00
scope.instanceId = fmt.Sprintf("%v%v", &scope, &scope.db)
}
return scope.instanceId
}
func (scope *Scope) InstanceSet(name string, value interface{}) *Scope {
return scope.Set(name+scope.InstanceId(), value)
}
func (scope *Scope) InstanceGet(name string) (interface{}, bool) {
return scope.Get(name + scope.InstanceId())
}
2014-01-29 15:14:37 +04:00
// Trace print sql log
2014-01-26 13:10:33 +04:00
func (scope *Scope) Trace(t time.Time) {
if len(scope.Sql) > 0 {
scope.db.slog(scope.Sql, t, scope.SqlVars...)
}
}
2014-01-29 15:14:37 +04:00
// Begin start a transaction
2014-01-26 13:10:33 +04:00
func (scope *Scope) Begin() *Scope {
2015-02-26 07:35:33 +03:00
if db, ok := scope.SqlDB().(sqlDb); ok {
2014-01-27 06:47:37 +04:00
if tx, err := db.Begin(); err == nil {
scope.db.db = interface{}(tx).(sqlCommon)
scope.InstanceSet("gorm:started_transaction", true)
2014-01-27 06:47:37 +04:00
}
2014-01-26 13:10:33 +04:00
}
return scope
}
2014-01-29 15:14:37 +04:00
// CommitOrRollback commit current transaction if there is no error, otherwise rollback it
2014-01-26 13:10:33 +04:00
func (scope *Scope) CommitOrRollback() *Scope {
if _, ok := scope.InstanceGet("gorm:started_transaction"); ok {
2014-01-26 13:10:33 +04:00
if db, ok := scope.db.db.(sqlTx); ok {
if scope.HasError() {
db.Rollback()
} else {
2016-01-04 08:32:35 +03:00
scope.Err(db.Commit())
2014-01-26 13:10:33 +04:00
}
scope.db.db = scope.db.parent.db
}
}
return scope
}
2015-03-12 12:47:31 +03:00
func (scope *Scope) SelectAttrs() []string {
if scope.selectAttrs == nil {
attrs := []string{}
for _, value := range scope.Search.selects {
if str, ok := value.(string); ok {
attrs = append(attrs, str)
2015-05-11 10:17:35 +03:00
} else if strs, ok := value.([]string); ok {
attrs = append(attrs, strs...)
} else if strs, ok := value.([]interface{}); ok {
for _, str := range strs {
attrs = append(attrs, fmt.Sprintf("%v", str))
}
2015-03-12 12:47:31 +03:00
}
}
scope.selectAttrs = &attrs
2015-03-12 12:47:31 +03:00
}
return *scope.selectAttrs
2015-03-12 12:47:31 +03:00
}
func (scope *Scope) OmitAttrs() []string {
return scope.Search.omits
}
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
}
2015-03-12 13:30:59 +03:00
func (scope *Scope) changeableField(field *Field) bool {
2015-03-12 12:47:31 +03:00
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()
}