JCC-CSScheduler/common/pkgs/db/db.go

92 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 db
import (
_ "github.com/go-sql-driver/mysql"
"github.com/sirupsen/logrus"
"gitlink.org.cn/cloudream/scheduler/common/pkgs/db/config"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// TODO 迁移到Gorm
// TODO ComputingCenter去掉了CDSNodeID字段需要修改DB的结构
//type DB struct {
// d *sqlx.DB
//}
//
//type SQLContext interface {
// sqlx.Queryer
// sqlx.Execer
// sqlx.Ext
//}
//
//func NewDB(cfg *config.Config) (*DB, error) {
// db, err := sqlx.Open("mysql", cfg.MakeSourceString())
// if err != nil {
// return nil, fmt.Errorf("open database connection failed, err: %w", err)
// }
//
// // 尝试连接一下数据库,如果数据库配置有错误在这里就能报出来
// err = db.Ping()
// if err != nil {
// return nil, err
// }
//
// return &DB{
// d: db,
// }, nil
//}
//
//func (db *DB) DoTx(isolation sql.IsolationLevel, fn func(tx *sqlx.Tx) error) error {
// tx, err := db.d.BeginTxx(context.Background(), &sql.TxOptions{Isolation: isolation})
// if err != nil {
// return err
// }
//
// if err := fn(tx); err != nil {
// tx.Rollback()
// return err
// }
//
// if err := tx.Commit(); err != nil {
// tx.Rollback()
// return err
// }
//
// return nil
//}
//
//func (db *DB) SQLCtx() SQLContext {
// return db.d
//}
type DB struct {
db *gorm.DB
}
func NewDB(cfg *config.Config) (*DB, error) {
mydb, err := gorm.Open(mysql.Open(cfg.MakeSourceString()), &gorm.Config{})
if err != nil {
logrus.Fatalf("failed to connect to database: %v", err)
}
return &DB{
db: mydb,
}, nil
}
func (db *DB) DoTx(do func(tx SQLContext) error) error {
return db.db.Transaction(func(tx *gorm.DB) error {
return do(SQLContext{tx})
})
}
type SQLContext struct {
*gorm.DB
}
func (db *DB) DefCtx() SQLContext {
return SQLContext{db.db}
}