Files

80 lines
1.5 KiB
Go
Raw Permalink Normal View History

2020-03-08 19:12:33 +08:00
package clause
2025-05-25 15:40:40 +08:00
import "gorm.io/gorm/utils"
2020-03-12 08:39:42 +08:00
type JoinType string
const (
CrossJoin JoinType = "CROSS"
2020-07-16 11:27:04 +08:00
InnerJoin JoinType = "INNER"
LeftJoin JoinType = "LEFT"
RightJoin JoinType = "RIGHT"
2020-03-12 08:39:42 +08:00
)
2025-05-25 15:40:40 +08:00
type JoinTarget struct {
Type JoinType
Association string
Subquery Expression
Table string
}
func Has(name string) JoinTarget {
return JoinTarget{Type: InnerJoin, Association: name}
}
func (jt JoinType) Association(name string) JoinTarget {
return JoinTarget{Type: jt, Association: name}
}
func (jt JoinType) AssociationFrom(name string, subquery Expression) JoinTarget {
return JoinTarget{Type: jt, Association: name, Subquery: subquery}
}
func (jt JoinTarget) As(name string) JoinTarget {
jt.Table = name
return jt
}
// Join clause for from
2020-03-12 08:39:42 +08:00
type Join struct {
2020-04-15 09:14:24 +08:00
Type JoinType
Table Table
ON Where
Using []string
Expression Expression
2020-03-12 08:39:42 +08:00
}
2025-05-25 15:40:40 +08:00
func JoinTable(names ...string) Table {
return Table{
Name: utils.JoinNestedRelationNames(names),
}
}
2020-03-12 08:39:42 +08:00
func (join Join) Build(builder Builder) {
2020-04-15 09:14:24 +08:00
if join.Expression != nil {
join.Expression.Build(builder)
} else {
if join.Type != "" {
builder.WriteString(string(join.Type))
builder.WriteByte(' ')
}
builder.WriteString("JOIN ")
builder.WriteQuoted(join.Table)
if len(join.ON.Exprs) > 0 {
builder.WriteString(" ON ")
join.ON.Build(builder)
} else if len(join.Using) > 0 {
builder.WriteString(" USING (")
for idx, c := range join.Using {
if idx > 0 {
builder.WriteByte(',')
}
builder.WriteQuoted(c)
}
builder.WriteByte(')')
2020-03-12 08:39:42 +08:00
}
}
2020-03-08 19:12:33 +08:00
}