gorm

package
v1.0.30 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 5, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

GORM Writer

Generates Go source files with GORM model definitions from database schema information.

Overview

The GORM Writer converts RelSpec's internal database model representation into Go source code with GORM struct definitions, complete with proper tags, relationships, and methods.

Features

  • Generates GORM-compatible Go structs
  • Creates proper gorm struct tags
  • Generates TableName() methods
  • Adds relationship fields (belongs-to, has-many)
  • Supports both single-file and multi-file output
  • Auto-generates helper methods (optional)
  • Maps SQL types to Go types
  • Handles nullable fields with custom sql_types

Usage

Basic Example
package main

import (
    "git.warky.dev/wdevs/relspecgo/pkg/models"
    "git.warky.dev/wdevs/relspecgo/pkg/writers"
    "git.warky.dev/wdevs/relspecgo/pkg/writers/gorm"
)

func main() {
    // Assume db is a *models.Database from a reader
    options := &writers.WriterOptions{
        OutputPath:  "models.go",
        PackageName: "models",
    }

    writer := gorm.NewWriter(options)
    err := writer.WriteDatabase(db)
    if err != nil {
        panic(err)
    }
}
CLI Examples
# Generate GORM models from PostgreSQL database (single file)
relspec --input pgsql \
  --conn "postgres://localhost/mydb" \
  --output gorm \
  --out-file models.go \
  --package models

# Generate GORM models with multi-file output (one file per table)
relspec --input json \
  --in-file schema.json \
  --output gorm \
  --out-file models/ \
  --package models

# Convert DBML to GORM models
relspec --input dbml --in-file schema.dbml --output gorm --out-file models.go

Output Modes

Single File Mode

Generates all models in one file:

relspec --input pgsql --conn "..." --output gorm --out-file models.go
Multi-File Mode

Generates one file per table (auto-detected when output is a directory):

relspec --input pgsql --conn "..." --output gorm --out-file models/

Files are named: sql_{schema}_{table}.go

Generated Code Example

package models

import (
    "time"
    sql_types "git.warky.dev/wdevs/sql_types"
)

type ModelUser struct {
    ID        int64                `gorm:"column:id;type:bigint;primaryKey;autoIncrement" json:"id"`
    Username  string               `gorm:"column:username;type:varchar(50);not null;uniqueIndex" json:"username"`
    Email     string               `gorm:"column:email;type:varchar(100);not null" json:"email"`
    CreatedAt time.Time            `gorm:"column:created_at;type:timestamp;not null;default:now()" json:"created_at"`

    // Relationships
    Pos []*ModelPost `gorm:"foreignKey:UserID;references:ID;constraint:OnDelete:CASCADE" json:"pos,omitempty"`
}

func (ModelUser) TableName() string {
    return "public.users"
}

type ModelPost struct {
    ID        int64           `gorm:"column:id;type:bigint;primaryKey" json:"id"`
    UserID    int64           `gorm:"column:user_id;type:bigint;not null" json:"user_id"`
    Title     string          `gorm:"column:title;type:varchar(200);not null" json:"title"`
    Content   sql_types.SqlString `gorm:"column:content;type:text" json:"content,omitempty"`

    // Belongs to
    Use *ModelUser `gorm:"foreignKey:UserID;references:ID" json:"use,omitempty"`
}

func (ModelPost) TableName() string {
    return "public.posts"
}

Writer Options

Metadata Options

Configure the writer behavior using metadata in WriterOptions:

options := &writers.WriterOptions{
    OutputPath:  "models.go",
    PackageName: "models",
    Metadata: map[string]interface{}{
        "multi_file":      true,  // Enable multi-file mode
        "populate_refs":   true,  // Populate RefDatabase/RefSchema
        "generate_get_id_str": true, // Generate GetIDStr() methods
    },
}

Type Mapping

SQL Type Go Type Notes
bigint, int8 int64 -
integer, int, int4 int -
smallint, int2 int16 -
varchar, text string Not nullable
varchar, text (nullable) sql_types.SqlString Nullable
boolean, bool bool -
timestamp, timestamptz time.Time -
numeric, decimal float64 -
uuid string -
json, jsonb string -

Relationship Generation

The writer automatically generates relationship fields:

  • Belongs-to: Generated for tables with foreign keys
  • Has-many: Generated for tables referenced by foreign keys
  • Relationship field names use 3-letter prefixes
  • Includes proper gorm tags with foreignKey and references

Notes

  • Model names are prefixed with "Model" (e.g., ModelUser)
  • Nullable columns use sql_types.SqlString, sql_types.SqlInt64, etc.
  • Generated code is auto-formatted with go fmt
  • JSON tags are automatically added
  • Supports schema-qualified table names in TableName() method

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GeneratePrefix

func GeneratePrefix(tableName string) string

GeneratePrefix generates a 3-letter prefix from a table name Examples: process → PRO, mastertask → MTL, user → USR

func PascalCaseToSnakeCase

func PascalCaseToSnakeCase(s string) string

PascalCaseToSnakeCase converts PascalCase to snake_case Examples: UserID → user_id, HTTPRequest → http_request

func Pluralize

func Pluralize(s string) string

