fix(scan): array element is set to a zero value (#6890)
* fix(scan): array element is set to a zero value * add test * fix test * optimization
This commit is contained in:
		
							parent
							
								
									e4e23d26d2
								
							
						
					
					
						commit
						7b1fb0bd73
					
				
							
								
								
									
										4
									
								
								scan.go
									
									
									
									
									
								
							
							
						
						
									
										4
									
								
								scan.go
									
									
									
									
									
								
							| @ -274,7 +274,9 @@ func Scan(rows Rows, db *DB, mode ScanMode) { | |||||||
| 
 | 
 | ||||||
| 			if !update || reflectValue.Len() == 0 { | 			if !update || reflectValue.Len() == 0 { | ||||||
| 				update = false | 				update = false | ||||||
| 				if !isArrayKind { | 				if isArrayKind { | ||||||
|  | 					db.Statement.ReflectValue.Set(reflect.Zero(reflectValue.Type())) | ||||||
|  | 				} else { | ||||||
| 					// if the slice cap is externally initialized, the externally initialized slice is directly used here
 | 					// if the slice cap is externally initialized, the externally initialized slice is directly used here
 | ||||||
| 					if reflectValue.Cap() == 0 { | 					if reflectValue.Cap() == 0 { | ||||||
| 						db.Statement.ReflectValue.Set(reflect.MakeSlice(reflectValue.Type(), 0, 20)) | 						db.Statement.ReflectValue.Set(reflect.MakeSlice(reflectValue.Type(), 0, 20)) | ||||||
|  | |||||||
| @ -1409,3 +1409,22 @@ func TestQueryError(t *testing.T) { | |||||||
| 	}, Value: 1}).Scan(&p2).Error | 	}, Value: 1}).Scan(&p2).Error | ||||||
| 	AssertEqual(t, err, gorm.ErrModelValueRequired) | 	AssertEqual(t, err, gorm.ErrModelValueRequired) | ||||||
| } | } | ||||||
|  | 
 | ||||||
|  | func TestQueryScanToArray(t *testing.T) { | ||||||
|  | 	err := DB.Create(&User{Name: "testname1", Age: 10}).Error | ||||||
|  | 	if err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	users := [2]*User{{Name: "1"}, {Name: "2"}} | ||||||
|  | 	err = DB.Model(&User{}).Where("name = ?", "testname1").Find(&users).Error | ||||||
|  | 	if err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | 	if users[0] == nil || users[0].Name != "testname1" { | ||||||
|  | 		t.Error("users[0] not covere") | ||||||
|  | 	} | ||||||
|  | 	if users[1] != nil { | ||||||
|  | 		t.Error("users[1] should be empty") | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  | |||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 jessetang
						jessetang