123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package models
- import (
- "bufio"
- "fmt"
- "io/fs"
- "log/slog"
- "strings"
- )
- import (
- "gorm.io/gorm"
- )
- import (
- "protocol-server/static"
- )
- func initTable(sqlFilePath string, db *gorm.DB) error {
- slog.Info("initTable ...", "file", sqlFilePath)
- file, err := static.GetSqlFile(sqlFilePath)
- if err != nil {
- return fmt.Errorf("error opening SQL file: %w", err)
- }
- defer func(file fs.File) {
- err := file.Close()
- if err != nil {
- slog.Error("error closing SQL file:", err)
- }
- }(file)
- scanner := bufio.NewScanner(file)
- err = db.Transaction(func(tx *gorm.DB) error {
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- result := tx.Exec(line)
- if result.Error != nil {
- return fmt.Errorf("error executing INSERT statement: %s\tError: %w", line, result.Error)
- }
- }
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("error reading SQL file: %w", err)
- }
- return nil
- })
- if err != nil {
- return err
- }
- slog.Info("Processed SQL file", "file", sqlFilePath)
- return nil
- }
- func migrate(db *gorm.DB) {
- panicHelper(db.AutoMigrate(&PatientType{}))
- var count int64
- db.Model(&BodyPart{}).Count(&count)
- if count == 0 {
- panicHelper(initTable("p_patient_type_202505291630.sql", db))
- }
- panicHelper(db.AutoMigrate(&BodyPart{}))
- db.Model(&BodyPart{}).Count(&count)
- if count == 0 {
- panicHelper(initTable("p_body_part_202505291606.sql", db))
- }
- panicHelper(db.AutoMigrate(&Procedure{}))
- db.Model(&Procedure{}).Count(&count)
- if count == 0 {
- panicHelper(initTable("p_procedure_human_202506031132.sql", db))
- panicHelper(initTable("p_procedure_vet_202506031132.sql", db))
- }
- panicHelper(db.AutoMigrate(&View{}))
- db.Model(&View{}).Count(&count)
- if count == 0 {
- panicHelper(initTable("p_view_human_202506051008.sql", db))
- panicHelper(initTable("p_procedure_views_human_202506051009.sql", db))
- panicHelper(initTable("p_view_vet_202506051008.sql", db))
- panicHelper(initTable("p_procedure_views_vet_202506051009.sql", db))
- }
- }
|