Files
relspecgo/pkg/writers/typemap.go
T
Hermes AgentandClaude Sonnet 5.5 948419ffd3 feat: add --type-map to override SQL-to-Go types in bun and gorm writers
Adds WriterOptions.TypeMappings and a repeatable --type-map sqltype=gotype
flag. Defaults are unchanged when no mapping is given. Closes #36 (bun/gorm).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 10:28:58 +02:00

47 lines
1.6 KiB
Go

package writers
import (
"fmt"
"strings"
"git.warky.dev/wdevs/relspecgo/pkg/pgsql"
)
// ParseTypeMappings parses "sqltype=gotype" entries (as given to --type-map)
// into a map keyed by the canonical lower-case SQL base type, so that
// "VARCHAR", "character varying" and "varchar(50)" all address one entry.
// It returns nil for empty input.
func ParseTypeMappings(entries []string) (map[string]string, error) {
if len(entries) == 0 {
return nil, nil
}
out := make(map[string]string, len(entries))
for _, entry := range entries {
sqlType, goType, ok := strings.Cut(entry, "=")
sqlType, goType = strings.TrimSpace(sqlType), strings.TrimSpace(goType)
if !ok || sqlType == "" || goType == "" {
return nil, fmt.Errorf("invalid type mapping %q: expected sqltype=gotype", entry)
}
out[pgsql.CanonicalizeBaseType(pgsql.ExtractBaseTypeLower(sqlType))] = goType
}
return out, nil
}
// LookupTypeMapping returns the user-configured override for baseType, which
// the caller must already have canonicalized.
func LookupTypeMapping(mappings map[string]string, baseType string) (string, bool) {
goType, ok := mappings[baseType]
return goType, ok
}
// ApplyTypeMapping wraps an overridden Go type for nullability: NOT NULL uses
// the type verbatim; nullable columns get a pointer prefix unless the type is
// already a pointer, slice, map or interface.
func ApplyTypeMapping(goType string, notNull bool) string {
if notNull || strings.HasPrefix(goType, "*") || strings.HasPrefix(goType, "[]") ||
strings.HasPrefix(goType, "map[") || goType == "any" || goType == "interface{}" {
return goType
}
return "*" + goType
}