错误场景一次普通的查询
sql = "select deploy_task,deploy_number,code_version,config_version,deploy_pack,deploy_username,create_time,state,failed_node from deployments where deploy_task = ?"
result = deploy.data.db.Raw(sql, jobName).Scan(resp)
然后执行失败抛出错误
reflect: reflect.Value.Set using unaddressable value
修复方法,直接说结论由于没有使用指针接受返回值导致的。ScanRows
中判断 tx.Statement.ReflectValue.Kind() == reflect.Ptr
所以需要结构体指针。
func (db *DB) ScanRows(rows *sql.Rows, dest interface{}) error {
tx := db.getInstance()
if err := tx.Statement.Parse(dest); !errors.Is(err, schema.ErrUnsupportedDataType) {
tx.AddError(err)
}
tx.Statement.Dest = dest
tx.Statement.ReflectValue = reflect.ValueOf(dest)
for tx.Statement.ReflectValue.Kind() == reflect.Ptr {
elem := tx.Statement.ReflectValue.Elem()
if !elem.IsValid() {
elem = reflect.New(tx.Statement.ReflectValue.Type().Elem())
tx.Statement.ReflectValue.Set(elem)
}
tx.Statement.ReflectValue = elem
}
Scan(rows, tx, ScanInitialized)
return tx.Error
}