gormcngen

package module
v1.0.50 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 29 Imported by: 0

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

gormcngen

gormcngen: Provides a Columns() Function to Retrieve Column Names from GORM Models

Like MyBatis Plus in the Java ecosystem, which allows developers to get column names using expressions like Example::getName.

Like SQLAlchemy in the Python ecosystem, which allows developers to access column names using a class function, like Example.name.

gormcngen also brings type-safe column referencing to Go models.


Ecosystem

GORM Type-Safe Ecosystem


CHINESE README

中文说明


Language Ecosystem Comparison

Language ORM Type-Safe Columns Example
Java MyBatis Plus Example::getName wrapper.eq(Example::getName, "alice")
Python SQLAlchemy Example.name query.filter(Example.name == "alice")
Go GORMCNGEN cls.Name.Eq() db.Where(cls.Name.Eq("alice"))

Installation

go get github.com/yyle88/gormcngen

Important Note

gormcngen is a Go package, not a CLI application. It requires a test-code-driven generation workflow.

Quick Start

1. Create Project Structure

Set up the basic project structure and create dedicated DIR to hold models and generated code:

# Create models DIR
mkdir -p internal/models
2. Define GORM Models

Define data models - gormcngen generates column access methods from these models:

Create internal/models/models.go:

package models

type Account struct {
    ID       uint   `gorm:"primaryKey"`
    Username string `gorm:"uniqueIndex;size:100"`
    Mailbox  string `gorm:"index;size:255"`
    Age      int    `gorm:"column:age"`
    IsActive bool   `gorm:"default:true"`
}
3. Create Generation Files

Create the target file to hold generated code and the test file containing generation logic:

# Create target file to hold generated code with package declaration
echo "package models" > internal/models/ngen.go

# Create test file containing generation logic with package declaration
echo "package models" > internal/models/ngen_test.go
4. Write Generation Logic

Write the code generation logic in the test file, configure generation options and set the models to process.

Note: In Go, using test files to generate source code is a common practice.

Create internal/models/ngen_test.go:

package models

import (
    "testing"

    "github.com/yyle88/gormcngen"
    "github.com/yyle88/osexistpath/osmustexist"
    "github.com/yyle88/runpath/runtestpath"
)

//go:generate go test -run ^TestGenerate$ -tags=gormcngen_generate
func TestGenerate(t *testing.T) {
    // Get absolute path to target file (ngen.go)
    absPath := osmustexist.FILE(runtestpath.SrcPath(t))
    t.Log(absPath)

    // Configure generation options
    options := gormcngen.NewOptions().
        WithColumnClassExportable(true).
        WithColumnsMethodRecvName("c").
        WithColumnsCheckFieldType(true)

    // Define models to process
    models := []interface{}{
		&Account{},
	}

    // Create config and generate
    cfg := gormcngen.NewConfigs(models, options, absPath)
    cfg.WithIsGenPreventEdit(true)  // Add "DO NOT EDIT" warning headers (default: true)
    cfg.WithGeneratedFromPos(gormcngen.GetGenPosFuncMark(0))  // Show generation source location (default: show)
    cfg.WithGoBuildDirective(gormcngen.DirectiveSkipGenerate)  // Add build directive to solve regeneration problem
    cfg.Gen()
}
5. Execute Generation

Run the test to initiate code generation - the generated code gets auto written to the target file:

# Clean up dependencies
go mod tidy

# Run generation test
cd internal/models
go test -v ./...

🎉 Generation Complete! The ngen.go file now contains the generated column access methods.

The generated ngen.go contains:

// Code generated using gormcngen. DO NOT EDIT.
// This file was auto generated via github.com/yyle88/gormcngen

//go:build !gormcngen_generate

// Generated from: ngen_test.go:20 -> models.TestGenerate
// ========== GORMCNGEN:DO-NOT-EDIT-MARKER:END ==========

func (c *Account) Columns() *AccountColumns {
    return &AccountColumns{
        ID:       gormcnm.Cnm(c.ID, "id"),
        Username: gormcnm.Cnm(c.Username, "username"),
        Mailbox:  gormcnm.Cnm(c.Mailbox, "mailbox"),
        Age:      gormcnm.Cnm(c.Age, "age"),
        IsActive: gormcnm.Cnm(c.IsActive, "is_active"),
    }
}

