select improvements
This commit is contained in:
@@ -5,15 +5,22 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// https://www.sqlite.org/lang_select.html
|
||||
type SelectQuery struct {
|
||||
distinct bool
|
||||
|
||||
columns []Column
|
||||
|
||||
// (from|join type), table, as, A, operator, B
|
||||
tables []SelectTable
|
||||
|
||||
where []Where
|
||||
args []any
|
||||
|
||||
// group // TODO
|
||||
// having // TODO
|
||||
|
||||
orderBy []OrderBy
|
||||
|
||||
limit int
|
||||
offset int
|
||||
}
|
||||
@@ -22,12 +29,6 @@ func (s *SelectQuery) Args() []any {
|
||||
return s.args
|
||||
}
|
||||
|
||||
func (s *SelectQuery) Column(def string) *SelectQuery {
|
||||
s.columns = append(s.columns, Column(def))
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *SelectQuery) Columns(defs ...string) *SelectQuery {
|
||||
for _, def := range defs {
|
||||
s.columns = append(s.columns, Column(def))
|
||||
@@ -36,6 +37,12 @@ func (s *SelectQuery) Columns(defs ...string) *SelectQuery {
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *SelectQuery) Distinct(distinct bool) *SelectQuery {
|
||||
s.distinct = distinct
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *SelectQuery) IsValid() bool {
|
||||
for _, c := range s.columns {
|
||||
if !c.IsValid() {
|
||||
@@ -83,13 +90,29 @@ func (s *SelectQuery) Offset(limit int) *SelectQuery {
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *SelectQuery) OrderBy(defs ...string) *SelectQuery {
|
||||
if s.orderBy == nil {
|
||||
s.orderBy = []OrderBy{}
|
||||
}
|
||||
|
||||
for _, def := range defs {
|
||||
s.orderBy = append(s.orderBy, OrderBy(def))
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *SelectQuery) String() string {
|
||||
strs := []string{"select"}
|
||||
|
||||
if s.distinct {
|
||||
strs = append(strs, "distinct")
|
||||
}
|
||||
|
||||
if len(s.columns) > 0 {
|
||||
for i, column := range s.columns {
|
||||
if i < len(s.columns)-1 {
|
||||
strs = append(strs, fmt.Sprintf("%s,", column.String()))
|
||||
strs = append(strs, fmt.Sprintf("%s,", column))
|
||||
} else {
|
||||
strs = append(strs, column.String())
|
||||
}
|
||||
@@ -110,9 +133,21 @@ func (s *SelectQuery) String() string {
|
||||
}
|
||||
}
|
||||
|
||||
if len(s.orderBy) > 0 {
|
||||
strs = append(strs, "order by")
|
||||
|
||||
for i, o := range s.orderBy {
|
||||
if i < len(s.orderBy)-1 {
|
||||
strs = append(strs, fmt.Sprintf("%s,", o))
|
||||
} else {
|
||||
strs = append(strs, o.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if s.limit > 0 {
|
||||
if s.offset > 0 {
|
||||
strs = append(strs, fmt.Sprintf("limit %d, %d", s.offset, s.limit))
|
||||
strs = append(strs, fmt.Sprintf("limit %d offset %d", s.offset, s.limit))
|
||||
} else {
|
||||
strs = append(strs, fmt.Sprintf("limit %d", s.limit))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user