gorm_gen.go 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package database
  2. import (
  3. "gorm.io/driver/mysql"
  4. "gorm.io/gen"
  5. "gorm.io/gorm"
  6. "os"
  7. )
  8. func generateGormDbModel(dsn string, daoPath string) {
  9. currentPath, _ := os.Getwd()
  10. db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
  11. genConfig := gen.Config{
  12. OutPath: currentPath + "/dao" + daoPath + "/query",
  13. ModelPkgPath: currentPath + "/dao" + daoPath + "/model",
  14. Mode: gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface,
  15. //// 表字段可为 null 值时, 对应结体字段使用指针类型
  16. FieldNullable: false, // generate pointer when field is nullable
  17. //
  18. //// 表字段默认值与模型结构体字段零值不一致的字段, 在插入数据时需要赋值该字段值为零值的, 结构体字段须是指针类型才能成功, 即`FieldCoverable:true`配置下生成的结构体字段.
  19. //// 因为在插入时遇到字段为零值的会被GORM赋予默认值. 如字段`age`表默认值为10, 即使你显式设置为0最后也会被GORM设为10提交.
  20. //// 如果该字段没有上面提到的插入时赋零值的特殊需要, 则字段为非指针类型使用起来会比较方便.
  21. //FieldCoverable: false, // generate pointer when field has default value, to fix problem zero value cannot be assign: https://gorm.io/docs/create.html#Default-Values
  22. //
  23. //// 模型结构体字段的数字类型的符号表示是否与表字段的一致, `false`指示都用有符号类型
  24. //FieldSignable: false, // detect integer field's unsigned type, adjust generated data type
  25. //// 生成 gorm 标签的字段索引属性
  26. //FieldWithIndexTag: false, // generate with gorm index tag
  27. //// 生成 gorm 标签的字段类型属性
  28. //FieldWithTypeTag: true, // generate with gorm column type tag
  29. }
  30. g := gen.NewGenerator(genConfig)
  31. g.WithImportPkgPath("github.com/shopspring/decimal")
  32. g.UseDB(db)
  33. // Add mapping for decimal(64,18) to decimal.Decimal
  34. // 自定义类型映射
  35. dataMap := map[string]func(detailType gorm.ColumnType) (dataType string){
  36. "tinyint": func(detailType gorm.ColumnType) (dataType string) { return "int64" },
  37. "smallint": func(detailType gorm.ColumnType) (dataType string) { return "int64" },
  38. "mediumint": func(detailType gorm.ColumnType) (dataType string) { return "int64" },
  39. "bigint": func(detailType gorm.ColumnType) (dataType string) { return "int64" },
  40. "int": func(detailType gorm.ColumnType) (dataType string) { return "int64" },
  41. "decimal": func(detailType gorm.ColumnType) (dataType string) { return "decimal.Decimal" }, // 金额类型全部转换为第三方库,github.com/shopspring/decimal
  42. }
  43. g.WithDataTypeMap(dataMap)
  44. // 修改字段名,和系统关键字冲突
  45. g.WithOpts(gen.FieldRename("table", "MTable"))
  46. g.GenerateAllTable()
  47. g.ApplyBasic(g.GenerateAllTable()...)
  48. g.Execute()
  49. }