From 878ac51e983858bce556877fa72227cb76643155 Mon Sep 17 00:00:00 2001 From: Cr <631807682@qq.com> Date: Wed, 8 Feb 2023 13:40:41 +0800 Subject: [PATCH] fix:throw model value required error (#6031) * fix:throw model value required error * chore:ingore typecheck * chore:ingore errcheck * refactor: use other error * chore: gofumpt style --- callbacks/row.go | 2 +- errors.go | 2 ++ statement.go | 2 ++ tests/query_test.go | 14 ++++++++++++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/callbacks/row.go b/callbacks/row.go index 56be742e..beaa189e 100644 --- a/callbacks/row.go +++ b/callbacks/row.go @@ -7,7 +7,7 @@ import ( func RowQuery(db *gorm.DB) { if db.Error == nil { BuildQuerySQL(db) - if db.DryRun { + if db.DryRun || db.Error != nil { return } diff --git a/errors.go b/errors.go index 49cbfe64..0f486c5e 100644 --- a/errors.go +++ b/errors.go @@ -21,6 +21,8 @@ var ( ErrPrimaryKeyRequired = errors.New("primary key required") // ErrModelValueRequired model value required ErrModelValueRequired = errors.New("model value required") + // ErrModelAccessibleFieldsRequired model accessible fields required + ErrModelAccessibleFieldsRequired = errors.New("model accessible fields required") // ErrInvalidData unsupported data ErrInvalidData = errors.New("unsupported data") // ErrUnsupportedDriver unsupported driver diff --git a/statement.go b/statement.go index 08165293..bc959f0b 100644 --- a/statement.go +++ b/statement.go @@ -120,6 +120,8 @@ func (stmt *Statement) QuoteTo(writer clause.Writer, field interface{}) { write(v.Raw, stmt.Schema.PrioritizedPrimaryField.DBName) } else if len(stmt.Schema.DBNames) > 0 { write(v.Raw, stmt.Schema.DBNames[0]) + } else { + stmt.DB.AddError(ErrModelAccessibleFieldsRequired) //nolint:typecheck,errcheck } } else { write(v.Raw, v.Name) diff --git a/tests/query_test.go b/tests/query_test.go index fa8f09e8..88e93c77 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -1366,3 +1366,17 @@ func TestQueryResetNullValue(t *testing.T) { AssertEqual(t, q1, qs[0]) AssertEqual(t, q2, qs[1]) } + +func TestQueryError(t *testing.T) { + type P struct{} + var p1 P + err := DB.Take(&p1, 1).Error + AssertEqual(t, err, gorm.ErrModelAccessibleFieldsRequired) + + var p2 interface{} + + err = DB.Table("ps").Clauses(clause.Eq{Column: clause.Column{ + Table: clause.CurrentTable, Name: clause.PrimaryKey, + }, Value: 1}).Scan(&p2).Error + AssertEqual(t, err, gorm.ErrModelValueRequired) +}