Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for custom columns names mapper functions #70

Merged
merged 1 commit into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion columns.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ var (
// the struct does not have a field that matches the column
// specified.
ErrStructFieldMissing = errors.New("struct field missing")

// ColumnsMapper transforms struct/map field names
// into the database column names.
// E.g. you can set function for convert CamelCase into snake_case
ColumnsMapper = func(name string) string { return name }
)

var columnsCache cache = &sync.Map{}
Expand Down Expand Up @@ -106,7 +111,7 @@ func columnNames(model reflect.Value, strict bool, excluded ...string) []string
continue
}

fieldName := typeField.Name
fieldName := ColumnsMapper(typeField.Name)
if tag, hasTag := typeField.Tag.Lookup(dbTag); hasTag {
if tag == "-" {
continue
Expand Down
6 changes: 5 additions & 1 deletion scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ var (
// OnAutoCloseError can be used to log errors which are returned from rows.Close()
// By default this is a NOOP function
OnAutoCloseError = func(error) {}

// ScannerMapper transforms database field names into struct/map field names
// E.g. you can set function for convert snake_case into CamelCase
ScannerMapper = func(name string) string { return cases.Title(language.English).String(name) }
)

// Row scans a single row into a single variable. It requires that you use
Expand Down Expand Up @@ -174,7 +178,7 @@ func structPointers(sliceItem reflect.Value, cols []string, strict bool) []inter
if strict {
fieldVal = reflect.ValueOf(nil)
} else {
fieldVal = sliceItem.FieldByName(cases.Title(language.English).String(colName))
fieldVal = sliceItem.FieldByName(ScannerMapper(colName))
}
}
if !fieldVal.IsValid() || !fieldVal.CanSet() {
Expand Down