From ba590650241bbab942745cd97269fa30e1a965f8 Mon Sep 17 00:00:00 2001 From: rorschach Date: Tue, 26 Jan 2021 20:08:41 +0800 Subject: [PATCH] retrieving gorm object support pointer --- callbacks.go | 5 +++++ scan.go | 2 +- tests/scan_test.go | 6 ++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/callbacks.go b/callbacks.go index e21e0718..cb14aff1 100644 --- a/callbacks.go +++ b/callbacks.go @@ -94,6 +94,11 @@ func (p *processor) Execute(db *DB) { if stmt.Dest != nil { stmt.ReflectValue = reflect.ValueOf(stmt.Dest) for stmt.ReflectValue.Kind() == reflect.Ptr { + if stmt.ReflectValue.IsNil() { + stmt.ReflectValue.Set(reflect.New(stmt.ReflectValue.Type().Elem())) + break + } + stmt.ReflectValue = stmt.ReflectValue.Elem() } if !stmt.ReflectValue.IsValid() { diff --git a/scan.go b/scan.go index 0416489d..acd637a4 100644 --- a/scan.go +++ b/scan.go @@ -191,7 +191,7 @@ func Scan(rows *sql.Rows, db *DB, initialized bool) { db.Statement.ReflectValue.Set(reflect.Append(db.Statement.ReflectValue, elem.Elem())) } } - case reflect.Struct: + case reflect.Struct, reflect.Ptr: if db.Statement.ReflectValue.Type() != Schema.ModelType { Schema, _ = schema.Parse(db.Statement.Dest, db.cacheStore, db.NamingStrategy) } diff --git a/tests/scan_test.go b/tests/scan_test.go index 785bb97e..86cb0399 100644 --- a/tests/scan_test.go +++ b/tests/scan_test.go @@ -28,6 +28,12 @@ func TestScan(t *testing.T) { t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user3) } + var resPointer *result + DB.Table("users").Select("id, name, age").Where("id = ?", user3.ID).Scan(&resPointer) + if res.ID != user3.ID || res.Name != user3.Name || res.Age != int(user3.Age) { + t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user3) + } + DB.Table("users").Select("id, name, age").Where("id = ?", user2.ID).Scan(&res) if res.ID != user2.ID || res.Name != user2.Name || res.Age != int(user2.Age) { t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user2)