select improvements

This commit is contained in:
2026-07-07 19:59:32 +01:00
parent daff6a8f09
commit b302622d0a
3 changed files with 60 additions and 9 deletions
+7
View File
@@ -0,0 +1,7 @@
package simql
type OrderBy string
func (o OrderBy) String() string {
return string(o)
}
+44 -9
View File
@@ -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))
}
+9
View File
@@ -45,6 +45,15 @@ func TestSelect(t *testing.T) {
Args: []any{1234},
String: "select name, email from customer where id = ?",
},
{
In: Select("customer").Where("age > ?", 18).OrderBy("age desc", "name asc"),
Args: []any{18},
String: "select * from customer where age > ? order by age desc, name asc",
},
{
In: Select("customer").Distinct(true).Columns("age"),
String: "select distinct age from customer",
},
}
for _, testCase := range testCases {