Skip to content

Commit

Permalink
feat: join
Browse files Browse the repository at this point in the history
  • Loading branch information
wusongyuan committed Jul 30, 2021
1 parent 1994d16 commit fb22f9d
Show file tree
Hide file tree
Showing 5 changed files with 286 additions and 7 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ _testmain.go
!.gitkeep
.DS_Store
/.idea
/.vscode
/.vscode
/test/
52 changes: 51 additions & 1 deletion do.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"

"gorm.io/gen/field"
)
Expand Down Expand Up @@ -54,7 +55,7 @@ func (s *DO) UseTable(tableName string) {
}

// Table return table name
func (s *DO) Table() string {
func (s *DO) TableName() string {
return s.db.Statement.Table
}

Expand Down Expand Up @@ -207,6 +208,55 @@ func (s *DO) Unscoped() Dao {
return NewDO(s.db.Unscoped())
}

func (s *DO) Join(table schema.Tabler, conds ...Condition) Dao {
return s.join(table, clause.InnerJoin, conds...)
}

func (s *DO) LeftJoin(table schema.Tabler, conds ...Condition) Dao {
return s.join(table, clause.LeftJoin, conds...)
}

func (s *DO) RightJoin(table schema.Tabler, conds ...Condition) Dao {
return s.join(table, clause.RightJoin, conds...)
}

func (s *DO) join(table schema.Tabler, joinType clause.JoinType, conds ...Condition) Dao {
Emit(methodJoin)
var exprs = make([]clause.Expression, 0, len(conds))
for _, cond := range conds {
switch cond := cond.(type) {
case *DO:
exprs = append(exprs, cond.buildWhere()...)
default:
exprs = append(exprs, cond)
}
}

join := clause.Join{Type: joinType, Table: clause.Table{Name: table.TableName()}, ON: clause.Where{
Exprs: exprs,
}}
from := getFromClause(s.db)
if from == nil {
from = &clause.From{}
}
from.Joins = append(from.Joins, join)
return NewDO(s.db.Clauses(from))
}

func getFromClause(db *gorm.DB) *clause.From {
if db == nil {
return nil
}
c, ok := db.Statement.Clauses[clause.From{}.Name()]
if !ok || c.Expression == nil {
return nil
}
if from, ok := c.Expression.(clause.From); ok {
return &from
}
return nil
}

// ======================== finisher api ========================
func (s *DO) Create(value interface{}) error {
Emit(methodCreate)
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ module gorm.io/gen
go 1.16

require (
code.byted.org/gopkg/env v1.4.0
golang.org/x/tools v0.1.5
gorm.io/driver/mysql v1.1.1
gorm.io/gorm v1.21.12
gorm.io/plugin/dbresolver v1.1.0
)
Loading

0 comments on commit fb22f9d

Please sign in to comment.