type AccountColumns struct {
    gormcnm.ColumnOperationClass
    ID       gormcnm.ColumnName[uint]
    Username gormcnm.ColumnName[string]
    Mailbox  gormcnm.ColumnName[string]
    Age      gormcnm.ColumnName[int]
    IsActive gormcnm.ColumnName[bool]
}

🚀 Setup Complete! You now have type-safe column access methods to work with models.

6. Use in Business Logic

Now when writing business code, you can use the generated type-safe column methods to build database queries:

var account Account
cls := account.Columns()

// Perfect type protection with zero boilerplate
err := db.Where(cls.Username.Eq("alice")).
         Where(cls.Age.Gte(18)).
         Where(cls.IsActive.Eq(true)).
         First(&account).Error
Advanced Usage
// Basic configuration (matches internal examples)
options := gormcngen.NewOptions().
    WithColumnClassExportable(true).           // Generate exported ExampleColumns struct
    WithEmbedColumnOperations(false)           // Don't embed operation methods

// Chinese field name support
chineseOptions := gormcngen.NewOptions().
    WithUseTagName(true).                      // Use cnm tag values as field names
    WithTagKeyName("cnm").                     // Set 'cnm' as the tag name
    WithColumnClassExportable(true)

// Advanced features (from example6)
advancedOptions := gormcngen.NewOptions().
    WithColumnClassExportable(true).           // Exported struct names
    WithColumnsMethodRecvName("one").          // Custom method argument
    WithColumnsCheckFieldType(true).           // Type checking (recommended)
    WithIsGenFuncTableColumns(true)            // Generate TableColumns function

// Batch processing multiple models
allModels := []interface{}{&Account{}, &Product{}, &Item{}, &Client{}}
configs := gormcngen.NewConfigs(allModels, options, "models_gen.go")
configs.WithIsGenPreventEdit(true)  // Add "DO NOT EDIT" headers to generated files
configs.WithGeneratedFromPos(gormcngen.GetGenPosFuncMark(0))  // Show generation source location (default: show)
configs.WithGoBuildDirective(gormcngen.DirectiveSkipGenerate)  // Add build directive (recommended)
configs.Gen()

Build Directive (Solving Regeneration Problem)

When GORM models change (e.g., a field is deleted/renamed), the generated code in ngen.go continues referencing the old field, causing compilation issues. This creates a "chicken and egg" situation: you can not run TestGenerate to regenerate the code because the project does not compile.

The Solution

WithGoBuildDirective(gormcngen.DirectiveSkipGenerate) adds a build constraint to the generated file:

//go:build !gormcngen_generate

This tells Go:

  • Standard build (go build ./...): The generated file compiles fine
  • Regeneration (go test -tags=gormcngen_generate): The generated file is skipped, allowing TestGenerate to run and regenerate the code
Usage

In the test file:

//go:generate go test -run ^TestGenerate$ -tags=gormcngen_generate
func TestGenerate(t *testing.T) {
    // ... configuration ...
    cfg := gormcngen.NewConfigs(models, options, absPath)
    cfg.WithGoBuildDirective(gormcngen.DirectiveSkipGenerate)  // Add this line
    cfg.Gen()
}

When schema changes cause compilation issues:

# This skips the outdated generated file and regenerates it
go generate ./...
# Same as:
go test -run ^TestGenerate$ -tags=gormcngen_generate
Recommendation

Each example in this project uses WithGoBuildDirective. Though not required, we recommend adding it to avoid getting stuck when models change.


Advanced Features

Multi-Language Field Support

The cnm tag lets you define Chinese aliases to use as field names, which are generated as extra struct fields:

type Product struct {
    ID          uint          `gorm:"primaryKey"`
    Name        string        `gorm:"size:255;not null" cnm:"V产品名称"`
    Price       decimal.Decimal `gorm:"type:decimal(10,2)"`
    CategoryID  uint          `gorm:"index"`
    CreatedAt   time.Time     `gorm:"autoCreateTime"`
    UpdatedAt   time.Time     `gorm:"autoUpdateTime"`
}

Generated Result:

