OSDN Git Service

feat: init cross_tx keepers (#146)
[bytom/vapor.git] / vendor / github.com / jinzhu / gorm / scope.go
1 package gorm
2
3 import (
4         "bytes"
5         "database/sql"
6         "database/sql/driver"
7         "errors"
8         "fmt"
9         "reflect"
10         "regexp"
11         "strings"
12         "time"
13 )
14
15 // Scope contain current operation's information when you perform any operation on the database
16 type Scope struct {
17         Search          *search
18         Value           interface{}
19         SQL             string
20         SQLVars         []interface{}
21         db              *DB
22         instanceID      string
23         primaryKeyField *Field
24         skipLeft        bool
25         fields          *[]*Field
26         selectAttrs     *[]string
27 }
28
29 // IndirectValue return scope's reflect value's indirect value
30 func (scope *Scope) IndirectValue() reflect.Value {
31         return indirect(reflect.ValueOf(scope.Value))
32 }
33
34 // New create a new Scope without search information
35 func (scope *Scope) New(value interface{}) *Scope {
36         return &Scope{db: scope.NewDB(), Search: &search{}, Value: value}
37 }
38
39 ////////////////////////////////////////////////////////////////////////////////
40 // Scope DB
41 ////////////////////////////////////////////////////////////////////////////////
42
43 // DB return scope's DB connection
44 func (scope *Scope) DB() *DB {
45         return scope.db
46 }
47
48 // NewDB create a new DB without search information
49 func (scope *Scope) NewDB() *DB {
50         if scope.db != nil {
51                 db := scope.db.clone()
52                 db.search = nil
53                 db.Value = nil
54                 return db
55         }
56         return nil
57 }
58
59 // SQLDB return *sql.DB
60 func (scope *Scope) SQLDB() SQLCommon {
61         return scope.db.db
62 }
63
64 // Dialect get dialect
65 func (scope *Scope) Dialect() Dialect {
66         return scope.db.dialect
67 }
68
69 // Quote used to quote string to escape them for database
70 func (scope *Scope) Quote(str string) string {
71         if strings.Contains(str, ".") {
72                 newStrs := []string{}
73                 for _, str := range strings.Split(str, ".") {
74                         newStrs = append(newStrs, scope.Dialect().Quote(str))
75                 }
76                 return strings.Join(newStrs, ".")
77         }
78
79         return scope.Dialect().Quote(str)
80 }
81
82 // Err add error to Scope
83 func (scope *Scope) Err(err error) error {
84         if err != nil {
85                 scope.db.AddError(err)
86         }
87         return err
88 }
89
90 // HasError check if there are any error
91 func (scope *Scope) HasError() bool {
92         return scope.db.Error != nil
93 }
94
95 // Log print log message
96 func (scope *Scope) Log(v ...interface{}) {
97         scope.db.log(v...)
98 }
99
100 // SkipLeft skip remaining callbacks
101 func (scope *Scope) SkipLeft() {
102         scope.skipLeft = true
103 }
104
105 // Fields get value's fields
106 func (scope *Scope) Fields() []*Field {
107         if scope.fields == nil {
108                 var (
109                         fields             []*Field
110                         indirectScopeValue = scope.IndirectValue()
111                         isStruct           = indirectScopeValue.Kind() == reflect.Struct
112                 )
113
114                 for _, structField := range scope.GetModelStruct().StructFields {
115                         if isStruct {
116                                 fieldValue := indirectScopeValue
117                                 for _, name := range structField.Names {
118                                         if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
119                                                 fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
120                                         }
121                                         fieldValue = reflect.Indirect(fieldValue).FieldByName(name)
122                                 }
123                                 fields = append(fields, &Field{StructField: structField, Field: fieldValue, IsBlank: isBlank(fieldValue)})
124                         } else {
125                                 fields = append(fields, &Field{StructField: structField, IsBlank: true})
126                         }
127                 }
128                 scope.fields = &fields
129         }
130
131         return *scope.fields
132 }
133
134 // FieldByName find `gorm.Field` with field name or db name
135 func (scope *Scope) FieldByName(name string) (field *Field, ok bool) {
136         var (
137                 dbName           = ToColumnName(name)
138                 mostMatchedField *Field
139         )
140
141         for _, field := range scope.Fields() {
142                 if field.Name == name || field.DBName == name {
143                         return field, true
144                 }
145                 if field.DBName == dbName {
146                         mostMatchedField = field
147                 }
148         }
149         return mostMatchedField, mostMatchedField != nil
150 }
151
152 // PrimaryFields return scope's primary fields
153 func (scope *Scope) PrimaryFields() (fields []*Field) {
154         for _, field := range scope.Fields() {
155                 if field.IsPrimaryKey {
156                         fields = append(fields, field)
157                 }
158         }
159         return fields
160 }
161
162 // PrimaryField return scope's main primary field, if defined more that one primary fields, will return the one having column name `id` or the first one
163 func (scope *Scope) PrimaryField() *Field {
164         if primaryFields := scope.GetModelStruct().PrimaryFields; len(primaryFields) > 0 {
165                 if len(primaryFields) > 1 {
166                         if field, ok := scope.FieldByName("id"); ok {
167                                 return field
168                         }
169                 }
170                 return scope.PrimaryFields()[0]
171         }
172         return nil
173 }
174
175 // PrimaryKey get main primary field's db name
176 func (scope *Scope) PrimaryKey() string {
177         if field := scope.PrimaryField(); field != nil {
178                 return field.DBName
179         }
180         return ""
181 }
182
183 // PrimaryKeyZero check main primary field's value is blank or not
184 func (scope *Scope) PrimaryKeyZero() bool {
185         field := scope.PrimaryField()
186         return field == nil || field.IsBlank
187 }
188
189 // PrimaryKeyValue get the primary key's value
190 func (scope *Scope) PrimaryKeyValue() interface{} {
191         if field := scope.PrimaryField(); field != nil && field.Field.IsValid() {
192                 return field.Field.Interface()
193         }
194         return 0
195 }
196
197 // HasColumn to check if has column
198 func (scope *Scope) HasColumn(column string) bool {
199         for _, field := range scope.GetStructFields() {
200                 if field.IsNormal && (field.Name == column || field.DBName == column) {
201                         return true
202                 }
203         }
204         return false
205 }
206
207 // SetColumn to set the column's value, column could be field or field's name/dbname
208 func (scope *Scope) SetColumn(column interface{}, value interface{}) error {
209         var updateAttrs = map[string]interface{}{}
210         if attrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
211                 updateAttrs = attrs.(map[string]interface{})
212                 defer scope.InstanceSet("gorm:update_attrs", updateAttrs)
213         }
214
215         if field, ok := column.(*Field); ok {
216                 updateAttrs[field.DBName] = value
217                 return field.Set(value)
218         } else if name, ok := column.(string); ok {
219                 var (
220                         dbName           = ToDBName(name)
221                         mostMatchedField *Field
222                 )
223                 for _, field := range scope.Fields() {
224                         if field.DBName == value {
225                                 updateAttrs[field.DBName] = value
226                                 return field.Set(value)
227                         }
228                         if (field.DBName == dbName) || (field.Name == name && mostMatchedField == nil) {
229                                 mostMatchedField = field
230                         }
231                 }
232
233                 if mostMatchedField != nil {
234                         updateAttrs[mostMatchedField.DBName] = value
235                         return mostMatchedField.Set(value)
236                 }
237         }
238         return errors.New("could not convert column to field")
239 }
240
241 // CallMethod call scope value's method, if it is a slice, will call its element's method one by one
242 func (scope *Scope) CallMethod(methodName string) {
243         if scope.Value == nil {
244                 return
245         }
246
247         if indirectScopeValue := scope.IndirectValue(); indirectScopeValue.Kind() == reflect.Slice {
248                 for i := 0; i < indirectScopeValue.Len(); i++ {
249                         scope.callMethod(methodName, indirectScopeValue.Index(i))
250                 }
251         } else {
252                 scope.callMethod(methodName, indirectScopeValue)
253         }
254 }
255
256 // AddToVars add value as sql's vars, used to prevent SQL injection
257 func (scope *Scope) AddToVars(value interface{}) string {
258         _, skipBindVar := scope.InstanceGet("skip_bindvar")
259
260         if expr, ok := value.(*expr); ok {
261                 exp := expr.expr
262                 for _, arg := range expr.args {
263                         if skipBindVar {
264                                 scope.AddToVars(arg)
265                         } else {
266                                 exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
267                         }
268                 }
269                 return exp
270         }
271
272         scope.SQLVars = append(scope.SQLVars, value)
273
274         if skipBindVar {
275                 return "?"
276         }
277         return scope.Dialect().BindVar(len(scope.SQLVars))
278 }
279
280 // SelectAttrs return selected attributes
281 func (scope *Scope) SelectAttrs() []string {
282         if scope.selectAttrs == nil {
283                 attrs := []string{}
284                 for _, value := range scope.Search.selects {
285                         if str, ok := value.(string); ok {
286                                 attrs = append(attrs, str)
287                         } else if strs, ok := value.([]string); ok {
288                                 attrs = append(attrs, strs...)
289                         } else if strs, ok := value.([]interface{}); ok {
290                                 for _, str := range strs {
291                                         attrs = append(attrs, fmt.Sprintf("%v", str))
292                                 }
293                         }
294                 }
295                 scope.selectAttrs = &attrs
296         }
297         return *scope.selectAttrs
298 }
299
300 // OmitAttrs return omitted attributes
301 func (scope *Scope) OmitAttrs() []string {
302         return scope.Search.omits
303 }
304
305 type tabler interface {
306         TableName() string
307 }
308
309 type dbTabler interface {
310         TableName(*DB) string
311 }
312
313 // TableName return table name
314 func (scope *Scope) TableName() string {
315         if scope.Search != nil && len(scope.Search.tableName) > 0 {
316                 return scope.Search.tableName
317         }
318
319         if tabler, ok := scope.Value.(tabler); ok {
320                 return tabler.TableName()
321         }
322
323         if tabler, ok := scope.Value.(dbTabler); ok {
324                 return tabler.TableName(scope.db)
325         }
326
327         return scope.GetModelStruct().TableName(scope.db.Model(scope.Value))
328 }
329
330 // QuotedTableName return quoted table name
331 func (scope *Scope) QuotedTableName() (name string) {
332         if scope.Search != nil && len(scope.Search.tableName) > 0 {
333                 if strings.Contains(scope.Search.tableName, " ") {
334                         return scope.Search.tableName
335                 }
336                 return scope.Quote(scope.Search.tableName)
337         }
338
339         return scope.Quote(scope.TableName())
340 }
341
342 // CombinedConditionSql return combined condition sql
343 func (scope *Scope) CombinedConditionSql() string {
344         joinSQL := scope.joinsSQL()
345         whereSQL := scope.whereSQL()
346         if scope.Search.raw {
347                 whereSQL = strings.TrimSuffix(strings.TrimPrefix(whereSQL, "WHERE ("), ")")
348         }
349         return joinSQL + whereSQL + scope.groupSQL() +
350                 scope.havingSQL() + scope.orderSQL() + scope.limitAndOffsetSQL()
351 }
352
353 // Raw set raw sql
354 func (scope *Scope) Raw(sql string) *Scope {
355         scope.SQL = strings.Replace(sql, "$$$", "?", -1)
356         return scope
357 }
358
359 // Exec perform generated SQL
360 func (scope *Scope) Exec() *Scope {
361         defer scope.trace(NowFunc())
362
363         if !scope.HasError() {
364                 if result, err := scope.SQLDB().Exec(scope.SQL, scope.SQLVars...); scope.Err(err) == nil {
365                         if count, err := result.RowsAffected(); scope.Err(err) == nil {
366                                 scope.db.RowsAffected = count
367                         }
368                 }
369         }
370         return scope
371 }
372
373 // Set set value by name
374 func (scope *Scope) Set(name string, value interface{}) *Scope {
375         scope.db.InstantSet(name, value)
376         return scope
377 }
378
379 // Get get setting by name
380 func (scope *Scope) Get(name string) (interface{}, bool) {
381         return scope.db.Get(name)
382 }
383
384 // InstanceID get InstanceID for scope
385 func (scope *Scope) InstanceID() string {
386         if scope.instanceID == "" {
387                 scope.instanceID = fmt.Sprintf("%v%v", &scope, &scope.db)
388         }
389         return scope.instanceID
390 }
391
392 // InstanceSet set instance setting for current operation, but not for operations in callbacks, like saving associations callback
393 func (scope *Scope) InstanceSet(name string, value interface{}) *Scope {
394         return scope.Set(name+scope.InstanceID(), value)
395 }
396
397 // InstanceGet get instance setting from current operation
398 func (scope *Scope) InstanceGet(name string) (interface{}, bool) {
399         return scope.Get(name + scope.InstanceID())
400 }
401
402 // Begin start a transaction
403 func (scope *Scope) Begin() *Scope {
404         if db, ok := scope.SQLDB().(sqlDb); ok {
405                 if tx, err := db.Begin(); err == nil {
406                         scope.db.db = interface{}(tx).(SQLCommon)
407                         scope.InstanceSet("gorm:started_transaction", true)
408                 }
409         }
410         return scope
411 }
412
413 // CommitOrRollback commit current transaction if no error happened, otherwise will rollback it
414 func (scope *Scope) CommitOrRollback() *Scope {
415         if _, ok := scope.InstanceGet("gorm:started_transaction"); ok {
416                 if db, ok := scope.db.db.(sqlTx); ok {
417                         if scope.HasError() {
418                                 db.Rollback()
419                         } else {
420                                 scope.Err(db.Commit())
421                         }
422                         scope.db.db = scope.db.parent.db
423                 }
424         }
425         return scope
426 }
427
428 ////////////////////////////////////////////////////////////////////////////////
429 // Private Methods For *gorm.Scope
430 ////////////////////////////////////////////////////////////////////////////////
431
432 func (scope *Scope) callMethod(methodName string, reflectValue reflect.Value) {
433         // Only get address from non-pointer
434         if reflectValue.CanAddr() && reflectValue.Kind() != reflect.Ptr {
435                 reflectValue = reflectValue.Addr()
436         }
437
438         if methodValue := reflectValue.MethodByName(methodName); methodValue.IsValid() {
439                 switch method := methodValue.Interface().(type) {
440                 case func():
441                         method()
442                 case func(*Scope):
443                         method(scope)
444                 case func(*DB):
445                         newDB := scope.NewDB()
446                         method(newDB)
447                         scope.Err(newDB.Error)
448                 case func() error:
449                         scope.Err(method())
450                 case func(*Scope) error:
451                         scope.Err(method(scope))
452                 case func(*DB) error:
453                         newDB := scope.NewDB()
454                         scope.Err(method(newDB))
455                         scope.Err(newDB.Error)
456                 default:
457                         scope.Err(fmt.Errorf("unsupported function %v", methodName))
458                 }
459         }
460 }
461
462 var (
463         columnRegexp        = regexp.MustCompile("^[a-zA-Z\\d]+(\\.[a-zA-Z\\d]+)*$") // only match string like `name`, `users.name`
464         isNumberRegexp      = regexp.MustCompile("^\\s*\\d+\\s*$")                   // match if string is number
465         comparisonRegexp    = regexp.MustCompile("(?i) (=|<>|(>|<)(=?)|LIKE|IS|IN) ")
466         countingQueryRegexp = regexp.MustCompile("(?i)^count(.+)$")
467 )
468
469 func (scope *Scope) quoteIfPossible(str string) string {
470         if columnRegexp.MatchString(str) {
471                 return scope.Quote(str)
472         }
473         return str
474 }
475
476 func (scope *Scope) scan(rows *sql.Rows, columns []string, fields []*Field) {
477         var (
478                 ignored            interface{}
479                 values             = make([]interface{}, len(columns))
480                 selectFields       []*Field
481                 selectedColumnsMap = map[string]int{}
482                 resetFields        = map[int]*Field{}
483         )
484
485         for index, column := range columns {
486                 values[index] = &ignored
487
488                 selectFields = fields
489                 offset := 0
490                 if idx, ok := selectedColumnsMap[column]; ok {
491                         offset = idx + 1
492                         selectFields = selectFields[offset:]
493                 }
494
495                 for fieldIndex, field := range selectFields {
496                         if field.DBName == column {
497                                 if field.Field.Kind() == reflect.Ptr {
498                                         values[index] = field.Field.Addr().Interface()
499                                 } else {
500                                         reflectValue := reflect.New(reflect.PtrTo(field.Struct.Type))
501                                         reflectValue.Elem().Set(field.Field.Addr())
502                                         values[index] = reflectValue.Interface()
503                                         resetFields[index] = field
504                                 }
505
506                                 selectedColumnsMap[column] = offset + fieldIndex
507
508                                 if field.IsNormal {
509                                         break
510                                 }
511                         }
512                 }
513         }
514
515         scope.Err(rows.Scan(values...))
516
517         for index, field := range resetFields {
518                 if v := reflect.ValueOf(values[index]).Elem().Elem(); v.IsValid() {
519                         field.Field.Set(v)
520                 }
521         }
522 }
523
524 func (scope *Scope) primaryCondition(value interface{}) string {
525         return fmt.Sprintf("(%v.%v = %v)", scope.QuotedTableName(), scope.Quote(scope.PrimaryKey()), value)
526 }
527
528 func (scope *Scope) buildCondition(clause map[string]interface{}, include bool) (str string) {
529         var (
530                 quotedTableName  = scope.QuotedTableName()
531                 quotedPrimaryKey = scope.Quote(scope.PrimaryKey())
532                 equalSQL         = "="
533                 inSQL            = "IN"
534         )
535
536         // If building not conditions
537         if !include {
538                 equalSQL = "<>"
539                 inSQL = "NOT IN"
540         }
541
542         switch value := clause["query"].(type) {
543         case sql.NullInt64:
544                 return fmt.Sprintf("(%v.%v %s %v)", quotedTableName, quotedPrimaryKey, equalSQL, value.Int64)
545         case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
546                 return fmt.Sprintf("(%v.%v %s %v)", quotedTableName, quotedPrimaryKey, equalSQL, value)
547         case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64, []string, []interface{}:
548                 if !include && reflect.ValueOf(value).Len() == 0 {
549                         return
550                 }
551                 str = fmt.Sprintf("(%v.%v %s (?))", quotedTableName, quotedPrimaryKey, inSQL)
552                 clause["args"] = []interface{}{value}
553         case string:
554                 if isNumberRegexp.MatchString(value) {
555                         return fmt.Sprintf("(%v.%v %s %v)", quotedTableName, quotedPrimaryKey, equalSQL, scope.AddToVars(value))
556                 }
557
558                 if value != "" {
559                         if !include {
560                                 if comparisonRegexp.MatchString(value) {
561                                         str = fmt.Sprintf("NOT (%v)", value)
562                                 } else {
563                                         str = fmt.Sprintf("(%v.%v NOT IN (?))", quotedTableName, scope.Quote(value))
564                                 }
565                         } else {
566                                 str = fmt.Sprintf("(%v)", value)
567                         }
568                 }
569         case map[string]interface{}:
570                 var sqls []string
571                 for key, value := range value {
572                         if value != nil {
573                                 sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", quotedTableName, scope.Quote(key), equalSQL, scope.AddToVars(value)))
574                         } else {
575                                 if !include {
576                                         sqls = append(sqls, fmt.Sprintf("(%v.%v IS NOT NULL)", quotedTableName, scope.Quote(key)))
577                                 } else {
578                                         sqls = append(sqls, fmt.Sprintf("(%v.%v IS NULL)", quotedTableName, scope.Quote(key)))
579                                 }
580                         }
581                 }
582                 return strings.Join(sqls, " AND ")
583         case interface{}:
584                 var sqls []string
585                 newScope := scope.New(value)
586
587                 if len(newScope.Fields()) == 0 {
588                         scope.Err(fmt.Errorf("invalid query condition: %v", value))
589                         return
590                 }
591                 scopeQuotedTableName := newScope.QuotedTableName()
592                 for _, field := range newScope.Fields() {
593                         if !field.IsIgnored && !field.IsBlank {
594                                 sqls = append(sqls, fmt.Sprintf("(%v.%v %s %v)", scopeQuotedTableName, scope.Quote(field.DBName), equalSQL, scope.AddToVars(field.Field.Interface())))
595                         }
596                 }
597                 return strings.Join(sqls, " AND ")
598         default:
599                 scope.Err(fmt.Errorf("invalid query condition: %v", value))
600                 return
601         }
602
603         replacements := []string{}
604         args := clause["args"].([]interface{})
605         for _, arg := range args {
606                 var err error
607                 switch reflect.ValueOf(arg).Kind() {
608                 case reflect.Slice: // For where("id in (?)", []int64{1,2})
609                         if scanner, ok := interface{}(arg).(driver.Valuer); ok {
610                                 arg, err = scanner.Value()
611                                 replacements = append(replacements, scope.AddToVars(arg))
612                         } else if b, ok := arg.([]byte); ok {
613                                 replacements = append(replacements, scope.AddToVars(b))
614                         } else if as, ok := arg.([][]interface{}); ok {
615                                 var tempMarks []string
616                                 for _, a := range as {
617                                         var arrayMarks []string
618                                         for _, v := range a {
619                                                 arrayMarks = append(arrayMarks, scope.AddToVars(v))
620                                         }
621
622                                         if len(arrayMarks) > 0 {
623                                                 tempMarks = append(tempMarks, fmt.Sprintf("(%v)", strings.Join(arrayMarks, ",")))
624                                         }
625                                 }
626
627                                 if len(tempMarks) > 0 {
628                                         replacements = append(replacements, strings.Join(tempMarks, ","))
629                                 }
630                         } else if values := reflect.ValueOf(arg); values.Len() > 0 {
631                                 var tempMarks []string
632                                 for i := 0; i < values.Len(); i++ {
633                                         tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
634                                 }
635                                 replacements = append(replacements, strings.Join(tempMarks, ","))
636                         } else {
637                                 replacements = append(replacements, scope.AddToVars(Expr("NULL")))
638                         }
639                 default:
640                         if valuer, ok := interface{}(arg).(driver.Valuer); ok {
641                                 arg, err = valuer.Value()
642                         }
643
644                         replacements = append(replacements, scope.AddToVars(arg))
645                 }
646
647                 if err != nil {
648                         scope.Err(err)
649                 }
650         }
651
652         buff := bytes.NewBuffer([]byte{})
653         i := 0
654         for _, s := range str {
655                 if s == '?' && len(replacements) > i {
656                         buff.WriteString(replacements[i])
657                         i++
658                 } else {
659                         buff.WriteRune(s)
660                 }
661         }
662
663         str = buff.String()
664
665         return
666 }
667
668 func (scope *Scope) buildSelectQuery(clause map[string]interface{}) (str string) {
669         switch value := clause["query"].(type) {
670         case string:
671                 str = value
672         case []string:
673                 str = strings.Join(value, ", ")
674         }
675
676         args := clause["args"].([]interface{})
677         replacements := []string{}
678         for _, arg := range args {
679                 switch reflect.ValueOf(arg).Kind() {
680                 case reflect.Slice:
681                         values := reflect.ValueOf(arg)
682                         var tempMarks []string
683                         for i := 0; i < values.Len(); i++ {
684                                 tempMarks = append(tempMarks, scope.AddToVars(values.Index(i).Interface()))
685                         }
686                         replacements = append(replacements, strings.Join(tempMarks, ","))
687                 default:
688                         if valuer, ok := interface{}(arg).(driver.Valuer); ok {
689                                 arg, _ = valuer.Value()
690                         }
691                         replacements = append(replacements, scope.AddToVars(arg))
692                 }
693         }
694
695         buff := bytes.NewBuffer([]byte{})
696         i := 0
697         for pos, char := range str {
698                 if str[pos] == '?' {
699                         buff.WriteString(replacements[i])
700                         i++
701                 } else {
702                         buff.WriteRune(char)
703                 }
704         }
705
706         str = buff.String()
707
708         return
709 }
710
711 func (scope *Scope) whereSQL() (sql string) {
712         var (
713                 quotedTableName                                = scope.QuotedTableName()
714                 deletedAtField, hasDeletedAtField              = scope.FieldByName("DeletedAt")
715                 primaryConditions, andConditions, orConditions []string
716         )
717
718         if !scope.Search.Unscoped && hasDeletedAtField {
719                 sql := fmt.Sprintf("%v.%v IS NULL", quotedTableName, scope.Quote(deletedAtField.DBName))
720                 primaryConditions = append(primaryConditions, sql)
721         }
722
723         if !scope.PrimaryKeyZero() {
724                 for _, field := range scope.PrimaryFields() {
725                         sql := fmt.Sprintf("%v.%v = %v", quotedTableName, scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))
726                         primaryConditions = append(primaryConditions, sql)
727                 }
728         }
729
730         for _, clause := range scope.Search.whereConditions {
731                 if sql := scope.buildCondition(clause, true); sql != "" {
732                         andConditions = append(andConditions, sql)
733                 }
734         }
735
736         for _, clause := range scope.Search.orConditions {
737                 if sql := scope.buildCondition(clause, true); sql != "" {
738                         orConditions = append(orConditions, sql)
739                 }
740         }
741
742         for _, clause := range scope.Search.notConditions {
743                 if sql := scope.buildCondition(clause, false); sql != "" {
744                         andConditions = append(andConditions, sql)
745                 }
746         }
747
748         orSQL := strings.Join(orConditions, " OR ")
749         combinedSQL := strings.Join(andConditions, " AND ")
750         if len(combinedSQL) > 0 {
751                 if len(orSQL) > 0 {
752                         combinedSQL = combinedSQL + " OR " + orSQL
753                 }
754         } else {
755                 combinedSQL = orSQL
756         }
757
758         if len(primaryConditions) > 0 {
759                 sql = "WHERE " + strings.Join(primaryConditions, " AND ")
760                 if len(combinedSQL) > 0 {
761                         sql = sql + " AND (" + combinedSQL + ")"
762                 }
763         } else if len(combinedSQL) > 0 {
764                 sql = "WHERE " + combinedSQL
765         }
766         return
767 }
768
769 func (scope *Scope) selectSQL() string {
770         if len(scope.Search.selects) == 0 {
771                 if len(scope.Search.joinConditions) > 0 {
772                         return fmt.Sprintf("%v.*", scope.QuotedTableName())
773                 }
774                 return "*"
775         }
776         return scope.buildSelectQuery(scope.Search.selects)
777 }
778
779 func (scope *Scope) orderSQL() string {
780         if len(scope.Search.orders) == 0 || scope.Search.ignoreOrderQuery {
781                 return ""
782         }
783
784         var orders []string
785         for _, order := range scope.Search.orders {
786                 if str, ok := order.(string); ok {
787                         orders = append(orders, scope.quoteIfPossible(str))
788                 } else if expr, ok := order.(*expr); ok {
789                         exp := expr.expr
790                         for _, arg := range expr.args {
791                                 exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
792                         }
793                         orders = append(orders, exp)
794                 }
795         }
796         return " ORDER BY " + strings.Join(orders, ",")
797 }
798
799 func (scope *Scope) limitAndOffsetSQL() string {
800         return scope.Dialect().LimitAndOffsetSQL(scope.Search.limit, scope.Search.offset)
801 }
802
803 func (scope *Scope) groupSQL() string {
804         if len(scope.Search.group) == 0 {
805                 return ""
806         }
807         return " GROUP BY " + scope.Search.group
808 }
809
810 func (scope *Scope) havingSQL() string {
811         if len(scope.Search.havingConditions) == 0 {
812                 return ""
813         }
814
815         var andConditions []string
816         for _, clause := range scope.Search.havingConditions {
817                 if sql := scope.buildCondition(clause, true); sql != "" {
818                         andConditions = append(andConditions, sql)
819                 }
820         }
821
822         combinedSQL := strings.Join(andConditions, " AND ")
823         if len(combinedSQL) == 0 {
824                 return ""
825         }
826
827         return " HAVING " + combinedSQL
828 }
829
830 func (scope *Scope) joinsSQL() string {
831         var joinConditions []string
832         for _, clause := range scope.Search.joinConditions {
833                 if sql := scope.buildCondition(clause, true); sql != "" {
834                         joinConditions = append(joinConditions, strings.TrimSuffix(strings.TrimPrefix(sql, "("), ")"))
835                 }
836         }
837
838         return strings.Join(joinConditions, " ") + " "
839 }
840
841 func (scope *Scope) prepareQuerySQL() {
842         if scope.Search.raw {
843                 scope.Raw(scope.CombinedConditionSql())
844         } else {
845                 scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql()))
846         }
847         return
848 }
849
850 func (scope *Scope) inlineCondition(values ...interface{}) *Scope {
851         if len(values) > 0 {
852                 scope.Search.Where(values[0], values[1:]...)
853         }
854         return scope
855 }
856
857 func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
858         defer func() {
859                 if err := recover(); err != nil {
860                         if db, ok := scope.db.db.(sqlTx); ok {
861                                 db.Rollback()
862                         }
863                         panic(err)
864                 }
865         }()
866         for _, f := range funcs {
867                 (*f)(scope)
868                 if scope.skipLeft {
869                         break
870                 }
871         }
872         return scope
873 }
874
875 func convertInterfaceToMap(values interface{}, withIgnoredField bool) map[string]interface{} {
876         var attrs = map[string]interface{}{}
877
878         switch value := values.(type) {
879         case map[string]interface{}:
880                 return value
881         case []interface{}:
882                 for _, v := range value {
883                         for key, value := range convertInterfaceToMap(v, withIgnoredField) {
884                                 attrs[key] = value
885                         }
886                 }
887         case interface{}:
888                 reflectValue := reflect.ValueOf(values)
889
890                 switch reflectValue.Kind() {
891                 case reflect.Map:
892                         for _, key := range reflectValue.MapKeys() {
893                                 attrs[ToColumnName(key.Interface().(string))] = reflectValue.MapIndex(key).Interface()
894                         }
895                 default:
896                         for _, field := range (&Scope{Value: values}).Fields() {
897                                 if !field.IsBlank && (withIgnoredField || !field.IsIgnored) {
898                                         attrs[field.DBName] = field.Field.Interface()
899                                 }
900                         }
901                 }
902         }
903         return attrs
904 }
905
906 func (scope *Scope) updatedAttrsWithValues(value interface{}) (results map[string]interface{}, hasUpdate bool) {
907         if scope.IndirectValue().Kind() != reflect.Struct {
908                 return convertInterfaceToMap(value, false), true
909         }
910
911         results = map[string]interface{}{}
912
913         for key, value := range convertInterfaceToMap(value, true) {
914                 if field, ok := scope.FieldByName(key); ok && scope.changeableField(field) {
915                         if _, ok := value.(*expr); ok {
916                                 hasUpdate = true
917                                 results[field.DBName] = value
918                         } else {
919                                 err := field.Set(value)
920                                 if field.IsNormal && !field.IsIgnored {
921                                         hasUpdate = true
922                                         if err == ErrUnaddressable {
923                                                 results[field.DBName] = value
924                                         } else {
925                                                 results[field.DBName] = field.Field.Interface()
926                                         }
927                                 }
928                         }
929                 }
930         }
931         return
932 }
933
934 func (scope *Scope) row() *sql.Row {
935         defer scope.trace(NowFunc())
936
937         result := &RowQueryResult{}
938         scope.InstanceSet("row_query_result", result)
939         scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
940
941         return result.Row
942 }
943
944 func (scope *Scope) rows() (*sql.Rows, error) {
945         defer scope.trace(NowFunc())
946
947         result := &RowsQueryResult{}
948         scope.InstanceSet("row_query_result", result)
949         scope.callCallbacks(scope.db.parent.callbacks.rowQueries)
950
951         return result.Rows, result.Error
952 }
953
954 func (scope *Scope) initialize() *Scope {
955         for _, clause := range scope.Search.whereConditions {
956                 scope.updatedAttrsWithValues(clause["query"])
957         }
958         scope.updatedAttrsWithValues(scope.Search.initAttrs)
959         scope.updatedAttrsWithValues(scope.Search.assignAttrs)
960         return scope
961 }
962
963 func (scope *Scope) isQueryForColumn(query interface{}, column string) bool {
964         queryStr := strings.ToLower(fmt.Sprint(query))
965         if queryStr == column {
966                 return true
967         }
968
969         if strings.HasSuffix(queryStr, "as "+column) {
970                 return true
971         }
972
973         if strings.HasSuffix(queryStr, "as "+scope.Quote(column)) {
974                 return true
975         }
976
977         return false
978 }
979
980 func (scope *Scope) pluck(column string, value interface{}) *Scope {
981         dest := reflect.Indirect(reflect.ValueOf(value))
982         if dest.Kind() != reflect.Slice {
983                 scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind()))
984                 return scope
985         }
986
987         if query, ok := scope.Search.selects["query"]; !ok || !scope.isQueryForColumn(query, column) {
988                 scope.Search.Select(column)
989         }
990
991         rows, err := scope.rows()
992         if scope.Err(err) == nil {
993                 defer rows.Close()
994                 for rows.Next() {
995                         elem := reflect.New(dest.Type().Elem()).Interface()
996                         scope.Err(rows.Scan(elem))
997                         dest.Set(reflect.Append(dest, reflect.ValueOf(elem).Elem()))
998                 }
999
1000                 if err := rows.Err(); err != nil {
1001                         scope.Err(err)
1002                 }
1003         }
1004         return scope
1005 }
1006
1007 func (scope *Scope) count(value interface{}) *Scope {
1008         if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) {
1009                 if len(scope.Search.group) != 0 {
1010                         scope.Search.Select("count(*) FROM ( SELECT count(*) as name ")
1011                         scope.Search.group += " ) AS count_table"
1012                 } else {
1013                         scope.Search.Select("count(*)")
1014                 }
1015         }
1016         scope.Search.ignoreOrderQuery = true
1017         scope.Err(scope.row().Scan(value))
1018         return scope
1019 }
1020
1021 func (scope *Scope) typeName() string {
1022         typ := scope.IndirectValue().Type()
1023
1024         for typ.Kind() == reflect.Slice || typ.Kind() == reflect.Ptr {
1025                 typ = typ.Elem()
1026         }
1027
1028         return typ.Name()
1029 }
1030
1031 // trace print sql log
1032 func (scope *Scope) trace(t time.Time) {
1033         if len(scope.SQL) > 0 {
1034                 scope.db.slog(scope.SQL, t, scope.SQLVars...)
1035         }
1036 }
1037
1038 func (scope *Scope) changeableField(field *Field) bool {
1039         if selectAttrs := scope.SelectAttrs(); len(selectAttrs) > 0 {
1040                 for _, attr := range selectAttrs {
1041                         if field.Name == attr || field.DBName == attr {
1042                                 return true
1043                         }
1044                 }
1045                 return false
1046         }
1047
1048         for _, attr := range scope.OmitAttrs() {
1049                 if field.Name == attr || field.DBName == attr {
1050                         return false
1051                 }
1052         }
1053
1054         return true
1055 }
1056
1057 func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
1058         toScope := scope.db.NewScope(value)
1059         tx := scope.db.Set("gorm:association:source", scope.Value)
1060
1061         for _, foreignKey := range append(foreignKeys, toScope.typeName()+"Id", scope.typeName()+"Id") {
1062                 fromField, _ := scope.FieldByName(foreignKey)
1063                 toField, _ := toScope.FieldByName(foreignKey)
1064
1065                 if fromField != nil {
1066                         if relationship := fromField.Relationship; relationship != nil {
1067                                 if relationship.Kind == "many_to_many" {
1068                                         joinTableHandler := relationship.JoinTableHandler
1069                                         scope.Err(joinTableHandler.JoinWith(joinTableHandler, tx, scope.Value).Find(value).Error)
1070                                 } else if relationship.Kind == "belongs_to" {
1071                                         for idx, foreignKey := range relationship.ForeignDBNames {
1072                                                 if field, ok := scope.FieldByName(foreignKey); ok {
1073                                                         tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.AssociationForeignDBNames[idx])), field.Field.Interface())
1074                                                 }
1075                                         }
1076                                         scope.Err(tx.Find(value).Error)
1077                                 } else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
1078                                         for idx, foreignKey := range relationship.ForeignDBNames {
1079                                                 if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
1080                                                         tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
1081                                                 }
1082                                         }
1083
1084                                         if relationship.PolymorphicType != "" {
1085                                                 tx = tx.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), relationship.PolymorphicValue)
1086                                         }
1087                                         scope.Err(tx.Find(value).Error)
1088                                 }
1089                         } else {
1090                                 sql := fmt.Sprintf("%v = ?", scope.Quote(toScope.PrimaryKey()))
1091                                 scope.Err(tx.Where(sql, fromField.Field.Interface()).Find(value).Error)
1092                         }
1093                         return scope
1094                 } else if toField != nil {
1095                         sql := fmt.Sprintf("%v = ?", scope.Quote(toField.DBName))
1096                         scope.Err(tx.Where(sql, scope.PrimaryKeyValue()).Find(value).Error)
1097                         return scope
1098                 }
1099         }
1100
1101         scope.Err(fmt.Errorf("invalid association %v", foreignKeys))
1102         return scope
1103 }
1104
1105 // getTableOptions return the table options string or an empty string if the table options does not exist
1106 func (scope *Scope) getTableOptions() string {
1107         tableOptions, ok := scope.Get("gorm:table_options")
1108         if !ok {
1109                 return ""
1110         }
1111         return " " + tableOptions.(string)
1112 }
1113
1114 func (scope *Scope) createJoinTable(field *StructField) {
1115         if relationship := field.Relationship; relationship != nil && relationship.JoinTableHandler != nil {
1116                 joinTableHandler := relationship.JoinTableHandler
1117                 joinTable := joinTableHandler.Table(scope.db)
1118                 if !scope.Dialect().HasTable(joinTable) {
1119                         toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}
1120
1121                         var sqlTypes, primaryKeys []string
1122                         for idx, fieldName := range relationship.ForeignFieldNames {
1123                                 if field, ok := scope.FieldByName(fieldName); ok {
1124                                         foreignKeyStruct := field.clone()
1125                                         foreignKeyStruct.IsPrimaryKey = false
1126                                         foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true")
1127                                         foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT")
1128                                         sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
1129                                         primaryKeys = append(primaryKeys, scope.Quote(relationship.ForeignDBNames[idx]))
1130                                 }
1131                         }
1132
1133                         for idx, fieldName := range relationship.AssociationForeignFieldNames {
1134                                 if field, ok := toScope.FieldByName(fieldName); ok {
1135                                         foreignKeyStruct := field.clone()
1136                                         foreignKeyStruct.IsPrimaryKey = false
1137                                         foreignKeyStruct.TagSettingsSet("IS_JOINTABLE_FOREIGNKEY", "true")
1138                                         foreignKeyStruct.TagSettingsDelete("AUTO_INCREMENT")
1139                                         sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+scope.Dialect().DataTypeOf(foreignKeyStruct))
1140                                         primaryKeys = append(primaryKeys, scope.Quote(relationship.AssociationForeignDBNames[idx]))
1141                                 }
1142                         }
1143
1144                         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)
1145                 }
1146                 scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler)
1147         }
1148 }
1149
1150 func (scope *Scope) createTable() *Scope {
1151         var tags []string
1152         var primaryKeys []string
1153         var primaryKeyInColumnType = false
1154         for _, field := range scope.GetModelStruct().StructFields {
1155                 if field.IsNormal {
1156                         sqlTag := scope.Dialect().DataTypeOf(field)
1157
1158                         // Check if the primary key constraint was specified as
1159                         // part of the column type. If so, we can only support
1160                         // one column as the primary key.
1161                         if strings.Contains(strings.ToLower(sqlTag), "primary key") {
1162                                 primaryKeyInColumnType = true
1163                         }
1164
1165                         tags = append(tags, scope.Quote(field.DBName)+" "+sqlTag)
1166                 }
1167
1168                 if field.IsPrimaryKey {
1169                         primaryKeys = append(primaryKeys, scope.Quote(field.DBName))
1170                 }
1171                 scope.createJoinTable(field)
1172         }
1173
1174         var primaryKeyStr string
1175         if len(primaryKeys) > 0 && !primaryKeyInColumnType {
1176                 primaryKeyStr = fmt.Sprintf(", PRIMARY KEY (%v)", strings.Join(primaryKeys, ","))
1177         }
1178
1179         scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v %v)%s", scope.QuotedTableName(), strings.Join(tags, ","), primaryKeyStr, scope.getTableOptions())).Exec()
1180
1181         scope.autoIndex()
1182         return scope
1183 }
1184
1185 func (scope *Scope) dropTable() *Scope {
1186         scope.Raw(fmt.Sprintf("DROP TABLE %v%s", scope.QuotedTableName(), scope.getTableOptions())).Exec()
1187         return scope
1188 }
1189
1190 func (scope *Scope) modifyColumn(column string, typ string) {
1191         scope.db.AddError(scope.Dialect().ModifyColumn(scope.QuotedTableName(), scope.Quote(column), typ))
1192 }
1193
1194 func (scope *Scope) dropColumn(column string) {
1195         scope.Raw(fmt.Sprintf("ALTER TABLE %v DROP COLUMN %v", scope.QuotedTableName(), scope.Quote(column))).Exec()
1196 }
1197
1198 func (scope *Scope) addIndex(unique bool, indexName string, column ...string) {
1199         if scope.Dialect().HasIndex(scope.TableName(), indexName) {
1200                 return
1201         }
1202
1203         var columns []string
1204         for _, name := range column {
1205                 columns = append(columns, scope.quoteIfPossible(name))
1206         }
1207
1208         sqlCreate := "CREATE INDEX"
1209         if unique {
1210                 sqlCreate = "CREATE UNIQUE INDEX"
1211         }
1212
1213         scope.Raw(fmt.Sprintf("%s %v ON %v(%v) %v", sqlCreate, indexName, scope.QuotedTableName(), strings.Join(columns, ", "), scope.whereSQL())).Exec()
1214 }
1215
1216 func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) {
1217         // Compatible with old generated key
1218         keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest, "foreign")
1219
1220         if scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
1221                 return
1222         }
1223         var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;`
1224         scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
1225 }
1226
1227 func (scope *Scope) removeForeignKey(field string, dest string) {
1228         keyName := scope.Dialect().BuildKeyName(scope.TableName(), field, dest, "foreign")
1229         if !scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
1230                 return
1231         }
1232         var mysql mysql
1233         var query string
1234         if scope.Dialect().GetName() == mysql.GetName() {
1235                 query = `ALTER TABLE %s DROP FOREIGN KEY %s;`
1236         } else {
1237                 query = `ALTER TABLE %s DROP CONSTRAINT %s;`
1238         }
1239
1240         scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName))).Exec()
1241 }
1242
1243 func (scope *Scope) removeIndex(indexName string) {
1244         scope.Dialect().RemoveIndex(scope.TableName(), indexName)
1245 }
1246
1247 func (scope *Scope) autoMigrate() *Scope {
1248         tableName := scope.TableName()
1249         quotedTableName := scope.QuotedTableName()
1250
1251         if !scope.Dialect().HasTable(tableName) {
1252                 scope.createTable()
1253         } else {
1254                 for _, field := range scope.GetModelStruct().StructFields {
1255                         if !scope.Dialect().HasColumn(tableName, field.DBName) {
1256                                 if field.IsNormal {
1257                                         sqlTag := scope.Dialect().DataTypeOf(field)
1258                                         scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, scope.Quote(field.DBName), sqlTag)).Exec()
1259                                 }
1260                         }
1261                         scope.createJoinTable(field)
1262                 }
1263                 scope.autoIndex()
1264         }
1265         return scope
1266 }
1267
1268 func (scope *Scope) autoIndex() *Scope {
1269         var indexes = map[string][]string{}
1270         var uniqueIndexes = map[string][]string{}
1271
1272         for _, field := range scope.GetStructFields() {
1273                 if name, ok := field.TagSettingsGet("INDEX"); ok {
1274                         names := strings.Split(name, ",")
1275
1276                         for _, name := range names {
1277                                 if name == "INDEX" || name == "" {
1278                                         name = scope.Dialect().BuildKeyName("idx", scope.TableName(), field.DBName)
1279                                 }
1280                                 indexes[name] = append(indexes[name], field.DBName)
1281                         }
1282                 }
1283
1284                 if name, ok := field.TagSettingsGet("UNIQUE_INDEX"); ok {
1285                         names := strings.Split(name, ",")
1286
1287                         for _, name := range names {
1288                                 if name == "UNIQUE_INDEX" || name == "" {
1289                                         name = scope.Dialect().BuildKeyName("uix", scope.TableName(), field.DBName)
1290                                 }
1291                                 uniqueIndexes[name] = append(uniqueIndexes[name], field.DBName)
1292                         }
1293                 }
1294         }
1295
1296         for name, columns := range indexes {
1297                 if db := scope.NewDB().Table(scope.TableName()).Model(scope.Value).AddIndex(name, columns...); db.Error != nil {
1298                         scope.db.AddError(db.Error)
1299                 }
1300         }
1301
1302         for name, columns := range uniqueIndexes {
1303                 if db := scope.NewDB().Table(scope.TableName()).Model(scope.Value).AddUniqueIndex(name, columns...); db.Error != nil {
1304                         scope.db.AddError(db.Error)
1305                 }
1306         }
1307
1308         return scope
1309 }
1310
1311 func (scope *Scope) getColumnAsArray(columns []string, values ...interface{}) (results [][]interface{}) {
1312         for _, value := range values {
1313                 indirectValue := indirect(reflect.ValueOf(value))
1314
1315                 switch indirectValue.Kind() {
1316                 case reflect.Slice:
1317                         for i := 0; i < indirectValue.Len(); i++ {
1318                                 var result []interface{}
1319                                 var object = indirect(indirectValue.Index(i))
1320                                 var hasValue = false
1321                                 for _, column := range columns {
1322                                         field := object.FieldByName(column)
1323                                         if hasValue || !isBlank(field) {
1324                                                 hasValue = true
1325                                         }
1326                                         result = append(result, field.Interface())
1327                                 }
1328
1329                                 if hasValue {
1330                                         results = append(results, result)
1331                                 }
1332                         }
1333                 case reflect.Struct:
1334                         var result []interface{}
1335                         var hasValue = false
1336                         for _, column := range columns {
1337                                 field := indirectValue.FieldByName(column)
1338                                 if hasValue || !isBlank(field) {
1339                                         hasValue = true
1340                                 }
1341                                 result = append(result, field.Interface())
1342                         }
1343
1344                         if hasValue {
1345                                 results = append(results, result)
1346                         }
1347                 }
1348         }
1349
1350         return
1351 }
1352
1353 func (scope *Scope) getColumnAsScope(column string) *Scope {
1354         indirectScopeValue := scope.IndirectValue()
1355
1356         switch indirectScopeValue.Kind() {
1357         case reflect.Slice:
1358                 if fieldStruct, ok := scope.GetModelStruct().ModelType.FieldByName(column); ok {
1359                         fieldType := fieldStruct.Type
1360                         if fieldType.Kind() == reflect.Slice || fieldType.Kind() == reflect.Ptr {
1361                                 fieldType = fieldType.Elem()
1362                         }
1363
1364                         resultsMap := map[interface{}]bool{}
1365                         results := reflect.New(reflect.SliceOf(reflect.PtrTo(fieldType))).Elem()
1366
1367                         for i := 0; i < indirectScopeValue.Len(); i++ {
1368                                 result := indirect(indirect(indirectScopeValue.Index(i)).FieldByName(column))
1369
1370                                 if result.Kind() == reflect.Slice {
1371                                         for j := 0; j < result.Len(); j++ {
1372                                                 if elem := result.Index(j); elem.CanAddr() && resultsMap[elem.Addr()] != true {
1373                                                         resultsMap[elem.Addr()] = true
1374                                                         results = reflect.Append(results, elem.Addr())
1375                                                 }
1376                                         }
1377                                 } else if result.CanAddr() && resultsMap[result.Addr()] != true {
1378                                         resultsMap[result.Addr()] = true
1379                                         results = reflect.Append(results, result.Addr())
1380                                 }
1381                         }
1382                         return scope.New(results.Interface())
1383                 }
1384         case reflect.Struct:
1385                 if field := indirectScopeValue.FieldByName(column); field.CanAddr() {
1386                         return scope.New(field.Addr().Interface())
1387                 }
1388         }
1389         return nil
1390 }
1391
1392 func (scope *Scope) hasConditions() bool {
1393         return !scope.PrimaryKeyZero() ||
1394                 len(scope.Search.whereConditions) > 0 ||
1395                 len(scope.Search.orConditions) > 0 ||
1396                 len(scope.Search.notConditions) > 0
1397 }