File tree Expand file tree Collapse file tree 2 files changed +67
-2
lines changed Expand file tree Collapse file tree 2 files changed +67
-2
lines changed Original file line number Diff line number Diff line change @@ -38,7 +38,11 @@ func (d *gormLike) queryCallback(db *gorm.DB) {
38
38
}
39
39
40
40
// Get the `gormlike` value
41
- tagValue := db .Statement .Schema .FieldsByDBName [columnName ].Tag .Get (tagName )
41
+ var tagValue string
42
+ dbField , ok := db .Statement .Schema .FieldsByDBName [columnName ]
43
+ if ok {
44
+ tagValue = dbField .Tag .Get (tagName )
45
+ }
42
46
43
47
// If the user has explicitly set this to false, ignore this field
44
48
if tagValue == "false" {
@@ -74,7 +78,11 @@ func (d *gormLike) queryCallback(db *gorm.DB) {
74
78
}
75
79
76
80
// Get the `gormlike` value
77
- tagValue := db .Statement .Schema .FieldsByDBName [columnName ].Tag .Get (tagName )
81
+ var tagValue string
82
+ dbField , ok := db .Statement .Schema .FieldsByDBName [columnName ]
83
+ if ok {
84
+ tagValue = dbField .Tag .Get (tagName )
85
+ }
78
86
79
87
// If the user has explicitly set this to false, ignore this field
80
88
if tagValue == "false" {
Original file line number Diff line number Diff line change @@ -510,3 +510,60 @@ func TestGormLike_Initialize_TriggersLikingCorrectlyWithSetting(t *testing.T) {
510
510
})
511
511
}
512
512
}
513
+
514
+ func TestGormLike_Initialize_ProcessUnknownFields (t * testing.T ) {
515
+ t .Parallel ()
516
+
517
+ type ObjectB struct {
518
+ Name string
519
+ Other string
520
+ }
521
+
522
+ tests := map [string ]struct {
523
+ filter map [string ]any
524
+ query func (* gorm.DB ) * gorm.DB
525
+ existing []ObjectB
526
+ expected []ObjectB
527
+ }{
528
+ "like with unknown field" : {
529
+ filter : map [string ]any {
530
+ "name" : "jes%" ,
531
+ "unknown_field" : false ,
532
+ },
533
+ query : func (db * gorm.DB ) * gorm.DB {
534
+ return db .Set (tagName , true )
535
+ },
536
+ existing : []ObjectB {{Name : "jessica" , Other : "abc" }},
537
+ expected : []ObjectB {},
538
+ },
539
+ }
540
+
541
+ for name , testData := range tests {
542
+ testData := testData
543
+ t .Run (name , func (t * testing.T ) {
544
+ t .Parallel ()
545
+ // Arrange
546
+ db := gormtestutil .NewMemoryDatabase (t , gormtestutil .WithName (t .Name ()))
547
+ _ = db .AutoMigrate (& ObjectB {})
548
+ plugin := New (SettingOnly ())
549
+
550
+ if err := db .CreateInBatches (testData .existing , 10 ).Error ; err != nil {
551
+ t .Error (err )
552
+ t .FailNow ()
553
+ }
554
+
555
+ db = testData .query (db )
556
+
557
+ // Act
558
+ err := db .Use (plugin )
559
+
560
+ // Assert
561
+ assert .NoError (t , err )
562
+
563
+ var actual []ObjectB
564
+ err = db .Where (testData .filter ).Find (& actual ).Error
565
+ assert .Equal (t , "no such column: unknown_field" , err .Error ())
566
+ assert .Nil (t , actual )
567
+ })
568
+ }
569
+ }
You can’t perform that action at this time.
0 commit comments