2 Star 1 Fork 1

mosache/YFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
db.go 2.64 KB
一键复制 编辑 原始数据 按行查看 历史
ヤ沒脩袮兲︶ 提交于 2023-07-07 18:26 . temp
package orm
import (
"context"
"database/sql"
"database/sql/driver"
"gitee.com/mosache/YFrame/orm/internal/errs"
"gitee.com/mosache/YFrame/orm/internal/valuer"
"gitee.com/mosache/YFrame/orm/schema"
"log"
)
type DB struct {
core
db *sql.DB
}
type DBOption func(db *DB)
func DBWithDialect(dialect Dialect) DBOption {
return func(db *DB) {
db.dialect = dialect
db.quoter = dialect.Quoter()
}
}
func DBWithRegister(r *schema.Register) DBOption {
return func(db *DB) {
db.r = r
}
}
func DBWithCreator(creator valuer.Creator) DBOption {
return func(db *DB) {
db.creator = creator
}
}
func DBWithMdls(mdls ...Middleware) DBOption {
return func(db *DB) {
db.mdls = mdls
}
}
///==================================================================================================
func Open(driveName string, dataSourceName string, opts ...DBOption) (*DB, error) {
sqlDB, err := sql.Open(driveName, dataSourceName)
if err != nil {
return nil, err
}
dialect := StandSQL{}
db := &DB{
core: core{
r: schema.NewRegister(),
creator: valuer.NewUnsafeValuer,
dialect: dialect,
quoter: dialect.Quoter(),
},
db: sqlDB,
}
for _, e := range opts {
e(db)
}
return db, nil
}
func OpenDB(sqlDB *sql.DB, opts ...DBOption) (*DB, error) {
dialect := StandSQL{}
db := &DB{
db: sqlDB,
core: core{
r: schema.NewRegister(),
creator: valuer.NewUnsafeValuer,
dialect: dialect,
quoter: dialect.Quoter(),
},
}
for _, e := range opts {
e(db)
}
return db, nil
}
func MustNewDB(driveName string, dataSourceName string, opts ...DBOption) *DB {
db, err := Open(driveName, dataSourceName, opts...)
if err != nil {
panic(err)
}
return db
}
func (db *DB) getCore() core {
return db.core
}
func (db *DB) queryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
return db.db.QueryContext(ctx, query, args...)
}
func (db *DB) execContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
return db.db.ExecContext(ctx, query, args...)
}
func (db *DB) DoTx(context context.Context, fn func(ctx context.Context, tx *Tx) error, opts *sql.TxOptions) (err error) {
var tx *Tx
tx, err = db.BeginTx(context, opts)
if err != nil {
return err
}
panicked := true
defer func() {
if panicked || err != nil {
rErr := tx.RollBack()
err = errs.NewErrRollBackErr(err, rErr, panicked)
} else {
err = tx.Commit()
}
}()
err = fn(context, tx)
if err != nil {
return err
}
panicked = false
return err
}
func (db *DB) Wait() error {
err := db.db.Ping()
for err == driver.ErrBadConn {
log.Println("wait for db to start...")
err = db.db.Ping()
}
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.103

搜索帮助

0d507c66 1850385 C8b1a773 1850385