So far so good
This commit is contained in:
284
pkg/writers/bun/name_converter.go
Normal file
284
pkg/writers/bun/name_converter.go
Normal file
@@ -0,0 +1,284 @@
|
||||
package bun
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// SnakeCaseToPascalCase converts snake_case to PascalCase
|
||||
// Examples: user_id → UserID, http_request → HTTPRequest
|
||||
func SnakeCaseToPascalCase(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
parts := strings.Split(s, "_")
|
||||
for i, part := range parts {
|
||||
parts[i] = capitalize(part)
|
||||
}
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
// SnakeCaseToCamelCase converts snake_case to camelCase
|
||||
// Examples: user_id → userID, http_request → httpRequest
|
||||
func SnakeCaseToCamelCase(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
parts := strings.Split(s, "_")
|
||||
for i, part := range parts {
|
||||
if i == 0 {
|
||||
parts[i] = strings.ToLower(part)
|
||||
} else {
|
||||
parts[i] = capitalize(part)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
// PascalCaseToSnakeCase converts PascalCase to snake_case
|
||||
// Examples: UserID → user_id, HTTPRequest → http_request
|
||||
func PascalCaseToSnakeCase(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
var result strings.Builder
|
||||
var prevUpper bool
|
||||
var nextUpper bool
|
||||
|
||||
runes := []rune(s)
|
||||
for i, r := range runes {
|
||||
isUpper := unicode.IsUpper(r)
|
||||
|
||||
if i+1 < len(runes) {
|
||||
nextUpper = unicode.IsUpper(runes[i+1])
|
||||
} else {
|
||||
nextUpper = false
|
||||
}
|
||||
|
||||
if i > 0 && isUpper {
|
||||
// Add underscore before uppercase letter if:
|
||||
// 1. Previous char was lowercase, OR
|
||||
// 2. Next char is lowercase (end of acronym)
|
||||
if !prevUpper || (nextUpper == false && i+1 < len(runes)) {
|
||||
result.WriteRune('_')
|
||||
}
|
||||
}
|
||||
|
||||
result.WriteRune(unicode.ToLower(r))
|
||||
prevUpper = isUpper
|
||||
}
|
||||
|
||||
return result.String()
|
||||
}
|
||||
|
||||
// capitalize capitalizes the first letter and handles common acronyms
|
||||
func capitalize(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
upper := strings.ToUpper(s)
|
||||
|
||||
// Handle common acronyms
|
||||
acronyms := map[string]bool{
|
||||
"ID": true,
|
||||
"UUID": true,
|
||||
"GUID": true,
|
||||
"URL": true,
|
||||
"URI": true,
|
||||
"HTTP": true,
|
||||
"HTTPS": true,
|
||||
"API": true,
|
||||
"JSON": true,
|
||||
"XML": true,
|
||||
"SQL": true,
|
||||
"HTML": true,
|
||||
"CSS": true,
|
||||
"RID": true,
|
||||
}
|
||||
|
||||
if acronyms[upper] {
|
||||
return upper
|
||||
}
|
||||
|
||||
// Capitalize first letter
|
||||
runes := []rune(s)
|
||||
runes[0] = unicode.ToUpper(runes[0])
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
// Pluralize converts a singular word to plural
|
||||
// Basic implementation with common rules
|
||||
func Pluralize(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Special cases
|
||||
irregular := map[string]string{
|
||||
"person": "people",
|
||||
"child": "children",
|
||||
"tooth": "teeth",
|
||||
"foot": "feet",
|
||||
"man": "men",
|
||||
"woman": "women",
|
||||
"mouse": "mice",
|
||||
"goose": "geese",
|
||||
"ox": "oxen",
|
||||
"datum": "data",
|
||||
"medium": "media",
|
||||
"analysis": "analyses",
|
||||
"crisis": "crises",
|
||||
"status": "statuses",
|
||||
}
|
||||
|
||||
if plural, ok := irregular[strings.ToLower(s)]; ok {
|
||||
return plural
|
||||
}
|
||||
|
||||
// Already plural (ends in 's' but not 'ss' or 'us')
|
||||
if strings.HasSuffix(s, "s") && !strings.HasSuffix(s, "ss") && !strings.HasSuffix(s, "us") {
|
||||
return s
|
||||
}
|
||||
|
||||
// Words ending in s, x, z, ch, sh
|
||||
if strings.HasSuffix(s, "s") || strings.HasSuffix(s, "x") ||
|
||||
strings.HasSuffix(s, "z") || strings.HasSuffix(s, "ch") ||
|
||||
strings.HasSuffix(s, "sh") {
|
||||
return s + "es"
|
||||
}
|
||||
|
||||
// Words ending in consonant + y
|
||||
if len(s) >= 2 && strings.HasSuffix(s, "y") {
|
||||
prevChar := s[len(s)-2]
|
||||
if !isVowel(prevChar) {
|
||||
return s[:len(s)-1] + "ies"
|
||||
}
|
||||
}
|
||||
|
||||
// Words ending in f or fe
|
||||
if strings.HasSuffix(s, "f") {
|
||||
return s[:len(s)-1] + "ves"
|
||||
}
|
||||
if strings.HasSuffix(s, "fe") {
|
||||
return s[:len(s)-2] + "ves"
|
||||
}
|
||||
|
||||
// Words ending in consonant + o
|
||||
if len(s) >= 2 && strings.HasSuffix(s, "o") {
|
||||
prevChar := s[len(s)-2]
|
||||
if !isVowel(prevChar) {
|
||||
return s + "es"
|
||||
}
|
||||
}
|
||||
|
||||
// Default: add 's'
|
||||
return s + "s"
|
||||
}
|
||||
|
||||
// Singularize converts a plural word to singular
|
||||
// Basic implementation with common rules
|
||||
func Singularize(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Special cases
|
||||
irregular := map[string]string{
|
||||
"people": "person",
|
||||
"children": "child",
|
||||
"teeth": "tooth",
|
||||
"feet": "foot",
|
||||
"men": "man",
|
||||
"women": "woman",
|
||||
"mice": "mouse",
|
||||
"geese": "goose",
|
||||
"oxen": "ox",
|
||||
"data": "datum",
|
||||
"media": "medium",
|
||||
"analyses": "analysis",
|
||||
"crises": "crisis",
|
||||
"statuses": "status",
|
||||
}
|
||||
|
||||
if singular, ok := irregular[strings.ToLower(s)]; ok {
|
||||
return singular
|
||||
}
|
||||
|
||||
// Words ending in ies
|
||||
if strings.HasSuffix(s, "ies") && len(s) > 3 {
|
||||
return s[:len(s)-3] + "y"
|
||||
}
|
||||
|
||||
// Words ending in ves
|
||||
if strings.HasSuffix(s, "ves") {
|
||||
return s[:len(s)-3] + "f"
|
||||
}
|
||||
|
||||
// Words ending in ses, xes, zes, ches, shes
|
||||
if strings.HasSuffix(s, "ses") || strings.HasSuffix(s, "xes") ||
|
||||
strings.HasSuffix(s, "zes") || strings.HasSuffix(s, "ches") ||
|
||||
strings.HasSuffix(s, "shes") {
|
||||
return s[:len(s)-2]
|
||||
}
|
||||
|
||||
// Words ending in s (not ss)
|
||||
if strings.HasSuffix(s, "s") && !strings.HasSuffix(s, "ss") {
|
||||
return s[:len(s)-1]
|
||||
}
|
||||
|
||||
// Already singular
|
||||
return s
|
||||
}
|
||||
|
||||
// GeneratePrefix generates a 3-letter prefix from a table name
|
||||
// Examples: process → PRO, mastertask → MTL, user → USR
|
||||
func GeneratePrefix(tableName string) string {
|
||||
if tableName == "" {
|
||||
return "TBL"
|
||||
}
|
||||
|
||||
// Remove common prefixes
|
||||
tableName = strings.TrimPrefix(tableName, "tbl_")
|
||||
tableName = strings.TrimPrefix(tableName, "tb_")
|
||||
|
||||
// Split by underscore and take first letters
|
||||
parts := strings.Split(tableName, "_")
|
||||
|
||||
var prefix strings.Builder
|
||||
for _, part := range parts {
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
prefix.WriteRune(unicode.ToUpper(rune(part[0])))
|
||||
if prefix.Len() >= 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
result := prefix.String()
|
||||
|
||||
// If we don't have 3 letters yet, add more from the first part
|
||||
if len(result) < 3 && len(parts) > 0 {
|
||||
firstPart := parts[0]
|
||||
for i := 1; i < len(firstPart) && len(result) < 3; i++ {
|
||||
result += strings.ToUpper(string(firstPart[i]))
|
||||
}
|
||||
}
|
||||
|
||||
// Pad with 'X' if still too short
|
||||
for len(result) < 3 {
|
||||
result += "X"
|
||||
}
|
||||
|
||||
return result[:3]
|
||||
}
|
||||
|
||||
// isVowel checks if a byte is a vowel
|
||||
func isVowel(c byte) bool {
|
||||
c = byte(unicode.ToLower(rune(c)))
|
||||
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
|
||||
}
|
||||
250
pkg/writers/bun/template_data.go
Normal file
250
pkg/writers/bun/template_data.go
Normal file
@@ -0,0 +1,250 @@
|
||||
package bun
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||
)
|
||||
|
||||
// TemplateData represents the data passed to the template for code generation
|
||||
type TemplateData struct {
|
||||
PackageName string
|
||||
Imports []string
|
||||
Models []*ModelData
|
||||
Config *MethodConfig
|
||||
}
|
||||
|
||||
// ModelData represents a single model/struct in the template
|
||||
type ModelData struct {
|
||||
Name string
|
||||
TableName string // schema.table format
|
||||
SchemaName string
|
||||
TableNameOnly string // just table name without schema
|
||||
Comment string
|
||||
Fields []*FieldData
|
||||
Config *MethodConfig
|
||||
PrimaryKeyField string // Name of the primary key field
|
||||
IDColumnName string // Name of the ID column in database
|
||||
Prefix string // 3-letter prefix
|
||||
}
|
||||
|
||||
// FieldData represents a single field in a struct
|
||||
type FieldData struct {
|
||||
Name string // Go field name (PascalCase)
|
||||
Type string // Go type
|
||||
GormTag string // Complete gorm tag
|
||||
JSONTag string // JSON tag
|
||||
Comment string // Field comment
|
||||
}
|
||||
|
||||
// MethodConfig controls which helper methods to generate
|
||||
type MethodConfig struct {
|
||||
GenerateTableName bool
|
||||
GenerateSchemaName bool
|
||||
GenerateTableNameOnly bool
|
||||
GenerateGetID bool
|
||||
GenerateGetIDStr bool
|
||||
GenerateSetID bool
|
||||
GenerateUpdateID bool
|
||||
GenerateGetIDName bool
|
||||
GenerateGetPrefix bool
|
||||
}
|
||||
|
||||
// DefaultMethodConfig returns a MethodConfig with all methods enabled
|
||||
func DefaultMethodConfig() *MethodConfig {
|
||||
return &MethodConfig{
|
||||
GenerateTableName: true,
|
||||
GenerateSchemaName: true,
|
||||
GenerateTableNameOnly: true,
|
||||
GenerateGetID: true,
|
||||
GenerateGetIDStr: true,
|
||||
GenerateSetID: true,
|
||||
GenerateUpdateID: true,
|
||||
GenerateGetIDName: true,
|
||||
GenerateGetPrefix: true,
|
||||
}
|
||||
}
|
||||
|
||||
// NewTemplateData creates a new TemplateData with the given package name and config
|
||||
func NewTemplateData(packageName string, config *MethodConfig) *TemplateData {
|
||||
if config == nil {
|
||||
config = DefaultMethodConfig()
|
||||
}
|
||||
|
||||
return &TemplateData{
|
||||
PackageName: packageName,
|
||||
Imports: make([]string, 0),
|
||||
Models: make([]*ModelData, 0),
|
||||
Config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// AddModel adds a model to the template data
|
||||
func (td *TemplateData) AddModel(model *ModelData) {
|
||||
model.Config = td.Config
|
||||
td.Models = append(td.Models, model)
|
||||
}
|
||||
|
||||
// AddImport adds an import to the template data (deduplicates automatically)
|
||||
func (td *TemplateData) AddImport(importPath string) {
|
||||
// Check if already exists
|
||||
for _, imp := range td.Imports {
|
||||
if imp == importPath {
|
||||
return
|
||||
}
|
||||
}
|
||||
td.Imports = append(td.Imports, importPath)
|
||||
}
|
||||
|
||||
// FinalizeImports sorts and organizes imports
|
||||
func (td *TemplateData) FinalizeImports() {
|
||||
// Sort imports alphabetically
|
||||
sort.Strings(td.Imports)
|
||||
}
|
||||
|
||||
// NewModelData creates a new ModelData from a models.Table
|
||||
func NewModelData(table *models.Table, schema string, typeMapper *TypeMapper) *ModelData {
|
||||
tableName := table.Name
|
||||
if schema != "" {
|
||||
tableName = schema + "." + table.Name
|
||||
}
|
||||
|
||||
// Generate model name: singularize and convert to PascalCase
|
||||
singularTable := Singularize(table.Name)
|
||||
modelName := SnakeCaseToPascalCase(singularTable)
|
||||
|
||||
// Add "Model" prefix if not already present
|
||||
if !hasModelPrefix(modelName) {
|
||||
modelName = "Model" + modelName
|
||||
}
|
||||
|
||||
model := &ModelData{
|
||||
Name: modelName,
|
||||
TableName: tableName,
|
||||
SchemaName: schema,
|
||||
TableNameOnly: table.Name,
|
||||
Comment: formatComment(table.Description, table.Comment),
|
||||
Fields: make([]*FieldData, 0),
|
||||
Prefix: GeneratePrefix(table.Name),
|
||||
}
|
||||
|
||||
// Find primary key
|
||||
for _, col := range table.Columns {
|
||||
if col.IsPrimaryKey {
|
||||
model.PrimaryKeyField = SnakeCaseToPascalCase(col.Name)
|
||||
model.IDColumnName = col.Name
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Convert columns to fields (sorted by sequence or name)
|
||||
columns := sortColumns(table.Columns)
|
||||
for _, col := range columns {
|
||||
field := columnToField(col, table, typeMapper)
|
||||
model.Fields = append(model.Fields, field)
|
||||
}
|
||||
|
||||
return model
|
||||
}
|
||||
|
||||
// columnToField converts a models.Column to FieldData
|
||||
func columnToField(col *models.Column, table *models.Table, typeMapper *TypeMapper) *FieldData {
|
||||
fieldName := SnakeCaseToPascalCase(col.Name)
|
||||
goType := typeMapper.SQLTypeToGoType(col.Type, col.NotNull)
|
||||
gormTag := typeMapper.BuildGormTag(col, table)
|
||||
jsonTag := col.Name // Use column name for JSON tag
|
||||
|
||||
return &FieldData{
|
||||
Name: fieldName,
|
||||
Type: goType,
|
||||
GormTag: gormTag,
|
||||
JSONTag: jsonTag,
|
||||
Comment: formatComment(col.Description, col.Comment),
|
||||
}
|
||||
}
|
||||
|
||||
// AddRelationshipField adds a relationship field to the model
|
||||
func (md *ModelData) AddRelationshipField(field *FieldData) {
|
||||
md.Fields = append(md.Fields, field)
|
||||
}
|
||||
|
||||
// formatComment combines description and comment into a single comment string
|
||||
func formatComment(description, comment string) string {
|
||||
if description != "" && comment != "" {
|
||||
return description + " - " + comment
|
||||
}
|
||||
if description != "" {
|
||||
return description
|
||||
}
|
||||
return comment
|
||||
}
|
||||
|
||||
// hasModelPrefix checks if a name already has "Model" prefix
|
||||
func hasModelPrefix(name string) bool {
|
||||
return len(name) >= 5 && name[:5] == "Model"
|
||||
}
|
||||
|
||||
// sortColumns sorts columns by sequence, then by name
|
||||
func sortColumns(columns map[string]*models.Column) []*models.Column {
|
||||
result := make([]*models.Column, 0, len(columns))
|
||||
for _, col := range columns {
|
||||
result = append(result, col)
|
||||
}
|
||||
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
// Sort by sequence if both have it
|
||||
if result[i].Sequence > 0 && result[j].Sequence > 0 {
|
||||
return result[i].Sequence < result[j].Sequence
|
||||
}
|
||||
|
||||
// Put primary keys first
|
||||
if result[i].IsPrimaryKey != result[j].IsPrimaryKey {
|
||||
return result[i].IsPrimaryKey
|
||||
}
|
||||
|
||||
// Otherwise sort alphabetically
|
||||
return result[i].Name < result[j].Name
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// LoadMethodConfigFromMetadata loads method configuration from metadata map
|
||||
func LoadMethodConfigFromMetadata(metadata map[string]interface{}) *MethodConfig {
|
||||
config := DefaultMethodConfig()
|
||||
|
||||
if metadata == nil {
|
||||
return config
|
||||
}
|
||||
|
||||
// Load each setting from metadata if present
|
||||
if val, ok := metadata["generate_table_name"].(bool); ok {
|
||||
config.GenerateTableName = val
|
||||
}
|
||||
if val, ok := metadata["generate_schema_name"].(bool); ok {
|
||||
config.GenerateSchemaName = val
|
||||
}
|
||||
if val, ok := metadata["generate_table_name_only"].(bool); ok {
|
||||
config.GenerateTableNameOnly = val
|
||||
}
|
||||
if val, ok := metadata["generate_get_id"].(bool); ok {
|
||||
config.GenerateGetID = val
|
||||
}
|
||||
if val, ok := metadata["generate_get_id_str"].(bool); ok {
|
||||
config.GenerateGetIDStr = val
|
||||
}
|
||||
if val, ok := metadata["generate_set_id"].(bool); ok {
|
||||
config.GenerateSetID = val
|
||||
}
|
||||
if val, ok := metadata["generate_update_id"].(bool); ok {
|
||||
config.GenerateUpdateID = val
|
||||
}
|
||||
if val, ok := metadata["generate_get_id_name"].(bool); ok {
|
||||
config.GenerateGetIDName = val
|
||||
}
|
||||
if val, ok := metadata["generate_get_prefix"].(bool); ok {
|
||||
config.GenerateGetPrefix = val
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
118
pkg/writers/bun/templates.go
Normal file
118
pkg/writers/bun/templates.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package bun
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
// modelTemplate defines the template for generating Bun models
|
||||
const modelTemplate = `// Code generated by relspecgo. DO NOT EDIT.
|
||||
package {{.PackageName}}
|
||||
|
||||
{{if .Imports -}}
|
||||
import (
|
||||
{{range .Imports -}}
|
||||
{{.}}
|
||||
{{end -}}
|
||||
)
|
||||
{{end}}
|
||||
{{range .Models}}
|
||||
{{if .Comment}}// {{.Comment}}{{end}}
|
||||
type {{.Name}} struct {
|
||||
bun.BaseModel ` + "`bun:\"table:{{.TableName}},alias:{{.TableNameOnly}}\"`" + `
|
||||
{{- range .Fields}}
|
||||
{{.Name}} {{.Type}} ` + "`bun:\"{{.BunTag}}\" json:\"{{.JSONTag}}\"`" + `{{if .Comment}} // {{.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}
|
||||
{{if .Config.GenerateTableName}}
|
||||
// TableName returns the table name for {{.Name}}
|
||||
func (m {{.Name}}) TableName() string {
|
||||
return "{{.TableName}}"
|
||||
}
|
||||
{{end}}
|
||||
{{if .Config.GenerateTableNameOnly}}
|
||||
// TableNameOnly returns the table name without schema for {{.Name}}
|
||||
func (m {{.Name}}) TableNameOnly() string {
|
||||
return "{{.TableNameOnly}}"
|
||||
}
|
||||
{{end}}
|
||||
{{if .Config.GenerateSchemaName}}
|
||||
// SchemaName returns the schema name for {{.Name}}
|
||||
func (m {{.Name}}) SchemaName() string {
|
||||
return "{{.SchemaName}}"
|
||||
}
|
||||
{{end}}
|
||||
{{if and .Config.GenerateGetID .PrimaryKeyField}}
|
||||
// GetID returns the primary key value
|
||||
func (m {{.Name}}) GetID() int64 {
|
||||
{{if .PrimaryKeyIsSQL -}}
|
||||
return m.{{.PrimaryKeyField}}.Int64()
|
||||
{{- else -}}
|
||||
return int64(m.{{.PrimaryKeyField}})
|
||||
{{- end}}
|
||||
}
|
||||
{{end}}
|
||||
{{if and .Config.GenerateGetIDStr .PrimaryKeyField}}
|
||||
// GetIDStr returns the primary key as a string
|
||||
func (m {{.Name}}) GetIDStr() string {
|
||||
return fmt.Sprintf("%d", m.{{.PrimaryKeyField}})
|
||||
}
|
||||
{{end}}
|
||||
{{if and .Config.GenerateSetID .PrimaryKeyField}}
|
||||
// SetID sets the primary key value
|
||||
func (m {{.Name}}) SetID(newid int64) {
|
||||
m.UpdateID(newid)
|
||||
}
|
||||
{{end}}
|
||||
{{if and .Config.GenerateUpdateID .PrimaryKeyField}}
|
||||
// UpdateID updates the primary key value
|
||||
func (m *{{.Name}}) UpdateID(newid int64) {
|
||||
{{if .PrimaryKeyIsSQL -}}
|
||||
m.{{.PrimaryKeyField}}.FromString(fmt.Sprintf("%d", newid))
|
||||
{{- else -}}
|
||||
m.{{.PrimaryKeyField}} = int32(newid)
|
||||
{{- end}}
|
||||
}
|
||||
{{end}}
|
||||
{{if and .Config.GenerateGetIDName .IDColumnName}}
|
||||
// GetIDName returns the name of the primary key column
|
||||
func (m {{.Name}}) GetIDName() string {
|
||||
return "{{.IDColumnName}}"
|
||||
}
|
||||
{{end}}
|
||||
{{if .Config.GenerateGetPrefix}}
|
||||
// GetPrefix returns the table prefix
|
||||
func (m {{.Name}}) GetPrefix() string {
|
||||
return "{{.Prefix}}"
|
||||
}
|
||||
{{end}}
|
||||
{{end -}}
|
||||
`
|
||||
|
||||
// Templates holds the parsed templates
|
||||
type Templates struct {
|
||||
modelTmpl *template.Template
|
||||
}
|
||||
|
||||
// NewTemplates creates and parses the templates
|
||||
func NewTemplates() (*Templates, error) {
|
||||
modelTmpl, err := template.New("model").Parse(modelTemplate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Templates{
|
||||
modelTmpl: modelTmpl,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GenerateCode executes the template with the given data
|
||||
func (t *Templates) GenerateCode(data *TemplateData) (string, error) {
|
||||
var buf bytes.Buffer
|
||||
err := t.modelTmpl.Execute(&buf, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
253
pkg/writers/bun/type_mapper.go
Normal file
253
pkg/writers/bun/type_mapper.go
Normal file
@@ -0,0 +1,253 @@
|
||||
package bun
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||
)
|
||||
|
||||
// TypeMapper handles type conversions between SQL and Go types for Bun
|
||||
type TypeMapper struct {
|
||||
// Package alias for sql_types import
|
||||
sqlTypesAlias string
|
||||
}
|
||||
|
||||
// NewTypeMapper creates a new TypeMapper with default settings
|
||||
func NewTypeMapper() *TypeMapper {
|
||||
return &TypeMapper{
|
||||
sqlTypesAlias: "resolvespec_common",
|
||||
}
|
||||
}
|
||||
|
||||
// SQLTypeToGoType converts a SQL type to its Go equivalent
|
||||
// Uses ResolveSpec common package types (all are nullable by default in Bun)
|
||||
func (tm *TypeMapper) SQLTypeToGoType(sqlType string, notNull bool) string {
|
||||
// Normalize SQL type (lowercase, remove length/precision)
|
||||
baseType := tm.extractBaseType(sqlType)
|
||||
|
||||
// For Bun, we typically use resolvespec_common types for most fields
|
||||
// unless they're explicitly NOT NULL and we want to avoid null handling
|
||||
if notNull && tm.isSimpleType(baseType) {
|
||||
return tm.baseGoType(baseType)
|
||||
}
|
||||
|
||||
// Use resolvespec_common types for nullable fields
|
||||
return tm.bunGoType(baseType)
|
||||
}
|
||||
|
||||
// extractBaseType extracts the base type from a SQL type string
|
||||
func (tm *TypeMapper) extractBaseType(sqlType string) string {
|
||||
sqlType = strings.ToLower(strings.TrimSpace(sqlType))
|
||||
|
||||
// Remove everything after '('
|
||||
if idx := strings.Index(sqlType, "("); idx > 0 {
|
||||
sqlType = sqlType[:idx]
|
||||
}
|
||||
|
||||
return sqlType
|
||||
}
|
||||
|
||||
// isSimpleType checks if a type should use base Go type when NOT NULL
|
||||
func (tm *TypeMapper) isSimpleType(sqlType string) bool {
|
||||
simpleTypes := map[string]bool{
|
||||
"bigint": true,
|
||||
"integer": true,
|
||||
"int8": true,
|
||||
"int4": true,
|
||||
"boolean": true,
|
||||
"bool": true,
|
||||
}
|
||||
return simpleTypes[sqlType]
|
||||
}
|
||||
|
||||
// baseGoType returns the base Go type for a SQL type (not null, simple types only)
|
||||
func (tm *TypeMapper) baseGoType(sqlType string) string {
|
||||
typeMap := map[string]string{
|
||||
"integer": "int32",
|
||||
"int": "int32",
|
||||
"int4": "int32",
|
||||
"smallint": "int16",
|
||||
"int2": "int16",
|
||||
"bigint": "int64",
|
||||
"int8": "int64",
|
||||
"serial": "int32",
|
||||
"bigserial": "int64",
|
||||
"boolean": "bool",
|
||||
"bool": "bool",
|
||||
}
|
||||
|
||||
if goType, ok := typeMap[sqlType]; ok {
|
||||
return goType
|
||||
}
|
||||
|
||||
// Default to resolvespec type
|
||||
return tm.bunGoType(sqlType)
|
||||
}
|
||||
|
||||
// bunGoType returns the Bun/ResolveSpec common type
|
||||
func (tm *TypeMapper) bunGoType(sqlType string) string {
|
||||
typeMap := map[string]string{
|
||||
// Integer types
|
||||
"integer": tm.sqlTypesAlias + ".SqlInt32",
|
||||
"int": tm.sqlTypesAlias + ".SqlInt32",
|
||||
"int4": tm.sqlTypesAlias + ".SqlInt32",
|
||||
"smallint": tm.sqlTypesAlias + ".SqlInt16",
|
||||
"int2": tm.sqlTypesAlias + ".SqlInt16",
|
||||
"bigint": tm.sqlTypesAlias + ".SqlInt64",
|
||||
"int8": tm.sqlTypesAlias + ".SqlInt64",
|
||||
"serial": tm.sqlTypesAlias + ".SqlInt32",
|
||||
"bigserial": tm.sqlTypesAlias + ".SqlInt64",
|
||||
"smallserial": tm.sqlTypesAlias + ".SqlInt16",
|
||||
|
||||
// String types
|
||||
"text": tm.sqlTypesAlias + ".SqlString",
|
||||
"varchar": tm.sqlTypesAlias + ".SqlString",
|
||||
"char": tm.sqlTypesAlias + ".SqlString",
|
||||
"character": tm.sqlTypesAlias + ".SqlString",
|
||||
"citext": tm.sqlTypesAlias + ".SqlString",
|
||||
"bpchar": tm.sqlTypesAlias + ".SqlString",
|
||||
|
||||
// Boolean
|
||||
"boolean": tm.sqlTypesAlias + ".SqlBool",
|
||||
"bool": tm.sqlTypesAlias + ".SqlBool",
|
||||
|
||||
// Float types
|
||||
"real": tm.sqlTypesAlias + ".SqlFloat32",
|
||||
"float4": tm.sqlTypesAlias + ".SqlFloat32",
|
||||
"double precision": tm.sqlTypesAlias + ".SqlFloat64",
|
||||
"float8": tm.sqlTypesAlias + ".SqlFloat64",
|
||||
"numeric": tm.sqlTypesAlias + ".SqlFloat64",
|
||||
"decimal": tm.sqlTypesAlias + ".SqlFloat64",
|
||||
|
||||
// Date/Time types
|
||||
"timestamp": tm.sqlTypesAlias + ".SqlTime",
|
||||
"timestamp without time zone": tm.sqlTypesAlias + ".SqlTime",
|
||||
"timestamp with time zone": tm.sqlTypesAlias + ".SqlTime",
|
||||
"timestamptz": tm.sqlTypesAlias + ".SqlTime",
|
||||
"date": tm.sqlTypesAlias + ".SqlDate",
|
||||
"time": tm.sqlTypesAlias + ".SqlTime",
|
||||
"time without time zone": tm.sqlTypesAlias + ".SqlTime",
|
||||
"time with time zone": tm.sqlTypesAlias + ".SqlTime",
|
||||
"timetz": tm.sqlTypesAlias + ".SqlTime",
|
||||
|
||||
// Binary
|
||||
"bytea": "[]byte",
|
||||
|
||||
// UUID
|
||||
"uuid": tm.sqlTypesAlias + ".SqlUUID",
|
||||
|
||||
// JSON
|
||||
"json": tm.sqlTypesAlias + ".SqlJSON",
|
||||
"jsonb": tm.sqlTypesAlias + ".SqlJSONB",
|
||||
|
||||
// Network
|
||||
"inet": tm.sqlTypesAlias + ".SqlString",
|
||||
"cidr": tm.sqlTypesAlias + ".SqlString",
|
||||
"macaddr": tm.sqlTypesAlias + ".SqlString",
|
||||
|
||||
// Other
|
||||
"money": tm.sqlTypesAlias + ".SqlFloat64",
|
||||
}
|
||||
|
||||
if goType, ok := typeMap[sqlType]; ok {
|
||||
return goType
|
||||
}
|
||||
|
||||
// Default to SqlString for unknown types
|
||||
return tm.sqlTypesAlias + ".SqlString"
|
||||
}
|
||||
|
||||
// BuildBunTag generates a complete Bun tag string for a column
|
||||
// Bun format: bun:"column_name,type:type_name,pk,default:value"
|
||||
func (tm *TypeMapper) BuildBunTag(column *models.Column, table *models.Table) string {
|
||||
var parts []string
|
||||
|
||||
// Column name comes first (no prefix)
|
||||
parts = append(parts, column.Name)
|
||||
|
||||
// Add type if specified
|
||||
if column.Type != "" {
|
||||
typeStr := column.Type
|
||||
if column.Length > 0 {
|
||||
typeStr = fmt.Sprintf("%s(%d)", typeStr, column.Length)
|
||||
} else if column.Precision > 0 {
|
||||
if column.Scale > 0 {
|
||||
typeStr = fmt.Sprintf("%s(%d,%d)", typeStr, column.Precision, column.Scale)
|
||||
} else {
|
||||
typeStr = fmt.Sprintf("%s(%d)", typeStr, column.Precision)
|
||||
}
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("type:%s", typeStr))
|
||||
}
|
||||
|
||||
// Primary key
|
||||
if column.IsPrimaryKey {
|
||||
parts = append(parts, "pk")
|
||||
}
|
||||
|
||||
// Default value
|
||||
if column.Default != nil {
|
||||
parts = append(parts, fmt.Sprintf("default:%v", column.Default))
|
||||
}
|
||||
|
||||
// Nullable (Bun uses nullzero for nullable fields)
|
||||
if !column.NotNull && !column.IsPrimaryKey {
|
||||
parts = append(parts, "nullzero")
|
||||
}
|
||||
|
||||
// Check for unique constraint
|
||||
if table != nil {
|
||||
for _, constraint := range table.Constraints {
|
||||
if constraint.Type == models.UniqueConstraint {
|
||||
for _, col := range constraint.Columns {
|
||||
if col == column.Name {
|
||||
parts = append(parts, "unique")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Join with commas and add trailing comma (Bun convention)
|
||||
return strings.Join(parts, ",") + ","
|
||||
}
|
||||
|
||||
// BuildRelationshipTag generates Bun tag for relationship fields
|
||||
// Bun format: bun:"rel:has-one,join:local_column=foreign_column"
|
||||
func (tm *TypeMapper) BuildRelationshipTag(constraint *models.Constraint, relType string) string {
|
||||
var parts []string
|
||||
|
||||
// Add relationship type
|
||||
parts = append(parts, fmt.Sprintf("rel:%s", relType))
|
||||
|
||||
// Add join clause
|
||||
if len(constraint.Columns) > 0 && len(constraint.ReferencedColumns) > 0 {
|
||||
localCol := constraint.Columns[0]
|
||||
foreignCol := constraint.ReferencedColumns[0]
|
||||
parts = append(parts, fmt.Sprintf("join:%s=%s", localCol, foreignCol))
|
||||
}
|
||||
|
||||
return strings.Join(parts, ",")
|
||||
}
|
||||
|
||||
// NeedsTimeImport checks if the Go type requires time package import
|
||||
func (tm *TypeMapper) NeedsTimeImport(goType string) bool {
|
||||
return strings.Contains(goType, "time.Time")
|
||||
}
|
||||
|
||||
// NeedsFmtImport checks if we need fmt import (for GetIDStr method)
|
||||
func (tm *TypeMapper) NeedsFmtImport(generateGetIDStr bool) bool {
|
||||
return generateGetIDStr
|
||||
}
|
||||
|
||||
// GetSQLTypesImport returns the import path for sql_types (ResolveSpec common)
|
||||
func (tm *TypeMapper) GetSQLTypesImport() string {
|
||||
return "github.com/bitechdev/ResolveSpec/pkg/common"
|
||||
}
|
||||
|
||||
// GetBunImport returns the import path for Bun
|
||||
func (tm *TypeMapper) GetBunImport() string {
|
||||
return "github.com/uptrace/bun"
|
||||
}
|
||||
Reference in New Issue
Block a user