From cd473c0e177f7e09612efccd3d4cd4a4d514ad7b Mon Sep 17 00:00:00 2001 From: Yvan <8574526@qq,com> Date: Wed, 7 Jan 2026 11:03:52 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E4=B8=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/gen/main.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 cmd/gen/main.go diff --git a/cmd/gen/main.go b/cmd/gen/main.go new file mode 100644 index 0000000..4f23349 --- /dev/null +++ b/cmd/gen/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "fmt" + "path/filepath" + "runtime" + + "gorm.io/driver/mysql" + "gorm.io/gen" + "gorm.io/gorm" +) + +func main() { + // 连接数据库 + dsn := "root:Xu950329.@tcp(localhost:3306)/spa?charset=utf8mb4&parseTime=True&loc=Local" + db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) + if err != nil { + panic(fmt.Errorf("connect db fail: %w", err)) + } + + // 获取项目根目录 + _, filename, _, _ := runtime.Caller(0) + projectRoot := filepath.Dir(filepath.Dir(filepath.Dir(filename))) + + // 创建gen实例 + g := gen.NewGenerator(gen.Config{ + OutPath: filepath.Join(projectRoot, "internal/data/query"), + ModelPkgPath: filepath.Join(projectRoot, "internal/data/model"), + Mode: gen.WithDefaultQuery | gen.WithQueryInterface, + FieldNullable: true, + FieldCoverable: false, + FieldSignable: false, + FieldWithIndexTag: true, + FieldWithTypeTag: true, + }) + + g.UseDB(db) + + // 字段名映射,避免与方法名冲突 + fieldOpts := []gen.ModelOpt{ + gen.FieldRename("table_name", "TblName"), + gen.FieldRename("table", "TblName"), // 避免与Table()方法冲突 + } + + // 生成所有表的model和query + allTables := g.GenerateAllTable(fieldOpts...) + g.ApplyBasic(allTables...) + + // 执行生成 + g.Execute() +}