Files
relspecgo/pkg/writers/drizzle/templates.go
Hein 35bc9dfb5c
Some checks failed
CI / Test (1.24) (push) Failing after -24m8s
CI / Test (1.25) (push) Failing after -23m54s
CI / Lint (push) Failing after -25m2s
CI / Build (push) Successful in -25m18s
Added Drizzle ORM support
2025-12-28 10:15:30 +02:00

65 lines
1.7 KiB
Go

package drizzle
import (
"bytes"
"text/template"
)
// schemaTemplate defines the template for generating Drizzle schemas
const schemaTemplate = `// Code generated by relspecgo. DO NOT EDIT.
{{range .Imports}}{{.}}
{{end}}
{{if .Enums}}
// Enums
{{range .Enums}}export const {{.VarName}} = pgEnum('{{.Name}}', [{{.ValuesStr}}]);
export type {{.Name}} = {{.TypeUnion}};
{{end}}
{{end}}
{{range .Tables}}// Table: {{.TableName}}{{if .Comment}} - {{.Comment}}{{end}}
export interface {{.TypeName}} {
{{- range $i, $col := .Columns}}
{{$col.FieldName}}: {{$col.TypeScriptType}};{{if $col.Comment}} // {{$col.Comment}}{{end}}
{{- end}}
}
export const {{.Name}} = pgTable('{{.TableName}}', {
{{- range $i, $col := .Columns}}
{{$col.FieldName}}: {{$col.DrizzleChain}},{{if $col.Comment}} // {{$col.Comment}}{{end}}
{{- end}}
}{{if .Indexes}}{{if .IndexColumnFields}}, ({ {{range $i, $field := .IndexColumnFields}}{{if $i}}, {{end}}{{$field}}{{end}} }) => [{{else}}, (table) => [{{end}}
{{- range $i, $idx := .Indexes}}
{{$idx.Definition}},
{{- end}}
]{{end}});
export type New{{.TypeName}} = typeof {{.Name}}.$inferInsert;
{{end}}`
// Templates holds the parsed templates
type Templates struct {
schemaTmpl *template.Template
}
// NewTemplates creates and parses the templates
func NewTemplates() (*Templates, error) {
schemaTmpl, err := template.New("schema").Parse(schemaTemplate)
if err != nil {
return nil, err
}
return &Templates{
schemaTmpl: schemaTmpl,
}, nil
}
// GenerateCode executes the template with the given data
func (t *Templates) GenerateCode(data *TemplateData) (string, error) {
var buf bytes.Buffer
err := t.schemaTmpl.Execute(&buf, data)
if err != nil {
return "", err
}
return buf.String(), nil
}