Use table name constant in Cols for type safety
This commit is contained in:
12
gencols.go
12
gencols.go
@@ -23,10 +23,11 @@ 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
|
||||
Fields []fieldInfo // list of fields
|
||||
FilePath string // source file path
|
||||
Name string // struct name
|
||||
Table string // table name from TableName const
|
||||
TableConst string // constant name (e.g., "TableNamePsAccess")
|
||||
Fields []fieldInfo // list of fields
|
||||
FilePath string // source file path
|
||||
}
|
||||
|
||||
// parseGormColumn extracts the column name value from a gorm tag string.
|
||||
@@ -73,6 +74,7 @@ func parseModelFile(path string) (*structInfo, error) {
|
||||
}
|
||||
for i, name := range vs.Names {
|
||||
if strings.HasPrefix(name.Name, "TableName") {
|
||||
si.TableConst = name.Name
|
||||
if i < len(vs.Values) {
|
||||
if bl, ok := vs.Values[i].(*ast.BasicLit); ok {
|
||||
si.Table = strings.Trim(bl.Value, "\"")
|
||||
@@ -150,7 +152,7 @@ func generateColsVarBlock(si *structInfo) string {
|
||||
}
|
||||
b.WriteString("}{\n")
|
||||
for _, f := range si.Fields {
|
||||
b.WriteString(fmt.Sprintf("\t%s: gormcol.Field{Table: %q, Column: %q},\n", f.GoName, si.Table, f.ColName))
|
||||
b.WriteString(fmt.Sprintf("\t%s: gormcol.Field{Table: %s, Column: %q},\n", f.GoName, si.TableConst, f.ColName))
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
return b.String()
|
||||
|
||||
Reference in New Issue
Block a user