migrate.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package models
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io/fs"
  6. "log/slog"
  7. "strings"
  8. )
  9. import (
  10. "gorm.io/gorm"
  11. )
  12. import (
  13. "protocol-server/static"
  14. )
  15. func initTable(sqlFilePath string, db *gorm.DB) error {
  16. slog.Info("initTable ...", "file", sqlFilePath)
  17. file, err := static.GetSqlFile(sqlFilePath)
  18. if err != nil {
  19. return fmt.Errorf("error opening SQL file: %w", err)
  20. }
  21. defer func(file fs.File) {
  22. err := file.Close()
  23. if err != nil {
  24. slog.Error("error closing SQL file:", err)
  25. }
  26. }(file)
  27. scanner := bufio.NewScanner(file)
  28. err = db.Transaction(func(tx *gorm.DB) error {
  29. for scanner.Scan() {
  30. line := strings.TrimSpace(scanner.Text())
  31. result := tx.Exec(line)
  32. if result.Error != nil {
  33. return fmt.Errorf("error executing INSERT statement: %s\tError: %w", line, result.Error)
  34. }
  35. }
  36. if err := scanner.Err(); err != nil {
  37. return fmt.Errorf("error reading SQL file: %w", err)
  38. }
  39. return nil
  40. })
  41. if err != nil {
  42. return err
  43. }
  44. slog.Info("Processed SQL file", "file", sqlFilePath)
  45. return nil
  46. }
  47. func migrate(db *gorm.DB) {
  48. panicHelper(db.AutoMigrate(&PatientType{}))
  49. var count int64
  50. db.Model(&BodyPart{}).Count(&count)
  51. if count == 0 {
  52. panicHelper(initTable("p_patient_type_202505291630.sql", db))
  53. }
  54. panicHelper(db.AutoMigrate(&BodyPart{}))
  55. db.Model(&BodyPart{}).Count(&count)
  56. if count == 0 {
  57. panicHelper(initTable("p_body_part_202505291606.sql", db))
  58. }
  59. panicHelper(db.AutoMigrate(&Procedure{}))
  60. db.Model(&Procedure{}).Count(&count)
  61. if count == 0 {
  62. panicHelper(initTable("p_procedure_human_202506031132.sql", db))
  63. panicHelper(initTable("p_procedure_vet_202506031132.sql", db))
  64. }
  65. panicHelper(db.AutoMigrate(&View{}))
  66. db.Model(&View{}).Count(&count)
  67. if count == 0 {
  68. panicHelper(initTable("p_view_human_202506051008.sql", db))
  69. panicHelper(initTable("p_procedure_views_human_202506051009.sql", db))
  70. panicHelper(initTable("p_view_vet_202506051008.sql", db))
  71. panicHelper(initTable("p_procedure_views_vet_202506051009.sql", db))
  72. }
  73. }