Skip to content

Commit

Permalink
Merge pull request #2 from Emptyless/feature/fix-nil-pointer
Browse files Browse the repository at this point in the history
fix nil pointer on unknown field
  • Loading branch information
survivorbat authored Jan 13, 2024
2 parents 0aad6a2 + 577bedb commit 7e2f9c9
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
12 changes: 10 additions & 2 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ func (d *gormLike) queryCallback(db *gorm.DB) {
}

// Get the `gormlike` value
tagValue := db.Statement.Schema.FieldsByDBName[columnName].Tag.Get(tagName)
var tagValue string
dbField, ok := db.Statement.Schema.FieldsByDBName[columnName]
if ok {
tagValue = dbField.Tag.Get(tagName)
}

// If the user has explicitly set this to false, ignore this field
if tagValue == "false" {
Expand Down Expand Up @@ -74,7 +78,11 @@ func (d *gormLike) queryCallback(db *gorm.DB) {
}

// Get the `gormlike` value
tagValue := db.Statement.Schema.FieldsByDBName[columnName].Tag.Get(tagName)
var tagValue string
dbField, ok := db.Statement.Schema.FieldsByDBName[columnName]
if ok {
tagValue = dbField.Tag.Get(tagName)
}

// If the user has explicitly set this to false, ignore this field
if tagValue == "false" {
Expand Down
57 changes: 57 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -510,3 +510,60 @@ func TestGormLike_Initialize_TriggersLikingCorrectlyWithSetting(t *testing.T) {
})
}
}

func TestGormLike_Initialize_ProcessUnknownFields(t *testing.T) {
t.Parallel()

type ObjectB struct {
Name string
Other string
}

tests := map[string]struct {
filter map[string]any
query func(*gorm.DB) *gorm.DB
existing []ObjectB
expected []ObjectB
}{
"like with unknown field": {
filter: map[string]any{
"name": "jes%",
"unknown_field": false,
},
query: func(db *gorm.DB) *gorm.DB {
return db.Set(tagName, true)
},
existing: []ObjectB{{Name: "jessica", Other: "abc"}},
expected: []ObjectB{},
},
}

for name, testData := range tests {
testData := testData
t.Run(name, func(t *testing.T) {
t.Parallel()
// Arrange
db := gormtestutil.NewMemoryDatabase(t, gormtestutil.WithName(t.Name()))
_ = db.AutoMigrate(&ObjectB{})
plugin := New(SettingOnly())

if err := db.CreateInBatches(testData.existing, 10).Error; err != nil {
t.Error(err)
t.FailNow()
}

db = testData.query(db)

// Act
err := db.Use(plugin)

// Assert
assert.NoError(t, err)

var actual []ObjectB
err = db.Where(testData.filter).Find(&actual).Error
assert.Equal(t, "no such column: unknown_field", err.Error())
assert.Nil(t, actual)
})
}
}

0 comments on commit 7e2f9c9

Please sign in to comment.