Skip to content

Commit

Permalink
feat: 添加 Engine.Prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Apr 8, 2024
1 parent ffea725 commit 93c64ed
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
27 changes: 20 additions & 7 deletions prefix.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,19 @@ type txPrefix struct {

// Prefix 为所有操作的表名加上统一的前缀
//
// 如果要复用表结构,可以采此对象进行相关操作,而不是直接使用 DBTx
// 如果要复用表结构,可以采此对象进行相关操作,而不是直接使用 [DB][Tx]
func (db *DB) Prefix(p string) Engine {
p = db.TablePrefix() + p
return newDBPrefix(db, db.TablePrefix()+p, db.Dialect())
}

func (p *dbPrefix) Prefix(pp string) Engine {
return newDBPrefix(p.db, p.TablePrefix()+pp, p.Dialect())
}

func newDBPrefix(db *DB, tablePrefix string, d Dialect) Engine {
dp := &dbPrefix{
Engine: engine.New(db.DB(), p, db.Dialect()),
p: p,
Engine: engine.New(db.DB(), tablePrefix, d),
p: tablePrefix,
db: db,
}
dp.sb = sqlbuilder.New(dp)
Expand All @@ -48,10 +54,17 @@ func (db *DB) Prefix(p string) Engine {
//
// 创建的 [Engine] 依然属于当前事务。
func (tx *Tx) Prefix(p string) Engine {
p = tx.TablePrefix() + p
return newTxPrefix(tx, tx.TablePrefix()+p, tx.Dialect())
}

func (p *txPrefix) Prefix(pp string) Engine {
return newTxPrefix(p.tx, p.TablePrefix()+pp, p.Dialect())
}

func newTxPrefix(tx *Tx, tablePrefix string, d Dialect) Engine {
dp := &txPrefix{
Engine: engine.New(tx.Tx(), p, tx.Dialect()),
p: p,
Engine: engine.New(tx.Tx(), tablePrefix, d),
p: tablePrefix,
tx: tx,
}
dp.sb = sqlbuilder.New(dp)
Expand Down
2 changes: 2 additions & 0 deletions prefix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,11 @@ func TestPrefix_LastInsertID(t *testing.T) {

suite.Run(func(t *test.Driver) {
p1 := t.DB.Prefix("p1_")
p11 := p1.Prefix("p1_")
p2 := t.DB.Prefix("p2_")

a.NotError(p1.Create(&User{}))
a.NotError(p11.Create(&User{}))
a.NotError(p2.Create(&User{}))
defer func() {
a.NotError(p1.Drop(&User{}))
Expand Down
5 changes: 5 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ type (

SQLBuilder() *sqlbuilder.SQLBuilder

// Prefix 声明带有统一表名前缀的 [Engine]
//
// 返回的实例表名前缀为当前实例的表名前缀+p
Prefix(p string) Engine

// newModel 获取 v 的 [core.Model] 实例
//
// 内部使用不公开,[Engine] 也不会有外部的实现。
Expand Down

0 comments on commit 93c64ed

Please sign in to comment.