dialect/sql: add option to prefix select queries (#1598)

This commit is contained in:
Ariel Mashraki
2021-05-25 18:38:06 +03:00
committed by GitHub
parent 5d3cc575b3
commit 02452aad89

View File

@@ -1731,6 +1731,7 @@ type Selector struct {
offset *int
distinct bool
union []union
prefix Queries
}
// WithContext sets the context into the *Selector.
@@ -1905,7 +1906,7 @@ func (s *Selector) join(kind string, t TableView) *Selector {
return s
}
// unionType describes a union type.
// unionType describes an UNION type.
type unionType string
const (
@@ -1945,6 +1946,12 @@ func (s *Selector) UnionDistinct(t TableView) *Selector {
return s
}
// Prefix prefixes the query with list of queries.
func (s *Selector) Prefix(queries ...Querier) *Selector {
s.prefix = append(s.prefix, queries...)
return s
}
// C returns a formatted string for a selected column from this statement.
func (s *Selector) C(column string) string {
if s.as != "" {
@@ -2081,6 +2088,7 @@ func (s *Selector) Having(p *Predicate) *Selector {
// Query returns query representation of a `SELECT` statement.
func (s *Selector) Query() (string, []interface{}) {
b := s.Builder.clone()
s.joinPrefix(&b)
b.WriteString("SELECT ")
if s.distinct {
b.WriteString("DISTINCT ")
@@ -2153,6 +2161,13 @@ func (s *Selector) Query() (string, []interface{}) {
return b.String(), b.args
}
func (s *Selector) joinPrefix(b *Builder) {
if len(s.prefix) > 0 {
b.join(s.prefix, " ")
b.WriteByte(' ')
}
}
func (s *Selector) joinUnion(b *Builder) {
for _, union := range s.union {
b.WriteString(" UNION ")
@@ -2234,6 +2249,13 @@ func (w *WithBuilder) As(s *Selector) *WithBuilder {
return w
}
// C returns a formatted string for the WITH column.
func (w *WithBuilder) C(column string) string {
b := &Builder{dialect: w.dialect}
b.Ident(w.name).WriteByte('.').Ident(column)
return b.String()
}
// Query returns query representation of a `WITH` clause.
func (w *WithBuilder) Query() (string, []interface{}) {
w.WriteString("WITH ")