55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
package business
|
|
|
|
import (
|
|
"errors"
|
|
kratoserrors "github.com/go-kratos/kratos/v3/errors"
|
|
"gorm.io/gorm"
|
|
"kra/internal/biz/business"
|
|
)
|
|
|
|
func storageError(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var typed *kratoserrors.Error
|
|
if errors.As(err, &typed) {
|
|
return err
|
|
}
|
|
return business.ErrStorage
|
|
}
|
|
|
|
func businessTableAvailable(db *gorm.DB, name string) (bool, error) {
|
|
return businessTablesAvailable(db, name)
|
|
}
|
|
|
|
// 一次检查请求所需的表,不为每个依赖重复枚举整个业务库。
|
|
// 不缓存结果,保留迁移后新建表和运行时连接异常的可见性。
|
|
func businessTablesAvailable(db *gorm.DB, names ...string) (bool, error) {
|
|
if len(names) == 0 {
|
|
return true, nil
|
|
}
|
|
var tables []string
|
|
var err error
|
|
switch db.Dialector.Name() {
|
|
case "mysql":
|
|
err = db.Raw("SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name IN ?", names).Scan(&tables).Error
|
|
case "sqlite":
|
|
err = db.Raw("SELECT name FROM sqlite_master WHERE type='table' AND name IN ?", names).Scan(&tables).Error
|
|
default:
|
|
tables, err = db.Migrator().GetTables()
|
|
}
|
|
if err != nil {
|
|
return false, business.ErrStorage
|
|
}
|
|
found := make(map[string]bool, len(tables))
|
|
for _, table := range tables {
|
|
found[table] = true
|
|
}
|
|
for _, name := range names {
|
|
if !found[name] {
|
|
return false, nil
|
|
}
|
|
}
|
|
return true, nil
|
|
}
|