gormzhcn

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 2 Imported by: 0

README

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

🇨🇳 GORMZHCN - Chinese GORM Naming Guardian

gormzhcn puts a Chinese-localized interface on gormmom naming validation. Write GORM models with native Chinese fields, then guard that each database name a struct produces — the table name, each column name, each index name — stays database-safe, through intuitive Chinese type and method names. It runs as a plain unit test and touches no database.

🎯 Code in Chinese, ship database-safe schemas. gormzhcn catches Chinese names that a database would reject — long before such names reach the database.

Ecosystem

GORM Type-Safe Ecosystem


CHINESE README

中文说明


DISCLAIMER

Writing Go code in Chinese is a viable technique, but something to avoid in production engineering. This approach should not be used in serious and business settings. Teams and companies that embrace it could face contempt from peers and negative judgment across the profession. In business companies, this practice often becomes a target of public criticism. This project is dedicated to research and academic studies. Do not use this approach in production.


🤖 How gormzhcn became just a guardian (the AI-era simplification)

gormzhcn used to wrap a generation engine: you wrote Chinese fields, tags left blank, and it auto-synthesized the column names and index names on its own (pinyin and pattern-based encodings).

The AI era made that generation pointless. The moment you define a field, an AI assistant gives you a good, database-safe column name — in context, a cut above a fixed rule engine. A machine-synthesized z_zhang_hao was not what someone wanted. So the entire generation step lost its reason to exist.

What AI does not hand you on its own is the part that bites: validation. When you program in Chinese, GORM might turn a field into a non-ASCII column name, and it can build a composite index name out of Chinese field names — names the database rejects. That failure shows up late, at migration time, at runtime.

So gormzhcn dropped generation outright and now does just one thing: catch those naming problems in a database-free unit test, so none of them blow up in production.

  • ❌ Gone: code generation, pinyin/pattern column synthesis, the old code-gen types.
  • ✅ Kept: one job — validate that the table / column / index names are database-safe.
  • ✅ Zero database connection — a pure static check that runs as a plain unit test.

🚀 Installation

go get github.com/yylego/gormzhcn

🌟 The Problem & Solution

⚡ The trap of Chinese-language models

Chinese fields read great, but the names GORM derives from them can be names the database refuses:

type T账户信息 struct {
    ID   uint   `gorm:"primaryKey"`
    Z账号 string `gorm:"uniqueIndex"` // ❌ no index name → GORM builds one from the field name → non-ASCII → rejected
    N昵称 string `gorm:""`            // ❌ no column name → column falls back to a non-ASCII name → rejected
}
✅ The gormzhcn approach

Keep the Chinese field names, but give explicit database-safe column / index / table names — and let gormzhcn guard them in a unit test:

type T账户信息 struct {
    ID   uint   `gorm:"primaryKey"`
    Z账号 string `gorm:"column:account;uniqueIndex:udx_account"`
    N昵称 string `gorm:"column:nickname;index:idx_nickname"`
    A年龄 int    `gorm:"column:age"`
    S状态 string `gorm:"column:status;index:idx_status"`
}

func (*T账户信息) TableName() string {
    return "accounts" // database-safe ASCII table name
}

🛠️ Usage — validate in a unit test

gormzhcn opens no database connection; it runs as a plain unit test:

func TestValidateNaming(t *testing.T) {
    objects := []interface{}{
        &T账户信息{},
    }

    // Guard a batch: table / column / index names must be database-safe.
    require.NoError(t, gormzhcn.NewT模型校验器(objects, gormzhcn.NewT配置项()).Validate())

    // Guard a single struct on its own.
    require.NoError(t, gormzhcn.NewT校验器(&T账户信息{}, gormzhcn.NewT配置项()).Validate())
}

A failing name comes back as a precise message — naming the struct, the offending name, and the field when one applies — caught long before a migration. The name length cap and the GORM naming strategy are tunable:

v配置项 := gormzhcn.NewT配置项().
    With最大名字长度(63).        // name length cap (Postgres uses 63)
    With命名策略(schema.NamingStrategy{}) // pass a custom strategy when a project needs one

🤝 Use with the ecosystem

gormzhcn guards the naming; its sibling packages handle type-safe columns and repo-style CRUD. A common flow, start to finish in Chinese:

1. Define a Chinese struct with explicit database-safe names (see above): a T学生 with fields V名字, V性别, V班级编码, ...

2. Guard the naming with gormzhcn — a database-free unit test:

require.NoError(t, gormzhcn.NewT模型校验器([]interface{}{&T学生{}}, gormzhcn.NewT配置项()).Validate())

3. Generate type-safe columns with gormcngen:

gormcngen.NewConfigs([]interface{}{&T学生{}}, gormcngen.NewOptions().WithUseTagName(true), srcPath).Gen()
// → produces T学生Columns with Chinese columns: V名字, V性别, V班级编码, ...

4. Run queries with gormrepo through the Chinese columns:

