From 9f7f4b430ea438e4427bb0c20f036d06aeabea08 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 4 Mar 2020 22:16:39 +0800 Subject: [PATCH] Refactor find slice --- callbacks/scan.go | 12 ++++++++---- logger/logger.go | 2 +- tests/docker-compose.yml | 2 +- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/callbacks/scan.go b/callbacks/scan.go index c9f948b1..f8f1ef54 100644 --- a/callbacks/scan.go +++ b/callbacks/scan.go @@ -5,6 +5,7 @@ import ( "reflect" "github.com/jinzhu/gorm" + "github.com/jinzhu/gorm/schema" ) func Scan(rows *sql.Rows, db *gorm.DB) { @@ -52,14 +53,17 @@ func Scan(rows *sql.Rows, db *gorm.DB) { case reflect.Slice, reflect.Array: isPtr := db.Statement.ReflectValue.Type().Elem().Kind() == reflect.Ptr db.Statement.ReflectValue.Set(reflect.MakeSlice(db.Statement.ReflectValue.Type(), 0, 0)) + fields := make([]*schema.Field, len(columns)) + + for idx, column := range columns { + fields[idx] = db.Statement.Schema.LookUpField(column) + } for rows.Next() { elem := reflect.New(db.Statement.Schema.ModelType).Elem() - for idx, column := range columns { - if field := db.Statement.Schema.LookUpField(column); field != nil { + for idx, field := range fields { + if field != nil { values[idx] = field.ReflectValueOf(elem).Addr().Interface() - } else if db.RowsAffected == 0 { - values[idx] = sql.RawBytes{} } } diff --git a/logger/logger.go b/logger/logger.go index d3b97b9d..2a765628 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -121,7 +121,7 @@ func (l logger) Error(msg string, data ...interface{}) { // Trace print sql message func (l logger) Trace(begin time.Time, fc func() (string, int64), err error) { - if elapsed := time.Now().Sub(begin); err != nil || elapsed > l.SlowThreshold { + if elapsed := time.Now().Sub(begin); err != nil || (elapsed > l.SlowThreshold && l.SlowThreshold != 0) { sql, rows := fc() fileline := utils.FileWithLineNum() if err != nil { diff --git a/tests/docker-compose.yml b/tests/docker-compose.yml index 79bf5fc3..6bf3fadf 100644 --- a/tests/docker-compose.yml +++ b/tests/docker-compose.yml @@ -15,8 +15,8 @@ services: ports: - 9920:5432 environment: - - POSTGRES_USER=gorm - POSTGRES_DB=gorm + - POSTGRES_USER=gorm - POSTGRES_PASSWORD=gorm mssql: image: 'mcmoe/mssqldocker:latest'