type ProductColumns struct {
    gormcnm.ColumnOperationClass
    // The column names and types of the model's columns
    ID       gormcnm.ColumnName[uint]
    Name     gormcnm.ColumnName[string]           // Maps to "name"
    V产品名称   gormcnm.ColumnName[string]           // Chinese alias mapping to Name field
    Price    gormcnm.ColumnName[decimal.Decimal]
    CategoryID gormcnm.ColumnName[uint]
    CreatedAt gormcnm.ColumnName[time.Time]
    UpdatedAt gormcnm.ColumnName[time.Time]
}

func (*Product) Columns() *ProductColumns {
    return &ProductColumns{
        ID:       "id",
        Name:     "name",
        V产品名称:   "name",      // Chinese alias pointing to same column
        Price:    "price",
        CategoryID: "category_id",
        CreatedAt: "created_at",
        UpdatedAt: "updated_at",
    }
}

Using Chinese Field Names in Queries:

With the generated Chinese aliases, you can write queries using native language:

var product Product
var cls = product.Columns()

// Query using Chinese field names - same database column, different Go field name
if err := db.Where(cls.V产品名称.Eq("iPhone")).
    Where(cls.Price.Gte(5000.00)).
    First(&product).Error; err != nil {
    panic(errors.WithMessage(err, "product not found"))
}

fmt.Println("Found product:", product.Name)

This allows developers to write more readable code in native language while maintaining complete type protection and database support.

Go Generate Integration

Create a generation script:

scripts/generate_columns.go:

package main

import (
    "github.com/yyle88/gormcngen"
    "project-name/models"
)

func main() {
    models := []interface{}{&models.Account{}}
    options := gormcngen.NewOptions()
    configs := gormcngen.NewConfigs(models, options, "models/account_columns_gen.go")
    configs.WithGoBuildDirective(gormcngen.DirectiveSkipGenerate)
    configs.Gen()
}

Then use in the target files:

//go:generate go run scripts/generate_columns.go

type Account struct {
    ID       uint   `gorm:"primaryKey"`
    Username string `gorm:"uniqueIndex"`
    Mailbox  string `gorm:"index"`
}

🔗 Using with gormrepo

Combine gormcngen with gormrepo to get type-safe CRUD operations.

Quick Preview
// Create repo with columns
repo := gormrepo.NewRepo(&Account{}, (&Account{}).Columns())

// Concise approach with gormrepo/gormclass
repo := gormrepo.NewRepo(gormclass.Use(&Account{}))

// Type-safe queries
account, err := repo.With(ctx, db).First(func(db *gorm.DB, cls *AccountColumns) *gorm.DB {
    return db.Where(cls.Username.Eq("alice"))
})

// Find with conditions
accounts, err := repo.With(ctx, db).Find(func(db *gorm.DB, cls *AccountColumns) *gorm.DB {
    return db.Where(cls.Age.Gte(18)).Where(cls.Age.Lte(65))
})

// Type-safe updates
err := repo.With(ctx, db).Updates(
    func(db *gorm.DB, cls *AccountColumns) *gorm.DB {
        return db.Where(cls.ID.Eq(1))
    },
    func(cls *AccountColumns) map[string]interface{} {
        return cls.Kw(cls.Age.Kv(26)).Kw(cls.Nickname.Kv("NewNick")).AsMap()
    },
)

👉 See gormrepo to get complete documentation and more examples.


Examples

See examples and demos directories.

Explore the complete GORM ecosystem with these integrated packages:

Core Ecosystem
  • gormcnm - GORM foundation providing type-safe columns and condition builders
  • gormcngen - Code generation using AST enabling type-safe GORM operations (this project)
  • gormrepo - Repo pattern implementation with GORM best practices
  • gormmom - Native language GORM tag generation engine with smart column naming
  • gormzhcn - Complete Chinese programming interface with GORM

Each package targets different aspects of GORM development, from localization to type protection and code generation.


📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
  • 💡 Fresh ideas? Create an issue to discuss
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


📈 GitHub Stars

starring

Documentation

Overview

Package gormcngen provides constants used in GORM code generation

gormcngen 提供 GORM 代码生成中使用的常量

Package gormcngen: Intelligent GORM code generation engine with AST-grade precision Auto generates type-safe column structs and Columns() methods from GORM models Supports complex scenarios including embedded fields, custom tags, and native language columns Provides intelligent code injection and smart updates to achieve zero-maintenance workflows

