main.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "fmt"
  4. "gorm.io/driver/mysql"
  5. "gorm.io/gen"
  6. "gorm.io/gorm"
  7. )
  8. var dsn = "root:1qaz2wsx!@tcp(10.14.85.240:3306)/pji_desktop?charset=utf8&parseTime=True&loc=Local"
  9. func main() {
  10. // 连接数据库
  11. db, err := gorm.Open(mysql.Open(dsn))
  12. if err != nil {
  13. panic(fmt.Errorf("cannot establish db connection: %w", err))
  14. }
  15. // 生成实例
  16. g := gen.NewGenerator(gen.Config{
  17. // 相对执行`go run`时的路径, 会自动创建目录
  18. OutPath: "gen/dal/query",
  19. // WithDefaultQuery 生成默认查询结构体(作为全局变量使用), 即`Q`结构体和其字段(各表模型)
  20. // WithoutContext 生成没有context调用限制的代码供查询
  21. // WithQueryInterface 生成interface形式的查询代码(可导出), 如`Where()`方法返回的就是一个可导出的接口类型
  22. Mode: gen.WithDefaultQuery | gen.WithQueryInterface,
  23. // 表字段可为 null 值时, 对应结体字段使用指针类型
  24. FieldNullable: true, // generate pointer when field is nullable
  25. // 表字段默认值与模型结构体字段零值不一致的字段, 在插入数据时需要赋值该字段值为零值的, 结构体字段须是指针类型才能成功, 即`FieldCoverable:true`配置下生成的结构体字段.
  26. // 因为在插入时遇到字段为零值的会被GORM赋予默认值. 如字段`age`表默认值为10, 即使你显式设置为0最后也会被GORM设为10提交.
  27. // 如果该字段没有上面提到的插入时赋零值的特殊需要, 则字段为非指针类型使用起来会比较方便.
  28. 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
  29. // 模型结构体字段的数字类型的符号表示是否与表字段的一致, `false`指示都用有符号类型
  30. FieldSignable: false, // detect integer field's unsigned type, adjust generated data type
  31. // 生成 gorm 标签的字段索引属性
  32. FieldWithIndexTag: false, // generate with gorm index tag
  33. // 生成 gorm 标签的字段类型属性
  34. FieldWithTypeTag: true, // generate with gorm column type tag
  35. })
  36. // 设置目标 db
  37. g.UseDB(db)
  38. // 创建模型文件
  39. //User := g.GenerateModel("users")
  40. MapUpdate := g.GenerateModel("map_update")
  41. World := g.GenerateModel("world")
  42. SimulationTestRecord := g.GenerateModel("simulation_test_record")
  43. Device := g.GenerateModel("device")
  44. DeviceMap := g.GenerateModel("device_map")
  45. SystemConfig := g.GenerateModel("system_config")
  46. OriginalMap := g.GenerateModel("original_map")
  47. // 创建模型的方法,生成文件在 query 目录; 先创建结果不会被后创建的覆盖
  48. g.ApplyBasic(MapUpdate, World, SimulationTestRecord, Device, DeviceMap, SystemConfig, OriginalMap)
  49. //g.ApplyBasic(World)
  50. g.Execute()
  51. }