setup.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package models
  2. import (
  3. "fmt"
  4. "log/slog"
  5. )
  6. import (
  7. "gorm.io/driver/postgres"
  8. "gorm.io/gorm"
  9. )
  10. import (
  11. "protocol-server/common"
  12. "protocol-server/logger"
  13. )
  14. var (
  15. DB *gorm.DB
  16. err error
  17. )
  18. func panicHelper(err error) {
  19. if err != nil {
  20. panic(err)
  21. }
  22. }
  23. func migrate() {
  24. panicHelper(DB.AutoMigrate(&PatientType{}))
  25. var count int64
  26. DB.Model(&BodyPart{}).Count(&count)
  27. if count == 0 {
  28. panicHelper(initTable("p_patient_type_202505291630.sql"))
  29. }
  30. panicHelper(DB.AutoMigrate(&BodyPart{}))
  31. DB.Model(&BodyPart{}).Count(&count)
  32. if count == 0 {
  33. panicHelper(initTable("p_body_part_202505291606.sql"))
  34. }
  35. panicHelper(DB.AutoMigrate(&Procedure{}))
  36. }
  37. func SetupGorm(m bool) {
  38. slog.Info("setup gorm")
  39. dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai",
  40. common.PostgresConfig.Ip,
  41. common.PostgresConfig.Username,
  42. common.PostgresConfig.Password,
  43. common.PostgresConfig.Name,
  44. common.PostgresConfig.Port,
  45. )
  46. if common.LoggerConfig.LogLevel == "debug" {
  47. DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
  48. Logger: logger.NewGormLogger(logger.WithGroup("gorm")),
  49. })
  50. } else {
  51. DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
  52. }
  53. if err != nil {
  54. panic(err)
  55. }
  56. if m {
  57. migrate()
  58. }
  59. slog.Info("setup gorm ok")
  60. }