| 1 |
package clause |
| 2 |
|
| 3 |
import "gorm.io/gorm/utils" |
| 4 |
|
| 5 |
type JoinType string |
| 6 |
|
| 7 |
const ( |
| 8 |
CrossJoin JoinType = "CROSS" |
| 9 |
InnerJoin JoinType = "INNER" |
| 10 |
LeftJoin JoinType = "LEFT" |
| 11 |
RightJoin JoinType = "RIGHT" |
| 12 |
) |
| 13 |
|
| 14 |
type JoinTarget struct { |
| 15 |
Type JoinType |
| 16 |
Association string |
| 17 |
Subquery Expression |
| 18 |
Table string |
| 19 |
} |
| 20 |
|
| 21 |
func Has(name string) JoinTarget { |
| 22 |
return JoinTarget{Type: InnerJoin, Association: name} |
| 23 |
} |
| 24 |
|
| 25 |
func (jt JoinType) Association(name string) JoinTarget { |
| 26 |
return JoinTarget{Type: jt, Association: name} |
| 27 |
} |
| 28 |
|
| 29 |
func (jt JoinType) AssociationFrom(name string, subquery Expression) JoinTarget { |
| 30 |
return JoinTarget{Type: jt, Association: name, Subquery: subquery} |
| 31 |
} |
| 32 |
|
| 33 |
func (jt JoinTarget) As(name string) JoinTarget { |
| 34 |
jt.Table = name |
| 35 |
return jt |
| 36 |
} |
| 37 |
|
| 38 |
// Join clause for from |
| 39 |
type Join struct { |
| 40 |
Type JoinType |
| 41 |
Table Table |
| 42 |
ON Where |
| 43 |
Using []string |
| 44 |
Expression Expression |
| 45 |
} |
| 46 |
|
| 47 |
func JoinTable(names ...string) Table { |
| 48 |
return Table{ |
| 49 |
Name: utils.JoinNestedRelationNames(names), |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
func (join Join) Build(builder Builder) { |
| 54 |
if join.Expression != nil { |
| 55 |
join.Expression.Build(builder) |
| 56 |
} else { |
| 57 |
if join.Type != "" { |
| 58 |
builder.WriteString(string(join.Type)) |
| 59 |
builder.WriteByte(' ') |
| 60 |
} |
| 61 |
|
| 62 |
builder.WriteString("JOIN ") |
| 63 |
builder.WriteQuoted(join.Table) |
| 64 |
|
| 65 |
if len(join.ON.Exprs) > 0 { |
| 66 |
builder.WriteString(" ON ") |
| 67 |
join.ON.Build(builder) |
| 68 |
} else if len(join.Using) > 0 { |
| 69 |
builder.WriteString(" USING (") |
| 70 |
for idx, c := range join.Using { |
| 71 |
if idx > 0 { |
| 72 |
builder.WriteByte(',') |
| 73 |
} |
| 74 |
builder.WriteQuoted(c) |
| 75 |
} |
| 76 |
builder.WriteByte(')') |
| 77 |
} |
| 78 |
} |
| 79 |
} |