Remove Table field from Cols, use GORM conventions
This commit is contained in:
27
gencols.go
27
gencols.go
@@ -13,6 +13,7 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// fieldInfo holds information about a struct field.
|
||||
@@ -24,12 +25,29 @@ type fieldInfo struct {
|
||||
// structInfo holds information about a parsed Go struct.
|
||||
type structInfo struct {
|
||||
Name string // struct name
|
||||
Table string // table name from TableName const
|
||||
Table string // table name (derived from struct name using GORM convention)
|
||||
TableConst string // constant name (e.g., "TableNamePsAccess")
|
||||
Fields []fieldInfo // list of fields
|
||||
FilePath string // source file path
|
||||
}
|
||||
|
||||
// toSnakeCase converts a CamelCase string to snake_case.
|
||||
// E.g., "PsProductShop" -> "ps_product_shop"
|
||||
func toSnakeCase(s string) string {
|
||||
var result strings.Builder
|
||||
for i, r := range s {
|
||||
if unicode.IsUpper(r) {
|
||||
if i > 0 {
|
||||
result.WriteRune('_')
|
||||
}
|
||||
result.WriteRune(unicode.ToLower(r))
|
||||
} else {
|
||||
result.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return result.String()
|
||||
}
|
||||
|
||||
// parseGormColumn extracts the column name value from a gorm tag string.
|
||||
// The tag is expected to be in the format "column:name;otherTag" or similar.
|
||||
// Returns the column name if found, empty string otherwise.
|
||||
@@ -134,6 +152,11 @@ func parseModelFile(path string) (*structInfo, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// If no TableName constant was found, derive table name from struct name using GORM convention.
|
||||
if si.Table == "" {
|
||||
si.Table = toSnakeCase(si.Name)
|
||||
}
|
||||
|
||||
return &si, nil
|
||||
}
|
||||
|
||||
@@ -152,7 +175,7 @@ func generateColsVarBlock(si *structInfo) string {
|
||||
}
|
||||
b.WriteString("}{\n")
|
||||
for _, f := range si.Fields {
|
||||
b.WriteString(fmt.Sprintf("\t%s: gormcol.Field{Table: %s, Column: %q},\n", f.GoName, si.TableConst, f.ColName))
|
||||
b.WriteString(fmt.Sprintf("\t%s: gormcol.Field{Column: %q},\n", f.GoName, f.ColName))
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
return b.String()
|
||||
|
||||
Reference in New Issue
Block a user