Pluralize converts a singular word to plural Basic implementation with common rules

func Singularize

func Singularize(s string) string

Singularize converts a plural word to singular Basic implementation with common rules

func SnakeCaseToCamelCase

func SnakeCaseToCamelCase(s string) string

SnakeCaseToCamelCase converts snake_case to camelCase Examples: user_id → userID, http_request → httpRequest

func SnakeCaseToPascalCase

func SnakeCaseToPascalCase(s string) string

SnakeCaseToPascalCase converts snake_case to PascalCase Examples: user_id → UserID, http_request → HTTPRequest

Types

type FieldData

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
}

FieldData represents a single field in a struct

type MethodConfig

type MethodConfig struct {
	GenerateTableName     bool
	GenerateSchemaName    bool
	GenerateTableNameOnly bool
	GenerateGetID         bool
	GenerateGetIDStr      bool
	GenerateSetID         bool
	GenerateUpdateID      bool
	GenerateGetIDName     bool
	GenerateGetPrefix     bool
}

MethodConfig controls which helper methods to generate

func DefaultMethodConfig

func DefaultMethodConfig() *MethodConfig

DefaultMethodConfig returns a MethodConfig with all methods enabled

func LoadMethodConfigFromMetadata

func LoadMethodConfigFromMetadata(metadata map[string]interface{}) *MethodConfig

LoadMethodConfigFromMetadata loads method configuration from metadata map

type ModelData

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
	PrimaryKeyType  string // Go type of the primary key field
	IDColumnName    string // Name of the ID column in database
	Prefix          string // 3-letter prefix
}

ModelData represents a single model/struct in the template

func NewModelData

func NewModelData(table *models.Table, schema string, typeMapper *TypeMapper, flattenSchema bool) *ModelData

NewModelData creates a new ModelData from a models.Table

func (*ModelData) AddRelationshipField

func (md *ModelData) AddRelationshipField(field *FieldData)

AddRelationshipField adds a relationship field to the model

type TemplateData

type TemplateData struct {
	PackageName string
	Imports     []string
	Models      []*ModelData
	Config      *MethodConfig
}

TemplateData represents the data passed to the template for code generation

func NewTemplateData

func NewTemplateData(packageName string, config *MethodConfig) *TemplateData

NewTemplateData creates a new TemplateData with the given package name and config

func (*TemplateData) AddImport

func (td *TemplateData) AddImport(importPath string)

AddImport adds an import to the template data (deduplicates automatically)

func (*TemplateData) AddModel

func (td *TemplateData) AddModel(model *ModelData)

AddModel adds a model to the template data

func (*TemplateData) FinalizeImports

func (td *TemplateData) FinalizeImports()

FinalizeImports sorts and organizes imports

type Templates

type Templates struct {
	// contains filtered or unexported fields
}

Templates holds the parsed templates

func NewTemplates

func NewTemplates() (*Templates, error)

NewTemplates creates and parses the templates

func (*Templates) GenerateCode

func (t *Templates) GenerateCode(data *TemplateData) (string, error)

GenerateCode executes the template with the given data

type TypeMapper

type TypeMapper struct {
	// contains filtered or unexported fields
}

TypeMapper handles type conversions between SQL and Go types

func NewTypeMapper

func NewTypeMapper() *TypeMapper

NewTypeMapper creates a new TypeMapper with default settings

func (*TypeMapper) BuildGormTag

func (tm *TypeMapper) BuildGormTag(column *models.Column, table *models.Table) string

BuildGormTag generates a complete GORM tag string for a column

func (*TypeMapper) BuildRelationshipTag

func (tm *TypeMapper) BuildRelationshipTag(constraint *models.Constraint, isParent bool) string

BuildRelationshipTag generates GORM tag for relationship fields

func (*TypeMapper) GetSQLTypesImport

func (tm *TypeMapper) GetSQLTypesImport() string

GetSQLTypesImport returns the import path for sql_types

func (*TypeMapper) NeedsFmtImport

func (tm *TypeMapper) NeedsFmtImport(generateGetIDStr bool) bool

NeedsFmtImport checks if we need fmt import (for GetIDStr method)

func (*TypeMapper) NeedsTimeImport

func (tm *TypeMapper) NeedsTimeImport(goType string) bool

NeedsTimeImport checks if the Go type requires time package import

func (*TypeMapper) SQLTypeToGoType

func (tm *TypeMapper) SQLTypeToGoType(sqlType string, notNull bool) string

SQLTypeToGoType converts a SQL type to its Go equivalent Handles nullable types using ResolveSpec sql_types package

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer implements the writers.Writer interface for GORM models

func NewWriter

func NewWriter(options *writers.WriterOptions) *Writer

NewWriter creates a new GORM writer with the given options

func (*Writer) WriteDatabase

func (w *Writer) WriteDatabase(db *models.Database) error

WriteDatabase writes a complete database as GORM models

func (*Writer) WriteSchema

func (w *Writer) WriteSchema(schema *models.Schema) error

WriteSchema writes a schema as GORM models

func (*Writer) WriteTable

func (w *Writer) WriteTable(table *models.Table) error

WriteTable writes a single table as a GORM model

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL