refactor(database):优化字段扫描与转换逻辑- 重命名 fieldVal 为 field 以提高代码可读性- 改进字段存在性和类型转换检查逻辑
- 添加详细注释说明字段处理流程 - 确保字段地址获取和转换正确处理 - 更新结构体复制和结果切片追加逻辑
This commit is contained in:
@@ -41,28 +41,28 @@ func scanIntoStruct(rows *sql.Rows, target interface{}) (results interface{}, er
|
|||||||
colNames, _ := rows.Columns()
|
colNames, _ := rows.Columns()
|
||||||
colTypes, _ := rows.ColumnTypes()
|
colTypes, _ := rows.ColumnTypes()
|
||||||
references := []interface{}{}
|
references := []interface{}{}
|
||||||
fieldVal := reflect.Value{}
|
|
||||||
var placeholder interface{}
|
var placeholder interface{}
|
||||||
|
|
||||||
for i, colName := range colNames {
|
for i, colName := range colNames {
|
||||||
Printfln("Column: %s", colName)
|
Printfln("Column: %s", colName)
|
||||||
// 获取字段值
|
// 获取字段
|
||||||
colNameParts := strings.Split(colName, ".")
|
colNameParts := strings.Split(colName, ".")
|
||||||
fieldVal = targetVal.FieldByName(colNameParts[0])
|
field := targetVal.FieldByName(colNameParts[0])
|
||||||
if fieldVal.IsValid() && fieldVal.Kind() == reflect.Struct && len(colNameParts) > 1 {
|
if field.IsValid() && field.Kind() == reflect.Struct && len(colNameParts) > 1 {
|
||||||
for _, namePart := range colNameParts[1:] {
|
for _, namePart := range colNameParts[1:] {
|
||||||
comFunction := matchColName(namePart)
|
comFunction := matchColName(namePart)
|
||||||
fieldVal = fieldVal.FieldByNameFunc(comFunction)
|
field = field.FieldByNameFunc(comFunction)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 判断是否可以转换
|
if !field.IsValid() || !colTypes[i].ScanType().ConvertibleTo(field.Type()) {
|
||||||
if !fieldVal.IsValid() || !colTypes[i].ScanType().ConvertibleTo(fieldVal.Type()) {
|
// 字段不存在或者不可以转换
|
||||||
Printfln("Column placeholder: %s", colName)
|
Printfln("Column placeholder: %s", colName)
|
||||||
references = append(references, &placeholder)
|
references = append(references, &placeholder)
|
||||||
} else if fieldVal.Kind() != reflect.Ptr && fieldVal.CanAddr() {
|
} else if field.Kind() != reflect.Ptr && field.CanAddr() {
|
||||||
|
// 字段存在并且可以转换,不为指针并且可以获取到地址
|
||||||
Printfln("Column Addr: %s", colName)
|
Printfln("Column Addr: %s", colName)
|
||||||
fieldVal = fieldVal.Addr()
|
field = field.Addr()
|
||||||
references = append(references, fieldVal.Interface())
|
references = append(references, field.Interface())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,6 +73,7 @@ func scanIntoStruct(rows *sql.Rows, target interface{}) (results interface{}, er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
// 将指针转换为结构体,从而可以复制该结构体,并增加到切片中
|
||||||
resultSlice = reflect.Append(resultSlice, targetVal)
|
resultSlice = reflect.Append(resultSlice, targetVal)
|
||||||
}
|
}
|
||||||
results = resultSlice.Interface()
|
results = resultSlice.Interface()
|
||||||
|
|||||||
Reference in New Issue
Block a user