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