// recordType is the type of a structure func (sess *Session) calculateFieldMap(recordType reflect.Type, columns []string, requireAllColumns bool) ([][]int, error) { // each value is either the slice to get to the field via FieldByIndex(index []int) in the record, or nil if we don't want to map it to the structure. lenColumns := len(columns) fieldMap := make([][]int, lenColumns) for i, col := range columns { fieldMap[i] = nil queue := []fieldMapQueueElement{{Type: recordType, Idxs: nil}} QueueLoop: for len(queue) > 0 { curEntry := queue[0] queue = queue[1:] curType := curEntry.Type curIdxs := curEntry.Idxs lenFields := curType.NumField() for j := 0; j < lenFields; j++ { fieldStruct := curType.Field(j) // Skip unexported field if len(fieldStruct.PkgPath) != 0 { continue } name := fieldStruct.Tag.Get("db") if name != "-" { if name == "" { name = utils.CamelCaseToUnderscore(fieldStruct.Name) } if name == col { fieldMap[i] = append(curIdxs, j) break QueueLoop } } if fieldStruct.Type.Kind() == reflect.Struct { var idxs2 []int copy(idxs2, curIdxs) idxs2 = append(idxs2, j) queue = append(queue, fieldMapQueueElement{Type: fieldStruct.Type, Idxs: idxs2}) } } } if requireAllColumns && fieldMap[i] == nil { return nil, errors.New(fmt.Sprint("couldn't find match for column ", col)) } } return fieldMap, nil }
func TestCamelCaseToUnderscore(t *testing.T) { tests := []struct { in string out string }{ {"CatalogProductEntity", "catalog_product_entity"}, {"CatalogPPoductEntity", "catalog_p_poduct_entity"}, {"catalogProductEntityE", "catalog_product_entity_e"}, {" catalogProductEntityE", " catalog_product_entity_e"}, {" CatalogProductEntityE", " _catalog_product_entity_e"}, // the leading underscore is a bug ... :-\ } for _, test := range tests { assert.Equal(t, test.out, utils.CamelCaseToUnderscore(test.in), "%#v", test) } }
// BenchmarkCamelCaseToUnderscore-4 2000000 928 ns/op 288 B/op 6 allocs/op func BenchmarkCamelCaseToUnderscore(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { benchCases = utils.CamelCaseToUnderscore("CatalogPPoductEntity") } }