repo := gormrepo.NewRepo(gormclass.Use(&T学生{}))
student, err := repo.Repo(db).First(func(db *gorm.DB, cls *T学生Columns) *gorm.DB {
    return db.Where(cls.V名字.Eq("杨亦乐"))
})

Complete runnable examples live in examples.


🔧 API Reference

Chinese name Wraps Description
NewT模型校验器(objects, 配置项) gormmom.NewConfigs Build a batch check
T模型校验器.Validate() Configs.Validate Validate the whole batch
NewT校验器(object, 配置项) gormmom.NewConfig Build a single-struct check
T校验器.Validate() Config.Validate Validate one struct
NewT配置项() gormmom.NewOptions Build a config
With最大名字长度(n) WithMaxNameLength Set the name length cap
With命名策略(namer) WithNamingStrategy Set the GORM naming strategy
GetOptions() Access the underlying gormmom.Options

Explore the complete GORM ecosystem with these integrated packages:

Core Ecosystem
  • gormcnm - GORM base package with type-safe columns and statement building
  • gormcngen - AST-based code generation with type-safe GORM operations
  • gormrepo - Repo pattern implementation with GORM best practices
  • gormmom - Native language GORM naming guardian (the engine gormzhcn wraps)
  • gormzhcn - Chinese GORM naming guardian (this package)

These packages handle GORM development aspects: localization, type protection, and naming validation.


📄 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

Stargazers

Documentation

Overview

Package gormzhcn gives gormmom naming validation a Chinese-localized interface. Write GORM models with native-language fields, then validate that the table name, each column name and each index name stays database-safe — through intuitive Chinese type and method names, built on top of gormmom.

gormzhcn 是 gormmom 命名校验的中文本地化封装 用母语字段编写 GORM 模型,再校验表名、每个列名和每个索引名是否数据库安全, 全程通过直观的中文类型名和方法名完成,底层基于 gormmom 构建

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type T校验器 added in v0.0.1

type T校验器 struct {
	// contains filtered or unexported fields
}

T校验器 validates a single object through a Chinese interface. Wraps gormmom.Config to validate one object on its own.

T校验器 通过中文接口校验单个模型 封装 gormmom.Config 单独校验一个模型

func NewT校验器 added in v0.0.1

func NewT校验器(object interface{}, v配置项 *T配置项) *T校验器

NewT校验器 prepares a single check from an object plus a config, parsing the object through reflection.

NewT校验器 用对象和配置构造校验器,通过反射解析对象

func (*T校验器) Validate added in v0.0.1

func (c *T校验器) Validate() error

Validate checks one object's table name, column names and index names.

Validate 校验单个模型的表名、列名、索引名

type T模型校验器 added in v0.0.1

type T模型校验器 struct {
	// contains filtered or unexported fields
}

T模型校验器 validates a batch of models through a Chinese interface. Wraps gormmom.Configs to validate a batch of models as a group.

T模型校验器 通过中文接口校验一批模型 封装 gormmom.Configs 把多个模型作为一组一起校验

func NewT模型校验器 added in v0.0.1

func NewT模型校验器(objects []interface{}, v配置项 *T配置项) *T模型校验器

NewT模型校验器 builds the batch from objects plus a config, parsing each through reflection.

NewT模型校验器 用对象集合和配置构造批量校验器,逐个通过反射解析

func (*T模型校验器) Validate added in v0.0.1

func (c *T模型校验器) Validate() error

Validate checks table, column and index names across the batch, returning the first issue.

Validate 校验整批模型的表名、列名、索引名,返回遇到的第一个问题

type T配置项

type T配置项 struct {
	// contains filtered or unexported fields
}

T配置项 represents validation settings with a Chinese interface. Wraps gormmom.Options to provide intuitive Chinese method names.

T配置项 代表带中文接口的校验设置 封装 gormmom.Options 以提供直观的中文方法名

func NewT配置项

func NewT配置项() *T配置项

NewT配置项 creates a new configuration with default settings.

NewT配置项 创建带默认设置的新配置

func (*T配置项) GetOptions

func (opt *T配置项) GetOptions() *gormmom.Options

GetOptions returns the underlying gormmom.Options instance.

GetOptions 返回底层的 gormmom.Options 实例

func (*T配置项) With命名策略 added in v0.0.1

func (opt *T配置项) With命名策略(namingStrategy schema.Namer) *T配置项

With命名策略 sets the GORM naming strategy and returns the config to chain. Set it when a project runs GORM with a custom strategy, so validation matches runtime.

With命名策略 设置 GORM 命名策略,返回自身以便链式调用 当项目用了自定义命名策略时设置它,让校验结果和运行时一致

func (*T配置项) With最大名字长度 added in v0.0.1

func (opt *T配置项) With最大名字长度(maxNameLength int) *T配置项

With最大名字长度 sets the name length cap and returns the config to chain. Databases reject a table, column, index name beyond this length.

With最大名字长度 设置名字长度上限,返回自身以便链式调用 超过该长度的表名、列名或索引名数据库不接受

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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