gormcngen: 智能 GORM 代码生成引擎,具备 AST 级精度 从 GORM 模型自动生成类型安全的列结构体和 Columns() 方法 支持嵌入字段、自定义标签和原生语言列等复杂场景 提供智能代码注入和增量更新,实现零维护工作流

Package gormcngen: Schema-based configuration and single-use code generation Handles single instance schema analysis and targeted code generation Provides precise management of column struct generation and method creation

gormcngen: 基于 schema 的配置和单次使用代码生成 处理单个模式 schema 分析和针对性代码生成 提供对列结构体生成和方法创建的精确控制

Package gormcngen: Configuration options used in intelligent code generation actions Manages fine-grained aspects of AST-based code generation process Supports various generation modes, tag handling, and output customization

gormcngen: 智能代码生成行为的配置选项 提供对基于 AST 代码生成过程的精细控制 支持各种生成模式、标签处理和输出自定义

Index

Constants

View Source
const DirectiveSkipGenerate = "!gormcngen_generate"

DirectiveSkipGenerate is the recommended build directive value Use this with WithGoBuildDirective() to solve the regeneration problem When models change and generated code causes compilation issues, use:

go test -tags=gormcngen_generate

DirectiveSkipGenerate 是推荐的构建指令值 与 WithGoBuildDirective() 配合使用,解决重新生成问题 当模型变更导致生成代码编译问题时,使用:

go test -tags=gormcngen_generate

Variables

This section is empty.

Functions

func ShowSchemaChinese

func ShowSchemaChinese(sch *schema.Schema)

ShowSchemaChinese Displays schema information including struct name, table name, and fields. ShowSchemaChinese 显示模式结构信息,包括结构体名称、表名和字段信息。

func ShowSchemaEnglish

func ShowSchemaEnglish(sch *schema.Schema)

ShowSchemaEnglish Displays schema information including struct name, table name, and fields. ShowSchemaEnglish 显示模式结构信息,包括结构体名称、表名和字段信息。

func ShowSchemaRelationshipsChinese added in v1.0.45

func ShowSchemaRelationshipsChinese(sch *schema.Schema)

ShowSchemaRelationshipsChinese displays relationship information in Chinese to demonstrate schema structure and assist debugging ShowSchemaRelationshipsChinese 用中文显示关系信息,用于教学和调试目的

func ShowSchemaRelationshipsEnglish added in v1.0.45

func ShowSchemaRelationshipsEnglish(sch *schema.Schema)

ShowSchemaRelationshipsEnglish displays relationship information to demonstrate schema structure and assist debugging ShowSchemaRelationshipsEnglish 显示关系信息,用于教学和调试目的

Types

type CodeGenerationConfig

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

CodeGenerationConfig defines the configuration used in intelligent code generation Contains schema configurations and output paths used in AST-based code generation Manages the entire code generation workflow from analysis to output

CodeGenerationConfig 定义智能代码生成的配置 包含基于 AST 代码生成的 schema 配置和输出路径 管理从分析到输出的整个代码生成工作流

func NewCodeGenerationConfig

func NewCodeGenerationConfig(schemas []*SchemaConfig) *CodeGenerationConfig

NewCodeGenerationConfig creates a new instance of CodeGenerationConfig Initializes configuration with provided schema definitions used in code generation Returns a configured instance, which is then used to set method and struct output paths

NewCodeGenerationConfig 创建一个新的 CodeGenerationConfig 实例 使用提供的 schema 定义初始化代码生成配置 返回一个已配置的实例,准备进行方法和结构体路径指定

type Config

type Config = SchemaConfig

Config Configuration of generating column methods and structures. Config 根据模型生成列方法和结构的配置。

func NewConfig

func NewConfig(sch *schema.Schema, namingConfig *NamingConfig, options *Options) *Config

NewConfig Creates a new Config instance with the provided schema, struct name, method name, and options. NewConfig 创建一个新的 Config 实例,使用提供的 schema、结构体名称、方法名称和选项。

func (*Config) Gen

func (c *Config) Gen() *GenOutput

Gen Generates the column method and struct based on the configuration. Gen 根据配置生成列方法和结构。

func (*Config) Generate

func (c *Config) Generate() *GenOutput

