github.com/kunlun-qilian/sqlx/v3@v3.0.0/builder/addition_join.go (about) 1 package builder 2 3 import ( 4 "context" 5 "strings" 6 ) 7 8 type JoinAddition struct{} 9 10 func (JoinAddition) AdditionType() AdditionType { 11 return AdditionJoin 12 } 13 14 func Join(table SqlExpr, prefixes ...string) *join { 15 return &join{ 16 prefix: strings.Join(prefixes, " "), 17 target: table, 18 } 19 } 20 21 func InnerJoin(table SqlExpr) *join { 22 return Join(table, "INNER") 23 } 24 25 func LeftJoin(table SqlExpr) *join { 26 return Join(table, "LEFT") 27 } 28 29 func RightJoin(table SqlExpr) *join { 30 return Join(table, "RIGHT") 31 } 32 33 func FullJoin(table SqlExpr) *join { 34 return Join(table, "FULL") 35 } 36 37 func CrossJoin(table SqlExpr) *join { 38 return Join(table, "CROSS") 39 } 40 41 var _ Addition = (*join)(nil) 42 43 type join struct { 44 prefix string 45 target SqlExpr 46 joinCondition SqlCondition 47 joinColumnList []*Column 48 JoinAddition 49 } 50 51 func (j join) On(joinCondition SqlCondition) *join { 52 j.joinCondition = joinCondition 53 return &j 54 } 55 56 func (j join) Using(joinColumnList ...*Column) *join { 57 j.joinColumnList = joinColumnList 58 return &j 59 } 60 61 func (j *join) IsNil() bool { 62 return j == nil || IsNilExpr(j.target) || (j.prefix != "CROSS" && IsNilExpr(j.joinCondition) && len(j.joinColumnList) == 0) 63 } 64 65 func (j *join) Ex(ctx context.Context) *Ex { 66 t := "JOIN " 67 if j.prefix != "" { 68 t = j.prefix + " " + t 69 } 70 71 e := Expr(t) 72 73 e.WriteExpr(j.target) 74 75 if !(IsNilExpr(j.joinCondition)) { 76 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 77 ex := Expr(" ON ") 78 ex.WriteExpr(j.joinCondition) 79 return ex.Ex(ctx) 80 })) 81 } 82 83 if len(j.joinColumnList) > 0 { 84 e.WriteExpr(ExprBy(func(ctx context.Context) *Ex { 85 ex := Expr(" USING ") 86 87 ex.WriteGroup(func(e *Ex) { 88 for i := range j.joinColumnList { 89 if i != 0 { 90 ex.WriteQuery(", ") 91 } 92 ex.WriteExpr(j.joinColumnList[i]) 93 } 94 }) 95 96 return ex.Ex(ContextWithToggles(ctx, Toggles{ 97 ToggleMultiTable: false, 98 })) 99 })) 100 } 101 102 return e.Ex(ctx) 103 }