Files
aggregate_translate_server/cmd/migrate/migration/models/initdb.go
hucan 8ae43bfba9
Some checks failed
Build / build (push) Has been cancelled
CodeQL / Analyze (go) (push) Has been cancelled
build / Build (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitee (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitlab (push) Has been cancelled
Issue Close Require / issue-close-require (push) Has been cancelled
Issue Check Inactive / issue-check-inactive (push) Has been cancelled
1
2025-06-29 00:36:30 +08:00

73 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package models
import (
"fmt"
"go-admin/common/global"
"io/ioutil"
"log"
"strings"
"gorm.io/gorm"
)
func InitDb(db *gorm.DB) (err error) {
filePath := "config/db.sql"
if global.Driver == "postgres" {
filePath := "config/db.sql"
if err = ExecSql(db, filePath); err != nil {
return err
}
filePath = "config/pg.sql"
err = ExecSql(db, filePath)
} else if global.Driver == "mysql" {
filePath = "config/db-begin-mysql.sql"
if err = ExecSql(db, filePath); err != nil {
return err
}
filePath = "config/db.sql"
if err = ExecSql(db, filePath); err != nil {
return err
}
filePath = "config/db-end-mysql.sql"
err = ExecSql(db, filePath)
} else {
err = ExecSql(db, filePath)
}
return err
}
func ExecSql(db *gorm.DB, filePath string) error {
sql, err := Ioutil(filePath)
if err != nil {
fmt.Println("数据库基础数据初始化脚本读取失败!原因:", err.Error())
return err
}
sqlList := strings.Split(sql, ";")
for i := 0; i < len(sqlList)-1; i++ {
if strings.Contains(sqlList[i], "--") {
fmt.Println(sqlList[i])
continue
}
sql := strings.Replace(sqlList[i]+";", "\n", "", -1)
sql = strings.TrimSpace(sql)
if err = db.Exec(sql).Error; err != nil {
log.Printf("error sql: %s", sql)
if !strings.Contains(err.Error(), "Query was empty") {
return err
}
}
}
return nil
}
func Ioutil(filePath string) (string, error) {
if contents, err := ioutil.ReadFile(filePath); err == nil {
//因为contents是[]byte类型直接转换成string类型后会多一行空格,需要使用strings.Replace替换换行符
result := strings.Replace(string(contents), "\n", "", 1)
fmt.Println("Use ioutil.ReadFile to read a file:", result)
return result, nil
} else {
return "", err
}
}