Generate Generates the column method and struct based on the configuration. Generate 根据配置生成列方法和结构。

type Configs

type Configs = CodeGenerationConfig

Configs is an alias of CodeGenerationConfig, used in code generation tasks Configs 是 CodeGenerationConfig 的别名,用于代码生成任务

func NewConfigs

func NewConfigs(models []interface{}, options *Options, outputPath string) *Configs

NewConfigs initializes a Configs instance based on provided models and options. NewConfigs 根据提供的模型和选项初始化 Configs 实例

func (*Configs) Gen

func (cfg *Configs) Gen()

Gen is the core AST-powered code generation engine Analyzes provided schemas and generates type-safe column structs and methods Handles complex scenarios including existing code detection, smart updates, and intelligent merging Uses sophisticated AST manipulation to ensure precise code injection without breaking existing logic

Gen 是核心的 AST 驱动代码生成引擎 分析提供的 schema 并生成类型安全的列结构体和方法 处理包括现有代码检测、增量更新和智能合并在内的复杂场景 使用精巧的 AST 操作确保精准的代码注入,不破坏现有逻辑

func (*Configs) Generate

func (cfg *Configs) Generate()

Generate triggers the intelligent code generation process Executes the complete AST-based code generation workflow Convenience method that calls Gen() with enhanced API design

Generate 触发智能代码生成过程 执行完整的基于 AST 的代码生成工作流 便利方法,调用 Gen() 以提供更好的 API 人机工学

func (*Configs) WithGeneratedFromPos added in v1.0.47

func (cfg *Configs) WithGeneratedFromPos(generatedFromPos string) *Configs

WithGeneratedFromPos sets custom source location info in generated files Pass blank string to disable source location info Pass non-blank string to show custom location info in generated file headings Use GetGenPosFuncMark() function to auto get current position

WithGeneratedFromPos 为生成文件设置自定义源位置信息 传入空字符串禁用源位置显示 传入非空字符串在生成文件头部显示自定义位置信息 使用 GetGenPosFuncMark() 函数自动获取当前位置

func (*Configs) WithGoBuildDirective added in v1.0.50

func (cfg *Configs) WithGoBuildDirective(goBuildDirective string) *Configs

WithGoBuildDirective sets the go:build directive at the top of generated files Pass non-blank string to add "//go:build {directive}" line at file top Use "!gormcngen_generate" to skip compilation during code generation Run "go test -tags=gormcngen_generate" to generate when model changes

WithGoBuildDirective 设置生成文件顶部的 go:build 指令 传入非空字符串在文件顶部添加 "//go:build {directive}" 行 使用 "!gormcngen_generate" 在代码生成时跳过编译 运行 "go test -tags=gormcngen_generate" 在模型变更后生成代码

func (*Configs) WithIsGenPreventEdit added in v1.0.47

func (cfg *Configs) WithIsGenPreventEdit(isGenPreventEdit bool) *Configs

WithIsGenPreventEdit controls adding "DO NOT EDIT" comment headers When enabled, adds warning comments to prevent editing of generated files Set to false if you want clean generated code without warning headers

WithIsGenPreventEdit 控制是否添加"请勿编辑"注释头部 启用时,添加警告注释以防止手动编辑生成的文件 如果你想要干净的生成代码而不带警告头部,设置为 false

func (*Configs) WithMethodOutputPath

func (cfg *Configs) WithMethodOutputPath(path string) *Configs

WithMethodOutputPath specifies the output path of generated method code Configures where Columns() methods are written during code generation Returns the configuration instance, enabling method chaining

WithMethodOutputPath 指定生成方法代码的输出路径 配置 Columns() 方法在代码生成过程中的写入位置 返回配置实例以支持方法链式调用

func (*Configs) WithStructOutputPath

func (cfg *Configs) WithStructOutputPath(path string) *Configs

WithStructOutputPath specifies the output path of generated struct code Configures where column struct definitions are written during code generation Returns the configuration instance, enabling method chaining

WithStructOutputPath 指定生成结构体代码的输出路径 配置列结构体定义在代码生成过程中的写入位置 返回配置实例以支持方法链式调用

type GenOutput added in v1.0.40

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

GenOutput Structure representing the generated method and struct code with package imports. GenOutput 表示生成的方法和结构体代码,以及涉及的包导入信息。

