generate.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/0xJacky/Nginx-UI/server/model"
  6. "github.com/0xJacky/Nginx-UI/server/settings"
  7. "gorm.io/driver/sqlite"
  8. "gorm.io/gen"
  9. "gorm.io/gorm"
  10. "gorm.io/gorm/logger"
  11. "log"
  12. "path"
  13. )
  14. func main() {
  15. // specify the output directory (default: "./query")
  16. // ### if you want to query without context constrain, set mode gen.WithoutContext ###
  17. g := gen.NewGenerator(gen.Config{
  18. OutPath: "../../server/query",
  19. Mode: gen.WithoutContext | gen.WithDefaultQuery,
  20. //if you want the nullable field generation property to be pointer type, set FieldNullable true
  21. FieldNullable: true,
  22. //if you want to assign field which has default value in `Create` API, set FieldCoverable true, reference: https://gorm.io/docs/create.html#Default-Values
  23. FieldCoverable: true,
  24. // if you want to generate field with unsigned integer type, set FieldSignable true
  25. /* FieldSignable: true,*/
  26. //if you want to generate index tags from database, set FieldWithIndexTag true
  27. /* FieldWithIndexTag: true,*/
  28. //if you want to generate type tags from database, set FieldWithTypeTag true
  29. /* FieldWithTypeTag: true,*/
  30. //if you need unit tests for query code, set WithUnitTest true
  31. /* WithUnitTest: true, */
  32. })
  33. // reuse the database connection in Project or create a connection here
  34. // if you want to use GenerateModel/GenerateModelAs, UseDB is necessary or it will panic
  35. var confPath string
  36. flag.StringVar(&confPath, "config", "app.ini", "Specify the configuration file")
  37. flag.Parse()
  38. settings.Init(confPath)
  39. dbPath := path.Join(path.Dir(settings.ConfPath), fmt.Sprintf("%s.db", settings.ServerSettings.Database))
  40. var err error
  41. db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{
  42. Logger: logger.Default.LogMode(logger.Info),
  43. PrepareStmt: true,
  44. DisableForeignKeyConstraintWhenMigrating: true,
  45. })
  46. if err != nil {
  47. log.Fatalln(err)
  48. }
  49. g.UseDB(db)
  50. // apply basic crud api on structs or table models which is specified by table name with function
  51. // GenerateModel/GenerateModelAs. And generator will generate table models' code when calling Excute.
  52. g.ApplyBasic(model.GenerateAllModel()...)
  53. // apply diy interfaces on structs or table models
  54. g.ApplyInterface(func(method model.Method) {}, model.GenerateAllModel()...)
  55. // execute the action of code generation
  56. g.Execute()
  57. }