Skip to content

Commit

Permalink
Added support for custom columns names mapper functions (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
mzahradnicek authored Aug 31, 2023
1 parent 644ce11 commit 4741cc8
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
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

0 comments on commit 4741cc8

Please sign in to comment.