func (*GenOutput) GetMethodCode added in v1.0.40

func (x *GenOutput) GetMethodCode() string

func (*GenOutput) GetMethodTableColumnsCode added in v1.0.40

func (x *GenOutput) GetMethodTableColumnsCode() string

func (*GenOutput) GetPkgImports added in v1.0.40

func (x *GenOutput) GetPkgImports() map[string]bool

func (*GenOutput) GetStructCode added in v1.0.40

func (x *GenOutput) GetStructCode() string

type NamingConfig added in v1.0.40

type NamingConfig struct {
	StructName             string // Generated column struct name // 生成的列结构体名称
	MethodNameColumns      string // Columns() method name // Columns() 方法名称
	MethodNameTableColumns string // TableColumns() method name // TableColumns() 方法名称
}

NamingConfig holds naming conventions used in generated code elements Contains struct name and method names used in code generation output

NamingConfig 保存生成代码元素的命名约定 包含代码生成输出中使用的结构体名称和方法名称

func NewNamingConfig added in v1.0.40

func NewNamingConfig(sch *schema.Schema, options *Options) *NamingConfig

NewNamingConfig creates naming configuration based on schema and options Generates struct name with appropriate exportable status Returns configured naming conventions used in code generation

NewNamingConfig 根据 schema 和选项创建命名配置 生成具有适当导出性的结构体名称 返回代码生成中使用的命名约定

type Options

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

Options manages fine-grained aspects of code generation actions Configures various aspects of the intelligent code generation process Manages struct export status, tag processing, field output, and method generation

Options 配置智能代码生成过程的各个方面 控制结构体导出可见性、标签处理、字段过滤和方法生成

func NewOptions added in v1.0.34

func NewOptions() *Options

NewOptions creates a new Options instance with sensible default values Initializes configuration optimized to common use cases and best practices Returns a pre-configured instance prepared to customize via With methods

NewOptions 创建一个具有合理默认值的 Options 实例 初始化针对常见用例和最佳实践优化的配置 返回一个预配置的实例,准备通过 With 方法进行自定义

func (*Options) WithColumnClassExportable added in v1.0.35

func (o *Options) WithColumnClassExportable(columnClassExportable bool) *Options

func (*Options) WithColumnsCheckFieldType added in v1.0.34

func (o *Options) WithColumnsCheckFieldType(columnsCheckFieldType bool) *Options

func (*Options) WithColumnsMethodRecvName added in v1.0.34

func (o *Options) WithColumnsMethodRecvName(columnsMethodRecvName string) *Options

func (*Options) WithEmbedColumnOperations added in v1.0.34

func (o *Options) WithEmbedColumnOperations(embedColumnOperations bool) *Options

func (*Options) WithExcludeUntaggedFields added in v1.0.34

func (o *Options) WithExcludeUntaggedFields(excludeUntaggedFields bool) *Options

func (*Options) WithIsGenFuncTableColumns added in v1.0.40

func (o *Options) WithIsGenFuncTableColumns(isGenFuncTableColumns bool) *Options

func (*Options) WithIsGenNewSimpleColumns added in v1.0.42

func (o *Options) WithIsGenNewSimpleColumns(isGenNewSimpleColumns bool) *Options

func (*Options) WithMatchIgnoreExportable added in v1.0.35

func (o *Options) WithMatchIgnoreExportable(matchIgnoreExportable bool) *Options

func (*Options) WithTagKeyName added in v1.0.34

func (o *Options) WithTagKeyName(tagKeyName string) *Options

func (*Options) WithUseTagName added in v1.0.34

func (o *Options) WithUseTagName(useTagName bool) *Options

type SchemaConfig

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

SchemaConfig holds configuration used in generating column methods and structures from GORM models Contains parsed schema information along with generation options and naming preferences Manages the complete lifecycle from schema analysis to code output generation

SchemaConfig 保存从 GORM 模型生成列方法和结构体的配置 包含已解析的 schema 信息以及生成选项和命名偏好 管理从 schema 分析到代码输出生成的完整生命周期

func NewSchemaConfig

func NewSchemaConfig(object interface{}, options *Options) *SchemaConfig

