Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca226e83df | ||
|
|
19a2cc1fe3 | ||
|
|
58e46e5b59 |
@@ -22,7 +22,7 @@ GOVULNCHECK = go run golang.org/x/vuln/cmd/govulncheck@latest
|
|||||||
# Version information
|
# Version information
|
||||||
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
||||||
BUILD_DATE := $(shell date -u +"%Y-%m-%d %H:%M:%S UTC")
|
BUILD_DATE := $(shell date -u +"%Y-%m-%d %H:%M:%S UTC")
|
||||||
LDFLAGS := -X 'main.version=$(VERSION)' -X 'main.buildDate=$(BUILD_DATE)'
|
LDFLAGS := -X 'git.warky.dev/wdevs/relspecgo/pkg/buildinfo.Version=$(VERSION)' -X 'git.warky.dev/wdevs/relspecgo/pkg/buildinfo.BuildDate=$(BUILD_DATE)'
|
||||||
|
|
||||||
# Auto-detect container runtime (Docker or Podman)
|
# Auto-detect container runtime (Docker or Podman)
|
||||||
CONTAINER_RUNTIME := $(shell \
|
CONTAINER_RUNTIME := $(shell \
|
||||||
@@ -207,7 +207,7 @@ docker-test-integration: docker-up ## Start DB and run integration tests
|
|||||||
$(GOTEST) -v ./pkg/readers/pgsql/ -count=1 || (make docker-down && exit 1)
|
$(GOTEST) -v ./pkg/readers/pgsql/ -count=1 || (make docker-down && exit 1)
|
||||||
@make docker-down
|
@make docker-down
|
||||||
|
|
||||||
release: ## Create and push a new release tag (auto-increments patch version)
|
release: lint fmt-check test build ## Run lint, format check, tests, build, then create and push a new release tag
|
||||||
@echo "Creating new release..."
|
@echo "Creating new release..."
|
||||||
@latest_tag=$$(git describe --tags --abbrev=0 2>/dev/null || echo ""); \
|
@latest_tag=$$(git describe --tags --abbrev=0 2>/dev/null || echo ""); \
|
||||||
if [ -z "$$latest_tag" ]; then \
|
if [ -z "$$latest_tag" ]; then \
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// asciiLogo (see version.go) is printed by the `version` command.
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
args := os.Args[1:]
|
args := os.Args[1:]
|
||||||
isSilent := hasSilentFlag(args)
|
isSilent := hasSilentFlag(args)
|
||||||
|
|||||||
+6
-35
@@ -2,52 +2,23 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"runtime/debug"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// version/buildDate mirror pkg/buildinfo so existing call sites keep working.
|
||||||
|
// The actual values are set there via ldflags (see Makefile).
|
||||||
var (
|
var (
|
||||||
// Version information, set via ldflags during build
|
version = buildinfo.Version
|
||||||
version = "dev"
|
buildDate = buildinfo.BuildDate
|
||||||
buildDate = "unknown"
|
|
||||||
prisma7 bool
|
prisma7 bool
|
||||||
noVersion bool
|
noVersion bool
|
||||||
silent bool
|
silent bool
|
||||||
strictDirectives bool
|
strictDirectives bool
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
|
||||||
// If version wasn't set via ldflags, try to get it from build info
|
|
||||||
if version == "dev" {
|
|
||||||
if info, ok := debug.ReadBuildInfo(); ok {
|
|
||||||
// Try to get version from VCS
|
|
||||||
var vcsRevision, vcsTime string
|
|
||||||
for _, setting := range info.Settings {
|
|
||||||
switch setting.Key {
|
|
||||||
case "vcs.revision":
|
|
||||||
if len(setting.Value) >= 7 {
|
|
||||||
vcsRevision = setting.Value[:7]
|
|
||||||
}
|
|
||||||
case "vcs.time":
|
|
||||||
vcsTime = setting.Value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if vcsRevision != "" {
|
|
||||||
version = vcsRevision
|
|
||||||
}
|
|
||||||
|
|
||||||
if vcsTime != "" {
|
|
||||||
if t, err := time.Parse(time.RFC3339, vcsTime); err == nil {
|
|
||||||
buildDate = t.UTC().Format("2006-01-02 15:04:05 UTC")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Use: "relspec",
|
Use: "relspec",
|
||||||
Short: "RelSpec - Database schema conversion and analysis tool",
|
Short: "RelSpec - Database schema conversion and analysis tool",
|
||||||
|
|||||||
@@ -4,13 +4,16 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
)
|
)
|
||||||
|
|
||||||
var versionCmd = &cobra.Command{
|
var versionCmd = &cobra.Command{
|
||||||
Use: "version",
|
Use: "version",
|
||||||
Short: "Print version information",
|
Short: "Print version information",
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
fmt.Printf("RelSpec %s\n", version)
|
fmt.Print(buildinfo.AsciiLogo)
|
||||||
fmt.Printf("Built: %s\n", buildDate)
|
fmt.Printf("RelSpec %s\n", buildinfo.Version)
|
||||||
|
fmt.Printf("Built: %s\n", buildinfo.BuildDate)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Package buildinfo exposes the RelSpec version and build date so that both the
|
||||||
|
// CLI and the schema writers can stamp generated output with the same values.
|
||||||
|
package buildinfo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"runtime/debug"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Version and BuildDate are set via -ldflags at build time (see Makefile). When
|
||||||
|
// built without ldflags they are backfilled from the Go module build info.
|
||||||
|
var (
|
||||||
|
Version = "dev"
|
||||||
|
BuildDate = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if Version != "dev" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
info, ok := debug.ReadBuildInfo()
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rev, vcsTime string
|
||||||
|
for _, s := range info.Settings {
|
||||||
|
switch s.Key {
|
||||||
|
case "vcs.revision":
|
||||||
|
if len(s.Value) >= 7 {
|
||||||
|
rev = s.Value[:7]
|
||||||
|
}
|
||||||
|
case "vcs.time":
|
||||||
|
vcsTime = s.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rev != "" {
|
||||||
|
Version = rev
|
||||||
|
}
|
||||||
|
if t, err := time.Parse(time.RFC3339, vcsTime); err == nil {
|
||||||
|
BuildDate = t.UTC().Format("2006-01-02 15:04:05 UTC")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GeneratedComment returns the one-line provenance string embedded in generated
|
||||||
|
// files, e.g. "RelSpec dev (built: unknown)".
|
||||||
|
func GeneratedComment() string {
|
||||||
|
return fmt.Sprintf("RelSpec %s (built: %s)", Version, BuildDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
const AsciiLogo = `
|
||||||
|
██████╗ ███████╗██╗ ███████╗██████╗ ███████╗ ██████╗
|
||||||
|
██╔══██╗██╔════╝██║ ██╔════╝██╔══██╗██╔════╝██╔════╝
|
||||||
|
██████╔╝█████╗ ██║ ███████╗██████╔╝█████╗ ██║
|
||||||
|
██╔══██╗██╔══╝ ██║ ╚════██║██╔═══╝ ██╔══╝ ██║
|
||||||
|
██║ ██║███████╗███████╗███████║██║ ███████╗╚██████╗
|
||||||
|
╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚═╝ ╚══════╝ ╚═════╝
|
||||||
|
[ IN ] ──▶ [ RELSPEC ] ──▶ [ OUT ]
|
||||||
|
╔══════════════════════════════════════╗
|
||||||
|
║ ║
|
||||||
|
║ © WARKY DEVS ║
|
||||||
|
║ Author: Hein (hein@warky.dev) ║
|
||||||
|
║ ║
|
||||||
|
╚══════════════════════════════════════╝
|
||||||
|
`
|
||||||
@@ -305,9 +305,39 @@ func sortDBMLFiles(files []string) []string {
|
|||||||
// Merges: Columns (map), Constraints (map), Indexes (map), Relationships (map)
|
// Merges: Columns (map), Constraints (map), Indexes (map), Relationships (map)
|
||||||
// Uses first non-empty Description
|
// Uses first non-empty Description
|
||||||
func mergeTable(baseTable, fileTable *models.Table) {
|
func mergeTable(baseTable, fileTable *models.Table) {
|
||||||
// Merge columns (map naturally merges - later keys overwrite)
|
// Merge columns. Each file numbers its own columns from 1, so a table split
|
||||||
for key, col := range fileTable.Columns {
|
// across files would otherwise end up with colliding Column.Sequence values
|
||||||
baseTable.Columns[key] = col
|
// and writers would fall back to alphabetical order. Re-base the incoming
|
||||||
|
// file's new columns after the highest sequence already present, preserving
|
||||||
|
// their in-file order. Columns that overwrite an existing key keep the
|
||||||
|
// original position.
|
||||||
|
var maxSeq uint
|
||||||
|
for _, col := range baseTable.Columns {
|
||||||
|
if col.Sequence > maxSeq {
|
||||||
|
maxSeq = col.Sequence
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
incoming := make([]*models.Column, 0, len(fileTable.Columns))
|
||||||
|
for _, col := range fileTable.Columns {
|
||||||
|
incoming = append(incoming, col)
|
||||||
|
}
|
||||||
|
sort.Slice(incoming, func(i, j int) bool {
|
||||||
|
if incoming[i].Sequence != incoming[j].Sequence {
|
||||||
|
return incoming[i].Sequence < incoming[j].Sequence
|
||||||
|
}
|
||||||
|
return incoming[i].Name < incoming[j].Name
|
||||||
|
})
|
||||||
|
|
||||||
|
var added uint
|
||||||
|
for _, col := range incoming {
|
||||||
|
if existing, ok := baseTable.Columns[col.Name]; ok {
|
||||||
|
col.Sequence = existing.Sequence
|
||||||
|
} else {
|
||||||
|
added++
|
||||||
|
col.Sequence = maxSeq + added
|
||||||
|
}
|
||||||
|
baseTable.Columns[col.Name] = col
|
||||||
}
|
}
|
||||||
|
|
||||||
// Merge constraints
|
// Merge constraints
|
||||||
@@ -454,7 +484,7 @@ func (r *Reader) parseDBML(content string) (*models.Database, error) {
|
|||||||
// for a column declaration.
|
// for a column declaration.
|
||||||
if inTableNote {
|
if inTableNote {
|
||||||
if line == "'''" {
|
if line == "'''" {
|
||||||
currentTable.Description = strings.TrimSpace(strings.Join(tableNoteLines, "\n"))
|
setTableNote(currentTable, strings.TrimSpace(strings.Join(tableNoteLines, "\n")))
|
||||||
inTableNote = false
|
inTableNote = false
|
||||||
tableNoteLines = nil
|
tableNoteLines = nil
|
||||||
continue
|
continue
|
||||||
@@ -557,9 +587,10 @@ func (r *Reader) parseDBML(content string) (*models.Database, error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse table note
|
// Parse table note. DBML files in the wild use both `Note:` and
|
||||||
if inTable && currentTable != nil && strings.HasPrefix(line, "Note:") {
|
// `note:`, so accept either spelling.
|
||||||
note := strings.TrimPrefix(line, "Note:")
|
if inTable && currentTable != nil && strings.HasPrefix(strings.ToLower(line), "note:") {
|
||||||
|
note := strings.TrimSpace(line[len("note:"):])
|
||||||
if strings.TrimSpace(note) == "'''" {
|
if strings.TrimSpace(note) == "'''" {
|
||||||
inTableNote = true
|
inTableNote = true
|
||||||
tableNoteLines = nil
|
tableNoteLines = nil
|
||||||
@@ -567,7 +598,7 @@ func (r *Reader) parseDBML(content string) (*models.Database, error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
note = strings.Trim(note, " '\"")
|
note = strings.Trim(note, " '\"")
|
||||||
currentTable.Description = note
|
setTableNote(currentTable, note)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -654,6 +685,20 @@ func (r *Reader) parseDBML(content string) (*models.Database, error) {
|
|||||||
return db, nil
|
return db, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// setTableNote preserves multiple table notes. The first maps to Description
|
||||||
|
// and the second to Comment, matching the model fields used by code writers.
|
||||||
|
func setTableNote(table *models.Table, note string) {
|
||||||
|
if table.Description == "" {
|
||||||
|
table.Description = note
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if table.Comment == "" {
|
||||||
|
table.Comment = note
|
||||||
|
return
|
||||||
|
}
|
||||||
|
table.Comment += "\n" + note
|
||||||
|
}
|
||||||
|
|
||||||
// parseColumn parses a DBML column definition
|
// parseColumn parses a DBML column definition
|
||||||
func (r *Reader) parseColumn(line, tableName, schemaName string) (*models.Column, *models.Constraint) {
|
func (r *Reader) parseColumn(line, tableName, schemaName string) (*models.Column, *models.Constraint) {
|
||||||
// Format: column_name type [attributes] // comment
|
// Format: column_name type [attributes] // comment
|
||||||
@@ -671,7 +716,7 @@ func (r *Reader) parseColumn(line, tableName, schemaName string) (*models.Column
|
|||||||
|
|
||||||
// Parse attributes in brackets
|
// Parse attributes in brackets
|
||||||
if attrs != "" {
|
if attrs != "" {
|
||||||
attrList := strings.Split(attrs, ",")
|
attrList := splitColumnAttrs(attrs)
|
||||||
|
|
||||||
for _, attr := range attrList {
|
for _, attr := range attrList {
|
||||||
attr = strings.TrimSpace(attr)
|
attr = strings.TrimSpace(attr)
|
||||||
@@ -754,6 +799,44 @@ func (r *Reader) parseColumn(line, tableName, schemaName string) (*models.Column
|
|||||||
return column, constraint
|
return column, constraint
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// splitColumnAttrs splits a DBML attribute list on top-level commas. Notes and
|
||||||
|
// quoted defaults may contain commas of their own, which are part of the value
|
||||||
|
// rather than attribute separators.
|
||||||
|
func splitColumnAttrs(attrs string) []string {
|
||||||
|
var result []string
|
||||||
|
start := 0
|
||||||
|
var quote byte
|
||||||
|
escaped := false
|
||||||
|
|
||||||
|
for i := 0; i < len(attrs); i++ {
|
||||||
|
ch := attrs[i]
|
||||||
|
if quote != 0 {
|
||||||
|
if escaped {
|
||||||
|
escaped = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ch == '\\' {
|
||||||
|
escaped = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ch == quote {
|
||||||
|
quote = 0
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
switch ch {
|
||||||
|
case '\'', '"', '`':
|
||||||
|
quote = ch
|
||||||
|
case ',':
|
||||||
|
result = append(result, attrs[start:i])
|
||||||
|
start = i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return append(result, attrs[start:])
|
||||||
|
}
|
||||||
|
|
||||||
func splitInlineComment(line string) (content, inlineComment string) {
|
func splitInlineComment(line string) (content, inlineComment string) {
|
||||||
commentStart := strings.Index(line, "//")
|
commentStart := strings.Index(line, "//")
|
||||||
if commentStart == -1 {
|
if commentStart == -1 {
|
||||||
|
|||||||
@@ -652,6 +652,22 @@ func TestReadDirectory_TableMerging(t *testing.T) {
|
|||||||
if emailCol.Type != "varchar(255)" {
|
if emailCol.Type != "varchar(255)" {
|
||||||
t.Errorf("Expected email type 'varchar(255)', got '%s'", emailCol.Type)
|
t.Errorf("Expected email type 'varchar(255)', got '%s'", emailCol.Type)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Merged columns must keep declaration order (file 1: id, email; file 3:
|
||||||
|
// name, created_at) via strictly increasing, non-colliding Sequence values
|
||||||
|
// so downstream writers do not fall back to alphabetical order.
|
||||||
|
order := []string{"id", "email", "name", "created_at"}
|
||||||
|
var prev uint
|
||||||
|
for i, name := range order {
|
||||||
|
col := usersTable.Columns[name]
|
||||||
|
if col.Sequence == 0 {
|
||||||
|
t.Fatalf("column %q has zero Sequence after merge", name)
|
||||||
|
}
|
||||||
|
if i > 0 && col.Sequence <= prev {
|
||||||
|
t.Errorf("column %q Sequence %d not greater than previous %d (order not preserved across files)", name, col.Sequence, prev)
|
||||||
|
}
|
||||||
|
prev = col.Sequence
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReadDirectory_CommentedRefsLast(t *testing.T) {
|
func TestReadDirectory_CommentedRefsLast(t *testing.T) {
|
||||||
@@ -1037,12 +1053,13 @@ func TestReader_ColumnPKOrderPreserved(t *testing.T) {
|
|||||||
func TestReader_MultilineTableNote(t *testing.T) {
|
func TestReader_MultilineTableNote(t *testing.T) {
|
||||||
dbmlContent := "Table \"info\".\"city\" {\n" +
|
dbmlContent := "Table \"info\".\"city\" {\n" +
|
||||||
" \"id_city\" serial [pk, not null, increment]\n" +
|
" \"id_city\" serial [pk, not null, increment]\n" +
|
||||||
" \"name\" text [not null]\n\n" +
|
" \"name\" text [not null, note: 'first, second, third']\n\n" +
|
||||||
" Note: '''\n" +
|
" note: '''\n" +
|
||||||
" Cities and municipalities worldwide.\n\n" +
|
" Cities and municipalities worldwide.\n\n" +
|
||||||
" SPATIAL:\n" +
|
" SPATIAL:\n" +
|
||||||
" Proximity queries use a GiST index.\n" +
|
" Proximity queries use a GiST index.\n" +
|
||||||
" '''\n" +
|
" '''\n" +
|
||||||
|
" Note: 'Short summary'\n" +
|
||||||
"}\n"
|
"}\n"
|
||||||
path := filepath.Join(t.TempDir(), "city.dbml")
|
path := filepath.Join(t.TempDir(), "city.dbml")
|
||||||
if err := os.WriteFile(path, []byte(dbmlContent), 0o644); err != nil {
|
if err := os.WriteFile(path, []byte(dbmlContent), 0o644); err != nil {
|
||||||
@@ -1058,7 +1075,13 @@ func TestReader_MultilineTableNote(t *testing.T) {
|
|||||||
if got, want := table.Description, "Cities and municipalities worldwide.\n\nSPATIAL:\nProximity queries use a GiST index."; got != want {
|
if got, want := table.Description, "Cities and municipalities worldwide.\n\nSPATIAL:\nProximity queries use a GiST index."; got != want {
|
||||||
t.Errorf("table description = %q, want %q", got, want)
|
t.Errorf("table description = %q, want %q", got, want)
|
||||||
}
|
}
|
||||||
|
if got, want := table.Comment, "Short summary"; got != want {
|
||||||
|
t.Errorf("table comment = %q, want %q", got, want)
|
||||||
|
}
|
||||||
if got, want := len(table.Columns), 2; got != want {
|
if got, want := len(table.Columns), 2; got != want {
|
||||||
t.Errorf("column count = %d, want %d; note body must not be parsed as columns", got, want)
|
t.Errorf("column count = %d, want %d; note body must not be parsed as columns", got, want)
|
||||||
}
|
}
|
||||||
|
if got, want := table.Columns["name"].Comment, "first, second, third"; got != want {
|
||||||
|
t.Errorf("column note = %q, want %q", got, want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
||||||
)
|
)
|
||||||
@@ -13,6 +14,7 @@ import (
|
|||||||
// TemplateData represents the data passed to the template for code generation
|
// TemplateData represents the data passed to the template for code generation
|
||||||
type TemplateData struct {
|
type TemplateData struct {
|
||||||
PackageName string
|
PackageName string
|
||||||
|
GeneratedBy string
|
||||||
Imports []string
|
Imports []string
|
||||||
Models []*ModelData
|
Models []*ModelData
|
||||||
Config *MethodConfig
|
Config *MethodConfig
|
||||||
@@ -165,6 +167,7 @@ func NewTemplateData(packageName string, config *MethodConfig) *TemplateData {
|
|||||||
|
|
||||||
return &TemplateData{
|
return &TemplateData{
|
||||||
PackageName: packageName,
|
PackageName: packageName,
|
||||||
|
GeneratedBy: buildinfo.GeneratedComment(),
|
||||||
Imports: make([]string, 0),
|
Imports: make([]string, 0),
|
||||||
Models: make([]*ModelData, 0),
|
Models: make([]*ModelData, 0),
|
||||||
Config: config,
|
Config: config,
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import (
|
|||||||
|
|
||||||
// modelTemplate defines the template for generating Bun models
|
// modelTemplate defines the template for generating Bun models
|
||||||
const modelTemplate = `// Code generated by relspecgo. DO NOT EDIT.
|
const modelTemplate = `// Code generated by relspecgo. DO NOT EDIT.
|
||||||
package {{.PackageName}}
|
{{if .GeneratedBy}}// {{.GeneratedBy}}
|
||||||
|
{{end}}package {{.PackageName}}
|
||||||
|
|
||||||
{{if .Imports -}}
|
{{if .Imports -}}
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
||||||
)
|
)
|
||||||
@@ -120,6 +121,42 @@ func TestWriter_WriteTable_MultilineDescriptionProducesValidGo(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWriter_WriteTable_EmbedsRelspecVersionHeader(t *testing.T) {
|
||||||
|
table := models.InitTable("users", "public")
|
||||||
|
table.Columns["id"] = &models.Column{Name: "id", Type: "bigint", IsPrimaryKey: true, NotNull: true, Sequence: 1}
|
||||||
|
|
||||||
|
outputPath := filepath.Join(t.TempDir(), "users.go")
|
||||||
|
writer := NewWriter(&writers.WriterOptions{OutputPath: outputPath, PackageName: "models"})
|
||||||
|
if err := writer.WriteTable(table); err != nil {
|
||||||
|
t.Fatalf("WriteTable() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
generated, err := os.ReadFile(outputPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to read generated code: %v", err)
|
||||||
|
}
|
||||||
|
src := string(generated)
|
||||||
|
|
||||||
|
if _, err := parser.ParseFile(token.NewFileSet(), outputPath, generated, parser.AllErrors); err != nil {
|
||||||
|
t.Fatalf("generated code is invalid Go: %v\n%s", err, src)
|
||||||
|
}
|
||||||
|
|
||||||
|
wantHeader := "// " + buildinfo.GeneratedComment()
|
||||||
|
if !strings.Contains(src, wantHeader) {
|
||||||
|
t.Errorf("generated code missing RelSpec version header %q\n%s", wantHeader, src)
|
||||||
|
}
|
||||||
|
// The provenance comment must sit between the "Code generated" marker and the package clause.
|
||||||
|
genIdx := strings.Index(src, "// Code generated by relspecgo. DO NOT EDIT.")
|
||||||
|
hdrIdx := strings.Index(src, wantHeader)
|
||||||
|
pkgIdx := strings.Index(src, "package models")
|
||||||
|
if genIdx < 0 || hdrIdx < 0 || pkgIdx < 0 || !(genIdx < hdrIdx && hdrIdx < pkgIdx) {
|
||||||
|
t.Errorf("RelSpec version header is misplaced (gen=%d hdr=%d pkg=%d)\n%s", genIdx, hdrIdx, pkgIdx, src)
|
||||||
|
}
|
||||||
|
if !strings.Contains(wantHeader, "RelSpec ") || !strings.Contains(wantHeader, "(built: ") {
|
||||||
|
t.Errorf("version header not in expected 'RelSpec <version> (built: <date>)' form: %q", wantHeader)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestWriter_WriteDatabase_MultiFile(t *testing.T) {
|
func TestWriter_WriteDatabase_MultiFile(t *testing.T) {
|
||||||
// Create a database with two tables
|
// Create a database with two tables
|
||||||
db := models.InitDatabase("testdb")
|
db := models.InitDatabase("testdb")
|
||||||
|
|||||||
@@ -4,14 +4,16 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TemplateData represents the data passed to the template for code generation
|
// TemplateData represents the data passed to the template for code generation
|
||||||
type TemplateData struct {
|
type TemplateData struct {
|
||||||
Imports []string
|
GeneratedBy string
|
||||||
Enums []*EnumData
|
Imports []string
|
||||||
Tables []*TableData
|
Enums []*EnumData
|
||||||
|
Tables []*TableData
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnumData represents an enum in the schema
|
// EnumData represents an enum in the schema
|
||||||
@@ -59,9 +61,10 @@ type IndexData struct {
|
|||||||
// NewTemplateData creates a new TemplateData
|
// NewTemplateData creates a new TemplateData
|
||||||
func NewTemplateData() *TemplateData {
|
func NewTemplateData() *TemplateData {
|
||||||
return &TemplateData{
|
return &TemplateData{
|
||||||
Imports: make([]string, 0),
|
GeneratedBy: buildinfo.GeneratedComment(),
|
||||||
Enums: make([]*EnumData, 0),
|
Imports: make([]string, 0),
|
||||||
Tables: make([]*TableData, 0),
|
Enums: make([]*EnumData, 0),
|
||||||
|
Tables: make([]*TableData, 0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import (
|
|||||||
|
|
||||||
// schemaTemplate defines the template for generating Drizzle schemas
|
// schemaTemplate defines the template for generating Drizzle schemas
|
||||||
const schemaTemplate = `// Code generated by relspecgo. DO NOT EDIT.
|
const schemaTemplate = `// Code generated by relspecgo. DO NOT EDIT.
|
||||||
{{range .Imports}}{{.}}
|
{{if .GeneratedBy}}// {{.GeneratedBy}}
|
||||||
|
{{end}}{{range .Imports}}{{.}}
|
||||||
{{end}}
|
{{end}}
|
||||||
{{if .Enums}}
|
{{if .Enums}}
|
||||||
// Enums
|
// Enums
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
||||||
)
|
)
|
||||||
@@ -11,6 +12,7 @@ import (
|
|||||||
// TemplateData represents the data passed to the template for code generation
|
// TemplateData represents the data passed to the template for code generation
|
||||||
type TemplateData struct {
|
type TemplateData struct {
|
||||||
PackageName string
|
PackageName string
|
||||||
|
GeneratedBy string
|
||||||
Imports []string
|
Imports []string
|
||||||
Models []*ModelData
|
Models []*ModelData
|
||||||
Config *MethodConfig
|
Config *MethodConfig
|
||||||
@@ -79,6 +81,7 @@ func NewTemplateData(packageName string, config *MethodConfig) *TemplateData {
|
|||||||
|
|
||||||
return &TemplateData{
|
return &TemplateData{
|
||||||
PackageName: packageName,
|
PackageName: packageName,
|
||||||
|
GeneratedBy: buildinfo.GeneratedComment(),
|
||||||
Imports: make([]string, 0),
|
Imports: make([]string, 0),
|
||||||
Models: make([]*ModelData, 0),
|
Models: make([]*ModelData, 0),
|
||||||
Config: config,
|
Config: config,
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import (
|
|||||||
|
|
||||||
// modelTemplate defines the template for generating GORM models
|
// modelTemplate defines the template for generating GORM models
|
||||||
const modelTemplate = `// Code generated by relspecgo. DO NOT EDIT.
|
const modelTemplate = `// Code generated by relspecgo. DO NOT EDIT.
|
||||||
package {{.PackageName}}
|
{{if .GeneratedBy}}// {{.GeneratedBy}}
|
||||||
|
{{end}}package {{.PackageName}}
|
||||||
|
|
||||||
{{if .Imports -}}
|
{{if .Imports -}}
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -112,6 +112,46 @@ func TestWriter_WriteTable_MultilineDescriptionProducesValidGo(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWriter_WriteTable_ColumnOrderFollowsSequence(t *testing.T) {
|
||||||
|
// Column.Sequence carries the source (e.g. DBML) declaration order; the
|
||||||
|
// generated struct fields must follow it, not fall back to alphabetical.
|
||||||
|
table := models.InitTable("widget", "public")
|
||||||
|
table.Columns["zeta"] = &models.Column{Name: "zeta", Type: "varchar", Length: 50, Sequence: 1}
|
||||||
|
table.Columns["alpha"] = &models.Column{Name: "alpha", Type: "bigint", NotNull: true, IsPrimaryKey: true, AutoIncrement: true, Sequence: 2}
|
||||||
|
table.Columns["mid_field"] = &models.Column{Name: "mid_field", Type: "integer", Sequence: 3}
|
||||||
|
table.Columns["beta"] = &models.Column{Name: "beta", Type: "varchar", Length: 100, Sequence: 4}
|
||||||
|
|
||||||
|
outputPath := filepath.Join(t.TempDir(), "widget.go")
|
||||||
|
writer := NewWriter(&writers.WriterOptions{OutputPath: outputPath, PackageName: "models"})
|
||||||
|
if err := writer.WriteTable(table); err != nil {
|
||||||
|
t.Fatalf("WriteTable() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
generated, err := os.ReadFile(outputPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to read generated code: %v", err)
|
||||||
|
}
|
||||||
|
src := string(generated)
|
||||||
|
if _, err := parser.ParseFile(token.NewFileSet(), outputPath, generated, parser.AllErrors); err != nil {
|
||||||
|
t.Fatalf("generated code is invalid Go: %v\n%s", err, src)
|
||||||
|
}
|
||||||
|
|
||||||
|
positions := make([]int, 0, 4)
|
||||||
|
for _, field := range []string{"Zeta ", "Alpha ", "MidField ", "Beta "} {
|
||||||
|
idx := strings.Index(src, "\t"+field)
|
||||||
|
if idx < 0 {
|
||||||
|
t.Fatalf("field %q missing from generated struct:\n%s", field, src)
|
||||||
|
}
|
||||||
|
positions = append(positions, idx)
|
||||||
|
}
|
||||||
|
for i := 1; i < len(positions); i++ {
|
||||||
|
if positions[i] <= positions[i-1] {
|
||||||
|
t.Errorf("struct fields not in Sequence order (want zeta, alpha, mid_field, beta):\n%s", src)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestWriter_WriteDatabase_MultiFile(t *testing.T) {
|
func TestWriter_WriteDatabase_MultiFile(t *testing.T) {
|
||||||
// Create a database with two tables
|
// Create a database with two tables
|
||||||
db := models.InitDatabase("testdb")
|
db := models.InitDatabase("testdb")
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
_ "github.com/microsoft/go-mssqldb" // MSSQL driver
|
_ "github.com/microsoft/go-mssqldb" // MSSQL driver
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/mssql"
|
"git.warky.dev/wdevs/relspecgo/pkg/mssql"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
||||||
@@ -68,7 +69,7 @@ func (w *Writer) WriteDatabase(db *models.Database) error {
|
|||||||
// Write header comment
|
// Write header comment
|
||||||
fmt.Fprintf(w.writer, "-- MSSQL Database Schema\n")
|
fmt.Fprintf(w.writer, "-- MSSQL Database Schema\n")
|
||||||
fmt.Fprintf(w.writer, "-- Database: %s\n", db.Name)
|
fmt.Fprintf(w.writer, "-- Database: %s\n", db.Name)
|
||||||
fmt.Fprintf(w.writer, "-- Generated by RelSpec\n\n")
|
fmt.Fprintf(w.writer, "-- Generated by %s\n\n", buildinfo.GeneratedComment())
|
||||||
|
|
||||||
// Process each schema in the database
|
// Process each schema in the database
|
||||||
for _, schema := range db.Schemas {
|
for _, schema := range db.Schemas {
|
||||||
@@ -477,7 +478,7 @@ func (w *Writer) executeDatabaseSQL(db *models.Database, connString string) erro
|
|||||||
statements := []string{}
|
statements := []string{}
|
||||||
statements = append(statements, "-- MSSQL Database Schema")
|
statements = append(statements, "-- MSSQL Database Schema")
|
||||||
statements = append(statements, fmt.Sprintf("-- Database: %s", db.Name))
|
statements = append(statements, fmt.Sprintf("-- Database: %s", db.Name))
|
||||||
statements = append(statements, "-- Generated by RelSpec")
|
statements = append(statements, "-- Generated by "+buildinfo.GeneratedComment())
|
||||||
|
|
||||||
for _, schema := range db.Schemas {
|
for _, schema := range db.Schemas {
|
||||||
if err := w.generateSchemaStatements(schema, &statements); err != nil {
|
if err := w.generateSchemaStatements(schema, &statements); err != nil {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/pgsql"
|
"git.warky.dev/wdevs/relspecgo/pkg/pgsql"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
||||||
@@ -143,7 +144,7 @@ func (w *MigrationWriter) WriteMigration(model, current *models.Database) error
|
|||||||
|
|
||||||
// Write header
|
// Write header
|
||||||
fmt.Fprintf(w.writer, "-- PostgreSQL Migration Script\n")
|
fmt.Fprintf(w.writer, "-- PostgreSQL Migration Script\n")
|
||||||
fmt.Fprintf(w.writer, "-- Generated by RelSpec\n")
|
fmt.Fprintf(w.writer, "-- Generated by %s\n", buildinfo.GeneratedComment())
|
||||||
fmt.Fprintf(w.writer, "-- Source: %s -> %s\n", current.Name, model.Name)
|
fmt.Fprintf(w.writer, "-- Source: %s -> %s\n", current.Name, model.Name)
|
||||||
if w.options.ContinueOnError {
|
if w.options.ContinueOnError {
|
||||||
fmt.Fprintf(w.writer, "\\set ON_ERROR_STOP off\n")
|
fmt.Fprintf(w.writer, "\\set ON_ERROR_STOP off\n")
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/pgsql"
|
"git.warky.dev/wdevs/relspecgo/pkg/pgsql"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
||||||
@@ -101,7 +102,7 @@ func (w *Writer) WriteDatabase(db *models.Database) error {
|
|||||||
// Write header comment
|
// Write header comment
|
||||||
fmt.Fprintf(w.writer, "-- PostgreSQL Database Schema\n")
|
fmt.Fprintf(w.writer, "-- PostgreSQL Database Schema\n")
|
||||||
fmt.Fprintf(w.writer, "-- Database: %s\n", db.Name)
|
fmt.Fprintf(w.writer, "-- Database: %s\n", db.Name)
|
||||||
fmt.Fprintf(w.writer, "-- Generated by RelSpec\n")
|
fmt.Fprintf(w.writer, "-- Generated by %s\n", buildinfo.GeneratedComment())
|
||||||
if w.options.ContinueOnError {
|
if w.options.ContinueOnError {
|
||||||
fmt.Fprintf(w.writer, "\\set ON_ERROR_STOP off\n")
|
fmt.Fprintf(w.writer, "\\set ON_ERROR_STOP off\n")
|
||||||
}
|
}
|
||||||
@@ -125,7 +126,7 @@ func (w *Writer) GenerateDatabaseStatements(db *models.Database) ([]string, erro
|
|||||||
// Add header comment
|
// Add header comment
|
||||||
statements = append(statements, "-- PostgreSQL Database Schema")
|
statements = append(statements, "-- PostgreSQL Database Schema")
|
||||||
statements = append(statements, fmt.Sprintf("-- Database: %s", db.Name))
|
statements = append(statements, fmt.Sprintf("-- Database: %s", db.Name))
|
||||||
statements = append(statements, "-- Generated by RelSpec")
|
statements = append(statements, "-- Generated by "+buildinfo.GeneratedComment())
|
||||||
|
|
||||||
// Process each schema in the database
|
// Process each schema in the database
|
||||||
for _, schema := range db.Schemas {
|
for _, schema := range db.Schemas {
|
||||||
@@ -555,7 +556,7 @@ func (w *Writer) GenerateAddColumnsForDatabase(db *models.Database) ([]string, e
|
|||||||
|
|
||||||
statements = append(statements, "-- Add missing columns to existing tables")
|
statements = append(statements, "-- Add missing columns to existing tables")
|
||||||
statements = append(statements, fmt.Sprintf("-- Database: %s", db.Name))
|
statements = append(statements, fmt.Sprintf("-- Database: %s", db.Name))
|
||||||
statements = append(statements, "-- Generated by RelSpec")
|
statements = append(statements, "-- Generated by "+buildinfo.GeneratedComment())
|
||||||
|
|
||||||
for _, schema := range db.Schemas {
|
for _, schema := range db.Schemas {
|
||||||
schemaStatements, err := w.GenerateAddColumnStatements(schema)
|
schemaStatements, err := w.GenerateAddColumnStatements(schema)
|
||||||
@@ -1446,19 +1447,10 @@ func (w *Writer) writeComments(schema *models.Schema) error {
|
|||||||
|
|
||||||
// Helper functions
|
// Helper functions
|
||||||
|
|
||||||
// getSortedColumns returns columns sorted by name
|
// getSortedColumns returns columns sorted by Sequence then Name, preserving the
|
||||||
|
// original column order from the source schema for deterministic output.
|
||||||
func getSortedColumns(columns map[string]*models.Column) []*models.Column {
|
func getSortedColumns(columns map[string]*models.Column) []*models.Column {
|
||||||
names := make([]string, 0, len(columns))
|
return sortColumns(columns)
|
||||||
for name := range columns {
|
|
||||||
names = append(names, name)
|
|
||||||
}
|
|
||||||
sort.Strings(names)
|
|
||||||
|
|
||||||
sorted := make([]*models.Column, 0, len(columns))
|
|
||||||
for _, name := range names {
|
|
||||||
sorted = append(sorted, columns[name])
|
|
||||||
}
|
|
||||||
return sorted
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// isIntegerType checks if a column type is an integer type
|
// isIntegerType checks if a column type is an integer type
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
|
|
||||||
_ "modernc.org/sqlite" // SQLite driver
|
_ "modernc.org/sqlite" // SQLite driver
|
||||||
|
|
||||||
|
"git.warky.dev/wdevs/relspecgo/pkg/buildinfo"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
"git.warky.dev/wdevs/relspecgo/pkg/models"
|
||||||
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
"git.warky.dev/wdevs/relspecgo/pkg/writers"
|
||||||
)
|
)
|
||||||
@@ -72,7 +73,7 @@ func (w *Writer) writeContent(db *models.Database) error {
|
|||||||
// Write header comment
|
// Write header comment
|
||||||
fmt.Fprintf(w.writer, "-- SQLite Database Schema\n")
|
fmt.Fprintf(w.writer, "-- SQLite Database Schema\n")
|
||||||
fmt.Fprintf(w.writer, "-- Database: %s\n", db.Name)
|
fmt.Fprintf(w.writer, "-- Database: %s\n", db.Name)
|
||||||
fmt.Fprintf(w.writer, "-- Generated by RelSpec\n")
|
fmt.Fprintf(w.writer, "-- Generated by %s\n", buildinfo.GeneratedComment())
|
||||||
fmt.Fprintf(w.writer, "-- Note: SQLite has no schema concept; non-default schema names are flattened into table name prefixes (e.g., auth.sessions -> auth_sessions)\n\n")
|
fmt.Fprintf(w.writer, "-- Note: SQLite has no schema concept; non-default schema names are flattened into table name prefixes (e.g., auth.sessions -> auth_sessions)\n\n")
|
||||||
|
|
||||||
// Enable foreign keys
|
// Enable foreign keys
|
||||||
|
|||||||
Reference in New Issue
Block a user