gormcngen

package module
v0.0.0-...-ba5f815 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2025 License: MIT Imports: 24 Imported by: 0

README

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

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

Like MyBatis Plus in the Java ecosystem, which allows developers to dynamically retrieve 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.

CHINESE README

中文说明

Installation

go get github.com/elementarydi/gormcngen

Example Usage

1. Define Your Model

For example, let's say you have the following model:

type Example struct {
	Name string `gorm:"primary_key;type:varchar(100);"`
	Type string `gorm:"column:type;"`
	Rank int    `gorm:"column:rank;"`
}
2. Automatically Generate the Columns() Method

Using gormcngen, it will automatically generate the Columns() method for your model:

func (*Example) Columns() *ExampleColumns {
	return &ExampleColumns{
		Name: "name",
		Type: "type",
		Rank: "rank",
	}
}

type ExampleColumns struct {
	Name gormcnm.ColumnName[string]
	Type gormcnm.ColumnName[string]
	Rank gormcnm.ColumnName[int]
}
3. Querying with the Generated Columns()

Now you can easily use the generated Columns() method to build queries:

var res Example
var cls = res.Columns()

if err := db.Where(cls.Name.Eq("abc")).
    Where(cls.Type.Eq("xyz")).
    Where(cls.Rank.Gt(100)).
    Where(cls.Rank.Lt(200)).
    First(&res).Error; err != nil {
    panic(errors.WithMessage(err, "wrong"))
}

fmt.Println(res)
4. Example with Custom Column Names

If your model contains custom column names (like using Chinese), it works similarly:

type Demo struct {
	gorm.Model
	Name string `gorm:"type:varchar(100);" cnm:"V名称"`
	Type string `gorm:"type:varchar(100);" cnm:"V类型"`
}

Generated code:

func (*Demo) Columns() *DemoColumns {
	return &DemoColumns{
		ID:        "id",
		CreatedAt: "created_at",
		UpdatedAt: "updated_at",
		DeletedAt: "deleted_at",
		V名称:      "name",
		V类型:      "type",
	}
}

type DemoColumns struct {
	ID        gormcnm.ColumnName[uint]
	CreatedAt gormcnm.ColumnName[time.Time]
	UpdatedAt gormcnm.ColumnName[time.Time]
	DeletedAt gormcnm.ColumnName[gorm.DeletedAt]
	V名称      gormcnm.ColumnName[string]
	V类型      gormcnm.ColumnName[string]
}

With this, you can use your native language for column names when querying:

var demo Demo
var cls = demo.Columns()

if err := db.Where(cls.V名称.Eq("测试")).
    Where(cls.V类型.Eq("类型A")).
    First(&demo).Error; err != nil {
    panic(errors.WithMessage(err, "wrong"))
}

fmt.Println(demo)

This is a more straightforward explanation of how to install and use gormcngen to generate the Columns() method for GORM models, allowing you to easily build queries with column names in any language.


Demos

demos

Design Ideas

README OLD DOC


License

gormcngen is open-source and released under the MIT License. See the LICENSE file for more information.


Support

Welcome to contribute to this project by submitting pull requests or reporting issues.

If you find this package helpful, give it a star on GitHub!

Thank you for your support!

Happy Coding with gormcngen! 🎉

Give me stars. Thank you!!!

Starring

starring

Documentation

Index

Constants

This section is empty.

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 显示模式结构信息,包括结构体名称、表名和字段信息。

Types

type CodeGenerationConfig

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

CodeGenerationConfig defines the configuration of code generation. CodeGenerationConfig 是代码生成的配置

func NewCodeGenerationConfig

func NewCodeGenerationConfig(schemas []*SchemaConfig) *CodeGenerationConfig

NewCodeGenerationConfig creates a new instance of CodeGenerationConfig. NewCodeGenerationConfig 创建一个新的 CodeGenerationConfig 实例

type ColumnsMethodStructOutput

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

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

func (*ColumnsMethodStructOutput) GetMethodCode

func (x *ColumnsMethodStructOutput) GetMethodCode() string

func (*ColumnsMethodStructOutput) GetPkgImports

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

func (*ColumnsMethodStructOutput) GetStructCode

func (x *ColumnsMethodStructOutput) GetStructCode() string

type Config

type Config = SchemaConfig

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

func NewConfig

func NewConfig(sch *schema.Schema, structName string, methodName string, 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

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

func (*Config) Generate

func (c *Config) Generate() *ColumnsMethodStructOutput

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

type Configs

type Configs = CodeGenerationConfig

Configs is an alias for CodeGenerationConfig, used for 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 method responsible for generating code based on the provided schemas. Gen 是核心方法,负责根据提供的 schemas 生成代码

func (*Configs) Generate

func (cfg *Configs) Generate()

Generate triggers the code generation process by calling the Gen method. Generate 通过调用 Gen 方法触发代码生成过程

func (*Configs) WithMethodOutputPath

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

WithMethodOutputPath specifies the output path for method code. WithMethodOutputPath 设置方法代码的输出路径

func (*Configs) WithStructOutputPath

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

WithStructOutputPath specifies the output path for struct code. WithStructOutputPath 设置结构体代码的输出路径

type Options

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

Options Configuration options for controlling the generation behavior. Options 用于控制生成行为的配置选项。

func NewOptions

func NewOptions() *Options

NewOptions creates a new Options instance with default values. NewOptions 用于创建一个具有默认值的 Options 实例。

func (*Options) WithColumnClassExportable

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

func (*Options) WithColumnsCheckFieldType

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

func (*Options) WithColumnsMethodRecvName

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

func (*Options) WithEmbedColumnOperations

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

func (*Options) WithExcludeUntaggedFields

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

func (*Options) WithMatchIgnoreExportable

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

func (*Options) WithTagKeyName

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

func (*Options) WithUseTagName

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

type SchemaConfig

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

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

func NewSchemaConfig

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

NewSchemaConfig Creates a Config instance for the given destination model and options. NewSchemaConfig 为指定的目标模型和选项创建 Config 实例。

Jump to

Keyboard shortcuts

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