NewSchemaConfig creates a SchemaConfig instance from a GORM structure and generation options Parses the structure using GORM schema parsing and applies naming strategies Initializes schema analysis, shows debug information, and configures generation parameters Returns a configured SchemaConfig prepared to generate code

NewSchemaConfig 从 GORM 模型和生成选项创建 SchemaConfig 实例 使用 GORM schema 解析器解析模型结构并应用命名策略 初始化 schema 分析,显示调试信息,并配置生成参数 返回一个完整配置的 SchemaConfig,准备进行代码生成

Directories

Path Synopsis
internal
demos/demo1x command
Package main: Demo application showcasing gormcngen type-safe column generation Demonstrates automatic code generation and usage of generated column structs Shows database operations with type-safe queries using generated Columns() methods
Package main: Demo application showcasing gormcngen type-safe column generation Demonstrates automatic code generation and usage of generated column structs Shows database operations with type-safe queries using generated Columns() methods
demos/demo1x/internal/models
Package models: GORM model definitions for demo1 application Contains example GORM models used to showcase automatic column generation Demonstrates various GORM tag configurations and field types in a clean structure
Package models: GORM model definitions for demo1 application Contains example GORM models used to showcase automatic column generation Demonstrates various GORM tag configurations and field types in a clean structure
demos/demo2x command
Package main: Advanced demo application showcasing gormcngen with complex queries Demonstrates table joins and sophisticated column operations using type-safe methods Shows database scenarios with account-purchase relationships in production settings
Package main: Advanced demo application showcasing gormcngen with complex queries Demonstrates table joins and sophisticated column operations using type-safe methods Shows database scenarios with account-purchase relationships in production settings
demos/demo2x/internal/models
Package models: Advanced GORM model examples for demo2 application Contains GORM models demonstrating custom table naming and column generation Shows integration with gormcnm for type-safe database operations in clean architecture
Package models: Advanced GORM model examples for demo2 application Contains GORM models demonstrating custom table naming and column generation Shows integration with gormcnm for type-safe database operations in clean architecture
examples/example1/internal/models
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
examples/example2/internal/models
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
examples/example3/internal/models
Package models demonstrates column generation with SQL reserved words as field names Auto contains Example struct with Create, Select, Update, Delete fields Used to showcase SafeCnm handling for SQL-conflicting column names
Package models demonstrates column generation with SQL reserved words as field names Auto contains Example struct with Create, Select, Update, Delete fields Used to showcase SafeCnm handling for SQL-conflicting column names
examples/example4/internal/models
Package models demonstrates native language field naming with cnm tag support Auto contains Student and Class structs with Chinese field aliases Used to showcase custom tag-based column name generation patterns
Package models demonstrates native language field naming with cnm tag support Auto contains Student and Class structs with Chinese field aliases Used to showcase custom tag-based column name generation patterns
examples/example5/internal/models
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
examples/example6/internal/models
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
Package models provides example GORM model definitions for gormcngen demonstration Auto contains Person and Example structs with standard GORM tags Used to showcase basic column generation patterns
examples/example7/internal/models
Package models demonstrates Chinese cnm tag naming with TableName method Auto contains User and Order structs with Chinese field aliases Used to showcase namespace pattern with custom table names
Package models demonstrates Chinese cnm tag naming with TableName method Auto contains User and Order structs with Chinese field aliases Used to showcase namespace pattern with custom table names
examples/example8/internal/models
Package models demonstrates Chinese cnm tag naming with TableName method Auto contains User and Order structs with Chinese field aliases Used to showcase namespace pattern with custom table names
Package models demonstrates Chinese cnm tag naming with TableName method Auto contains User and Order structs with Chinese field aliases Used to showcase namespace pattern with custom table names
examples/example9/internal/models
Package models demonstrates GORM associations with pointer fields Auto contains User and Profile structs with foreignKey relationship Used to showcase column generation excluding association fields
Package models demonstrates GORM associations with pointer fields Auto contains User and Profile structs with foreignKey relationship Used to showcase column generation excluding association fields
utils
Package utils: Print utilities for gormcngen debugging and output Provides convenient printing functions for development and testing Wraps printgo functions with gormcngen-specific configurations
Package utils: Print utilities for gormcngen debugging and output Provides convenient printing functions for development and testing Wraps printgo functions with gormcngen-specific configurations

Jump to

Keyboard shortcuts

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