super-graph/psql/psql.go

990 lines
22 KiB
Go
Raw Normal View History

2019-03-24 14:57:29 +01:00
package psql
import (
"bytes"
2019-03-24 14:57:29 +01:00
"errors"
"fmt"
"io"
"math"
"strings"
2019-03-24 14:57:29 +01:00
"github.com/dosco/super-graph/qcode"
"github.com/dosco/super-graph/util"
)
2019-05-13 01:27:26 +02:00
const (
empty = ""
)
2019-04-08 08:47:59 +02:00
type Config struct {
2019-04-09 03:24:29 +02:00
Schema *DBSchema
Vars map[string]string
TableMap map[string]string
2019-04-08 08:47:59 +02:00
}
2019-03-24 14:57:29 +01:00
type Compiler struct {
schema *DBSchema
2019-04-08 08:47:59 +02:00
vars map[string]string
2019-04-09 03:24:29 +02:00
tmap map[string]string
2019-03-24 14:57:29 +01:00
}
2019-04-08 08:47:59 +02:00
func NewCompiler(conf Config) *Compiler {
2019-04-09 03:24:29 +02:00
return &Compiler{conf.Schema, conf.Vars, conf.TableMap}
2019-03-24 14:57:29 +01:00
}
func (c *Compiler) AddRelationship(key uint64, val *DBRel) {
2019-05-13 01:27:26 +02:00
c.schema.RelMap[key] = val
}
func (c *Compiler) IDColumn(table string) string {
t, ok := c.schema.Tables[table]
if !ok {
return empty
}
return t.PrimaryCol
}
2019-06-02 01:48:42 +02:00
func (c *Compiler) CompileEx(qc *qcode.QCode) (uint32, []byte, error) {
w := &bytes.Buffer{}
skipped, err := c.Compile(qc, w)
return skipped, w.Bytes(), err
}
func (c *Compiler) Compile(qc *qcode.QCode, w *bytes.Buffer) (uint32, error) {
2019-05-13 01:27:26 +02:00
if len(qc.Query.Selects) == 0 {
2019-06-02 01:48:42 +02:00
return 0, errors.New("empty query")
2019-05-13 01:27:26 +02:00
}
root := &qc.Query.Selects[0]
2019-03-24 14:57:29 +01:00
st := util.NewStack()
2019-05-13 01:27:26 +02:00
ti, err := c.getTable(root)
2019-04-09 03:24:29 +02:00
if err != nil {
2019-06-02 01:48:42 +02:00
return 0, err
2019-04-09 03:24:29 +02:00
}
2019-03-24 14:57:29 +01:00
2019-05-13 01:27:26 +02:00
st.Push(&selectBlockClose{nil, root})
st.Push(&selectBlock{nil, root, qc, ti, c})
2019-03-24 14:57:29 +01:00
//fmt.Fprintf(w, `SELECT json_object_agg('%s', %s) FROM (`,
//root.FieldName, root.Table)
w.WriteString(`SELECT json_object_agg('`)
w.WriteString(root.FieldName)
w.WriteString(`', `)
w.WriteString(root.Table)
w.WriteString(`) FROM (`)
2019-05-13 01:27:26 +02:00
var ignored uint32
2019-03-24 14:57:29 +01:00
for {
if st.Len() == 0 {
break
}
intf := st.Pop()
switch v := intf.(type) {
case *selectBlock:
2019-05-13 01:27:26 +02:00
skipped, err := v.render(w)
if err != nil {
2019-06-02 01:48:42 +02:00
return 0, err
2019-05-13 01:27:26 +02:00
}
ignored |= skipped
2019-03-24 14:57:29 +01:00
2019-05-13 01:27:26 +02:00
for _, id := range v.sel.Children {
if hasBit(skipped, uint16(id)) {
2019-05-13 01:27:26 +02:00
continue
}
child := &qc.Query.Selects[id]
2019-04-09 03:24:29 +02:00
2019-05-13 01:27:26 +02:00
ti, err := c.getTable(child)
if err != nil {
2019-06-02 01:48:42 +02:00
return 0, err
}
2019-05-13 01:27:26 +02:00
st.Push(&joinClose{child})
st.Push(&selectBlockClose{v.sel, child})
st.Push(&selectBlock{v.sel, child, qc, ti, c})
st.Push(&joinOpen{child})
2019-03-24 14:57:29 +01:00
}
case *selectBlockClose:
2019-05-13 01:27:26 +02:00
err = v.render(w)
2019-03-24 14:57:29 +01:00
case *joinOpen:
2019-05-13 01:27:26 +02:00
err = v.render(w)
2019-03-24 14:57:29 +01:00
case *joinClose:
2019-05-13 01:27:26 +02:00
err = v.render(w)
}
2019-03-24 14:57:29 +01:00
2019-05-13 01:27:26 +02:00
if err != nil {
2019-06-02 01:48:42 +02:00
return 0, err
2019-03-24 14:57:29 +01:00
}
}
w.WriteString(`)`)
alias(w, `done_1337`)
w.WriteString(`;`)
2019-03-24 14:57:29 +01:00
2019-06-02 01:48:42 +02:00
return ignored, nil
2019-03-24 14:57:29 +01:00
}
2019-04-09 03:24:29 +02:00
func (c *Compiler) getTable(sel *qcode.Select) (*DBTableInfo, error) {
if tn, ok := c.tmap[sel.Table]; ok {
return c.schema.GetTable(tn)
}
return c.schema.GetTable(sel.Table)
}
2019-05-13 01:27:26 +02:00
func (v *selectBlock) processChildren() (uint32, []*qcode.Column) {
var skipped uint32
cols := make([]*qcode.Column, 0, len(v.sel.Cols))
colmap := make(map[string]struct{}, len(v.sel.Cols))
2019-03-24 14:57:29 +01:00
2019-05-13 01:27:26 +02:00
for i := range v.sel.Cols {
colmap[v.sel.Cols[i].Name] = struct{}{}
2019-03-24 14:57:29 +01:00
}
2019-05-13 01:27:26 +02:00
for _, id := range v.sel.Children {
child := &v.qc.Query.Selects[id]
2019-03-24 14:57:29 +01:00
rel, ok := v.schema.RelMap[child.RelID]
2019-03-24 14:57:29 +01:00
if !ok {
2019-05-13 01:27:26 +02:00
skipped |= (1 << uint(id))
2019-03-24 14:57:29 +01:00
continue
}
2019-05-13 01:27:26 +02:00
switch rel.Type {
case RelOneToMany:
fallthrough
case RelBelongTo:
2019-03-24 14:57:29 +01:00
if _, ok := colmap[rel.Col2]; !ok {
2019-05-13 01:27:26 +02:00
cols = append(cols, &qcode.Column{v.sel.Table, rel.Col2, rel.Col2})
2019-03-24 14:57:29 +01:00
}
2019-05-13 01:27:26 +02:00
case RelOneToManyThrough:
2019-03-24 14:57:29 +01:00
if _, ok := colmap[rel.Col1]; !ok {
2019-05-13 01:27:26 +02:00
cols = append(cols, &qcode.Column{v.sel.Table, rel.Col1, rel.Col1})
2019-03-24 14:57:29 +01:00
}
2019-05-13 01:27:26 +02:00
case RelRemote:
if _, ok := colmap[rel.Col1]; !ok {
cols = append(cols, &qcode.Column{v.sel.Table, rel.Col1, rel.Col2})
}
skipped |= (1 << uint(id))
default:
skipped |= (1 << uint(id))
2019-03-24 14:57:29 +01:00
}
}
2019-05-13 01:27:26 +02:00
return skipped, cols
2019-03-24 14:57:29 +01:00
}
type selectBlock struct {
parent *qcode.Select
sel *qcode.Select
2019-05-13 01:27:26 +02:00
qc *qcode.QCode
ti *DBTableInfo
2019-03-24 14:57:29 +01:00
*Compiler
}
func (v *selectBlock) render(w *bytes.Buffer) (uint32, error) {
2019-05-13 01:27:26 +02:00
skipped, childCols := v.processChildren()
2019-03-24 14:57:29 +01:00
hasOrder := len(v.sel.OrderBy) != 0
// SELECT
if v.sel.AsList {
//fmt.Fprintf(w, `SELECT coalesce(json_agg("%s"`, v.sel.Table)
w.WriteString(`SELECT coalesce(json_agg("`)
w.WriteString(v.sel.Table)
w.WriteString(`"`)
2019-03-24 14:57:29 +01:00
if hasOrder {
err := renderOrderBy(w, v.sel)
if err != nil {
2019-05-13 01:27:26 +02:00
return skipped, err
2019-03-24 14:57:29 +01:00
}
}
//fmt.Fprintf(w, `), '[]') AS "%s" FROM (`, v.sel.Table)
w.WriteString(`), '[]')`)
alias(w, v.sel.Table)
w.WriteString(` FROM (`)
2019-03-24 14:57:29 +01:00
}
// ROW-TO-JSON
w.WriteString(`SELECT `)
2019-03-24 14:57:29 +01:00
if len(v.sel.DistinctOn) != 0 {
v.renderDistinctOn(w)
}
w.WriteString(`row_to_json((`)
2019-03-24 14:57:29 +01:00
//fmt.Fprintf(w, `SELECT "sel_%d" FROM (SELECT `, v.sel.ID)
w.WriteString(`SELECT "sel_`)
int2string(w, v.sel.ID)
w.WriteString(`" FROM (SELECT `)
2019-03-24 14:57:29 +01:00
// Combined column names
v.renderColumns(w)
2019-05-13 01:27:26 +02:00
v.renderRemoteRelColumns(w)
err := v.renderJoinedColumns(w, skipped)
2019-03-24 14:57:29 +01:00
if err != nil {
2019-05-13 01:27:26 +02:00
return skipped, err
2019-03-24 14:57:29 +01:00
}
//fmt.Fprintf(w, `) AS "sel_%d"`, v.sel.ID)
w.WriteString(`)`)
aliasWithID(w, "sel", v.sel.ID)
2019-03-24 14:57:29 +01:00
//fmt.Fprintf(w, `)) AS "%s"`, v.sel.Table)
w.WriteString(`))`)
alias(w, v.sel.Table)
2019-03-24 14:57:29 +01:00
// END-ROW-TO-JSON
if hasOrder {
v.renderOrderByColumns(w)
}
// END-SELECT
// FROM (SELECT .... )
2019-05-13 01:27:26 +02:00
err = v.renderBaseSelect(w, childCols, skipped)
if err != nil {
2019-05-13 01:27:26 +02:00
return skipped, err
2019-03-24 14:57:29 +01:00
}
// END-FROM
2019-05-13 01:27:26 +02:00
return skipped, nil
2019-03-24 14:57:29 +01:00
}
type selectBlockClose struct {
parent *qcode.Select
sel *qcode.Select
}
func (v *selectBlockClose) render(w *bytes.Buffer) error {
2019-03-24 14:57:29 +01:00
hasOrder := len(v.sel.OrderBy) != 0
if hasOrder {
err := renderOrderBy(w, v.sel)
if err != nil {
return err
}
}
if len(v.sel.Paging.Limit) != 0 {
//fmt.Fprintf(w, ` LIMIT ('%s') :: integer`, v.sel.Paging.Limit)
w.WriteString(` LIMIT ('`)
w.WriteString(v.sel.Paging.Limit)
w.WriteString(`') :: integer`)
2019-03-24 14:57:29 +01:00
} else {
w.WriteString(` LIMIT ('20') :: integer`)
2019-03-24 14:57:29 +01:00
}
if len(v.sel.Paging.Offset) != 0 {
//fmt.Fprintf(w, ` OFFSET ('%s') :: integer`, v.sel.Paging.Offset)
w.WriteString(`OFFSET ('`)
w.WriteString(v.sel.Paging.Offset)
w.WriteString(`') :: integer`)
2019-03-24 14:57:29 +01:00
}
if v.sel.AsList {
//fmt.Fprintf(w, `) AS "%s_%d"`, v.sel.Table, v.sel.ID)
w.WriteString(`)`)
aliasWithID(w, v.sel.Table, v.sel.ID)
2019-03-24 14:57:29 +01:00
}
return nil
}
type joinOpen struct {
sel *qcode.Select
}
func (v joinOpen) render(w *bytes.Buffer) error {
w.WriteString(` LEFT OUTER JOIN LATERAL (`)
2019-03-24 14:57:29 +01:00
return nil
}
type joinClose struct {
sel *qcode.Select
}
func (v *joinClose) render(w *bytes.Buffer) error {
//fmt.Fprintf(w, `) AS "%s_%d_join" ON ('true')`, v.sel.Table, v.sel.ID)
w.WriteString(`)`)
aliasWithIDSuffix(w, v.sel.Table, v.sel.ID, "_join")
w.WriteString(` ON ('true')`)
2019-03-24 14:57:29 +01:00
return nil
}
func (v *selectBlock) renderJoinTable(w *bytes.Buffer) {
rel, ok := v.schema.RelMap[v.sel.RelID]
2019-03-24 14:57:29 +01:00
if !ok {
panic(errors.New("no relationship found"))
}
if rel.Type != RelOneToManyThrough {
return
}
//fmt.Fprintf(w, ` LEFT OUTER JOIN "%s" ON (("%s"."%s") = ("%s_%d"."%s"))`,
//rel.Through, rel.Through, rel.ColT, v.parent.Table, v.parent.ID, rel.Col1)
w.WriteString(` LEFT OUTER JOIN "`)
w.WriteString(rel.Through)
w.WriteString(`" ON ((`)
colWithTable(w, rel.Through, rel.ColT)
w.WriteString(`) = (`)
colWithTableID(w, v.parent.Table, v.parent.ID, rel.Col1)
w.WriteString(`))`)
2019-03-24 14:57:29 +01:00
}
func (v *selectBlock) renderColumns(w *bytes.Buffer) {
2019-03-24 14:57:29 +01:00
for i, col := range v.sel.Cols {
2019-05-13 01:27:26 +02:00
if i != 0 {
io.WriteString(w, ", ")
}
//fmt.Fprintf(w, `"%s_%d"."%s" AS "%s"`,
//v.sel.Table, v.sel.ID, col.Name, col.FieldName)
colWithTableIDAlias(w, v.sel.Table, v.sel.ID, col.Name, col.FieldName)
2019-05-13 01:27:26 +02:00
}
}
2019-03-24 14:57:29 +01:00
func (v *selectBlock) renderRemoteRelColumns(w *bytes.Buffer) {
2019-05-13 01:27:26 +02:00
i := 0
for _, id := range v.sel.Children {
child := &v.qc.Query.Selects[id]
rel, ok := v.schema.RelMap[child.RelID]
2019-05-13 01:27:26 +02:00
if !ok || rel.Type != RelRemote {
continue
}
if i != 0 || len(v.sel.Cols) != 0 {
2019-03-24 14:57:29 +01:00
io.WriteString(w, ", ")
}
//fmt.Fprintf(w, `"%s_%d"."%s" AS "%s"`,
//v.sel.Table, v.sel.ID, rel.Col1, rel.Col2)
colWithTableID(w, v.sel.Table, v.sel.ID, rel.Col1)
alias(w, rel.Col2)
2019-05-13 01:27:26 +02:00
i++
2019-03-24 14:57:29 +01:00
}
}
func (v *selectBlock) renderJoinedColumns(w *bytes.Buffer, skipped uint32) error {
2019-05-13 01:27:26 +02:00
colsRendered := len(v.sel.Cols) != 0
2019-03-24 14:57:29 +01:00
2019-05-13 01:27:26 +02:00
for _, id := range v.sel.Children {
skipThis := hasBit(skipped, uint16(id))
2019-03-24 14:57:29 +01:00
2019-05-13 01:27:26 +02:00
if colsRendered && !skipThis {
2019-03-24 14:57:29 +01:00
io.WriteString(w, ", ")
}
2019-05-13 01:27:26 +02:00
if skipThis {
continue
}
s := &v.qc.Query.Selects[id]
//fmt.Fprintf(w, `"%s_%d_join"."%s" AS "%s"`,
//s.Table, s.ID, s.Table, s.FieldName)
colWithTableIDSuffixAlias(w, s.Table, s.ID, "_join", s.Table, s.FieldName)
2019-03-24 14:57:29 +01:00
}
return nil
}
func (v *selectBlock) renderBaseSelect(w *bytes.Buffer, childCols []*qcode.Column, skipped uint32) error {
var groupBy []int
2019-04-04 06:53:24 +02:00
isRoot := v.parent == nil
isFil := v.sel.Where != nil
2019-04-09 03:24:29 +02:00
isSearch := v.sel.Args["search"] != nil
isAgg := false
w.WriteString(` FROM (SELECT `)
for i, col := range v.sel.Cols {
cn := col.Name
2019-04-09 03:24:29 +02:00
_, isRealCol := v.ti.Columns[cn]
2019-04-07 07:12:11 +02:00
2019-04-09 03:24:29 +02:00
if !isRealCol {
if isSearch {
switch {
case cn == "search_rank":
cn = v.ti.TSVCol
arg := v.sel.Args["search"]
//fmt.Fprintf(w, `ts_rank("%s"."%s", to_tsquery('%s')) AS %s`,
//v.sel.Table, cn, arg.Val, col.Name)
w.WriteString(`ts_rank(`)
colWithTable(w, v.sel.Table, cn)
w.WriteString(`, to_tsquery('`)
w.WriteString(arg.Val)
w.WriteString(`')`)
alias(w, col.Name)
2019-04-07 07:12:11 +02:00
2019-04-09 03:24:29 +02:00
case strings.HasPrefix(cn, "search_headline_"):
cn = cn[16:]
arg := v.sel.Args["search"]
//fmt.Fprintf(w, `ts_headline("%s"."%s", to_tsquery('%s')) AS %s`,
//v.sel.Table, cn, arg.Val, col.Name)
w.WriteString(`ts_headlinek(`)
colWithTable(w, v.sel.Table, cn)
w.WriteString(`, to_tsquery('`)
w.WriteString(arg.Val)
w.WriteString(`')`)
alias(w, col.Name)
2019-04-09 03:24:29 +02:00
}
} else {
pl := funcPrefixLen(cn)
if pl == 0 {
//fmt.Fprintf(w, `'%s not defined' AS %s`, cn, col.Name)
w.WriteString(`'`)
w.WriteString(cn)
w.WriteString(` not defined'`)
alias(w, col.Name)
} else {
isAgg = true
fn := cn[0 : pl-1]
cn := cn[pl:]
//fmt.Fprintf(w, `%s("%s"."%s") AS %s`, fn, v.sel.Table, cn, col.Name)
w.WriteString(fn)
w.WriteString(`(`)
colWithTable(w, v.sel.Table, cn)
w.WriteString(`)`)
alias(w, col.Name)
}
}
2019-03-24 14:57:29 +01:00
} else {
groupBy = append(groupBy, i)
//fmt.Fprintf(w, `"%s"."%s"`, v.sel.Table, cn)
colWithTable(w, v.sel.Table, cn)
2019-03-24 14:57:29 +01:00
}
if i < len(v.sel.Cols)-1 || len(childCols) != 0 {
//io.WriteString(w, ", ")
w.WriteString(`, `)
2019-03-24 14:57:29 +01:00
}
}
for i, col := range childCols {
2019-05-13 01:27:26 +02:00
if i != 0 {
//io.WriteString(w, ", ")
w.WriteString(`, `)
}
2019-05-13 01:27:26 +02:00
//fmt.Fprintf(w, `"%s"."%s"`, col.Table, col.Name)
colWithTable(w, col.Table, col.Name)
}
w.WriteString(` FROM `)
2019-04-09 03:24:29 +02:00
if tn, ok := v.tmap[v.sel.Table]; ok {
//fmt.Fprintf(w, ` FROM "%s" AS "%s"`, tn, v.sel.Table)
colWithAlias(w, tn, v.sel.Table)
2019-04-09 03:24:29 +02:00
} else {
//fmt.Fprintf(w, ` FROM "%s"`, v.sel.Table)
w.WriteString(`"`)
w.WriteString(v.sel.Table)
w.WriteString(`"`)
2019-04-09 03:24:29 +02:00
}
2019-04-04 06:53:24 +02:00
if isRoot && isFil {
w.WriteString(` WHERE (`)
2019-04-04 06:53:24 +02:00
if err := v.renderWhere(w); err != nil {
return err
}
w.WriteString(`)`)
}
2019-04-04 06:53:24 +02:00
if !isRoot {
2019-05-13 01:27:26 +02:00
v.renderJoinTable(w)
2019-04-04 06:53:24 +02:00
w.WriteString(` WHERE (`)
2019-05-13 01:27:26 +02:00
v.renderRelationship(w)
2019-04-04 06:53:24 +02:00
if isFil {
w.WriteString(` AND `)
if err := v.renderWhere(w); err != nil {
return err
}
}
w.WriteString(`)`)
}
2019-04-04 06:53:24 +02:00
if isAgg {
if len(groupBy) != 0 {
w.WriteString(` GROUP BY `)
2019-04-04 06:53:24 +02:00
for i, id := range groupBy {
2019-05-13 01:27:26 +02:00
if i != 0 {
w.WriteString(`, `)
2019-04-04 06:53:24 +02:00
}
//fmt.Fprintf(w, `"%s"."%s"`, v.sel.Table, v.sel.Cols[id].Name)
colWithTable(w, v.sel.Table, v.sel.Cols[id].Name)
}
}
}
if len(v.sel.Paging.Limit) != 0 {
//fmt.Fprintf(w, ` LIMIT ('%s') :: integer`, v.sel.Paging.Limit)
w.WriteString(` LIMIT ('`)
w.WriteString(v.sel.Paging.Limit)
w.WriteString(`') :: integer`)
} else {
w.WriteString(` LIMIT ('20') :: integer`)
}
if len(v.sel.Paging.Offset) != 0 {
//fmt.Fprintf(w, ` OFFSET ('%s') :: integer`, v.sel.Paging.Offset)
w.WriteString(` OFFSET ('`)
w.WriteString(v.sel.Paging.Offset)
w.WriteString(`') :: integer`)
}
//fmt.Fprintf(w, `) AS "%s_%d"`, v.sel.Table, v.sel.ID)
w.WriteString(`)`)
aliasWithID(w, v.sel.Table, v.sel.ID)
return nil
2019-03-24 14:57:29 +01:00
}
func (v *selectBlock) renderOrderByColumns(w *bytes.Buffer) {
2019-05-13 01:27:26 +02:00
colsRendered := len(v.sel.Cols) != 0
2019-03-24 14:57:29 +01:00
for i := range v.sel.OrderBy {
2019-05-13 01:27:26 +02:00
if colsRendered {
//io.WriteString(w, ", ")
w.WriteString(`, `)
2019-05-13 01:27:26 +02:00
}
2019-03-24 14:57:29 +01:00
c := v.sel.OrderBy[i].Col
//fmt.Fprintf(w, `"%s_%d"."%s" AS "%s_%d_%s_ob"`,
//v.sel.Table, v.sel.ID, c,
//v.sel.Table, v.sel.ID, c)
colWithTableID(w, v.sel.Table, v.sel.ID, c)
w.WriteString(` AS `)
tableIDColSuffix(w, v.sel.Table, v.sel.ID, c, "_ob")
2019-03-24 14:57:29 +01:00
}
}
func (v *selectBlock) renderRelationship(w *bytes.Buffer) {
rel, ok := v.schema.RelMap[v.sel.RelID]
2019-03-24 14:57:29 +01:00
if !ok {
panic(errors.New("no relationship found"))
}
switch rel.Type {
case RelBelongTo:
//fmt.Fprintf(w, `(("%s"."%s") = ("%s_%d"."%s"))`,
//v.sel.Table, rel.Col1, v.parent.Table, v.parent.ID, rel.Col2)
w.WriteString(`((`)
colWithTable(w, v.sel.Table, rel.Col1)
w.WriteString(`) = (`)
colWithTableID(w, v.parent.Table, v.parent.ID, rel.Col2)
w.WriteString(`))`)
2019-03-24 14:57:29 +01:00
case RelOneToMany:
//fmt.Fprintf(w, `(("%s"."%s") = ("%s_%d"."%s"))`,
//v.sel.Table, rel.Col1, v.parent.Table, v.parent.ID, rel.Col2)
w.WriteString(`((`)
colWithTable(w, v.sel.Table, rel.Col1)
w.WriteString(`) = (`)
colWithTableID(w, v.parent.Table, v.parent.ID, rel.Col2)
w.WriteString(`))`)
2019-03-24 14:57:29 +01:00
case RelOneToManyThrough:
//fmt.Fprintf(w, `(("%s"."%s") = ("%s"."%s"))`,
//v.sel.Table, rel.Col1, rel.Through, rel.Col2)
w.WriteString(`((`)
colWithTable(w, v.sel.Table, rel.Col1)
w.WriteString(`) = (`)
colWithTable(w, rel.Through, rel.Col2)
w.WriteString(`))`)
2019-03-24 14:57:29 +01:00
}
}
func (v *selectBlock) renderWhere(w *bytes.Buffer) error {
2019-03-24 14:57:29 +01:00
st := util.NewStack()
if v.sel.Where != nil {
st.Push(v.sel.Where)
2019-03-24 14:57:29 +01:00
}
for {
if st.Len() == 0 {
break
}
intf := st.Pop()
switch val := intf.(type) {
case qcode.ExpOp:
switch val {
case qcode.OpAnd:
w.WriteString(` AND `)
2019-03-24 14:57:29 +01:00
case qcode.OpOr:
w.WriteString(` OR `)
2019-03-24 14:57:29 +01:00
case qcode.OpNot:
w.WriteString(`NOT `)
2019-03-24 14:57:29 +01:00
default:
2019-05-13 01:27:26 +02:00
return fmt.Errorf("11: unexpected value %v (%t)", intf, intf)
2019-03-24 14:57:29 +01:00
}
case *qcode.Exp:
switch val.Op {
case qcode.OpAnd, qcode.OpOr:
for i := len(val.Children) - 1; i >= 0; i-- {
st.Push(val.Children[i])
if i > 0 {
st.Push(val.Op)
}
}
2019-03-24 14:57:29 +01:00
continue
case qcode.OpNot:
st.Push(val.Children[0])
st.Push(qcode.OpNot)
2019-03-24 14:57:29 +01:00
continue
}
if val.NestedCol {
//fmt.Fprintf(w, `(("%s") `, val.Col)
w.WriteString(`(("`)
w.WriteString(val.Col)
w.WriteString(`") `)
} else if len(val.Col) != 0 {
//fmt.Fprintf(w, `(("%s"."%s") `, v.sel.Table, val.Col)
w.WriteString(`((`)
colWithTable(w, v.sel.Table, val.Col)
w.WriteString(`) `)
2019-03-24 14:57:29 +01:00
}
valExists := true
2019-03-24 14:57:29 +01:00
switch val.Op {
case qcode.OpEquals:
w.WriteString(`=`)
2019-03-24 14:57:29 +01:00
case qcode.OpNotEquals:
w.WriteString(`!=`)
2019-03-24 14:57:29 +01:00
case qcode.OpGreaterOrEquals:
w.WriteString(`>=`)
2019-03-24 14:57:29 +01:00
case qcode.OpLesserOrEquals:
w.WriteString(`<=`)
2019-03-24 14:57:29 +01:00
case qcode.OpGreaterThan:
w.WriteString(`>`)
2019-03-24 14:57:29 +01:00
case qcode.OpLesserThan:
w.WriteString(`<`)
2019-03-24 14:57:29 +01:00
case qcode.OpIn:
w.WriteString(`IN`)
2019-03-24 14:57:29 +01:00
case qcode.OpNotIn:
w.WriteString(`NOT IN`)
2019-03-24 14:57:29 +01:00
case qcode.OpLike:
w.WriteString(`LIKE`)
2019-03-24 14:57:29 +01:00
case qcode.OpNotLike:
w.WriteString(`NOT LIKE`)
2019-03-24 14:57:29 +01:00
case qcode.OpILike:
w.WriteString(`ILIKE`)
2019-03-24 14:57:29 +01:00
case qcode.OpNotILike:
w.WriteString(`NOT ILIKE`)
2019-03-24 14:57:29 +01:00
case qcode.OpSimilar:
w.WriteString(`SIMILAR TO`)
2019-03-24 14:57:29 +01:00
case qcode.OpNotSimilar:
w.WriteString(`NOT SIMILAR TO`)
2019-03-24 14:57:29 +01:00
case qcode.OpContains:
w.WriteString(`@>`)
2019-03-24 14:57:29 +01:00
case qcode.OpContainedIn:
w.WriteString(`<@`)
2019-03-24 14:57:29 +01:00
case qcode.OpHasKey:
w.WriteString(`?`)
case qcode.OpHasKeyAny:
w.WriteString(`?|`)
case qcode.OpHasKeyAll:
w.WriteString(`?&`)
case qcode.OpIsNull:
if strings.EqualFold(val.Val, "true") {
w.WriteString(`IS NULL)`)
} else {
w.WriteString(`IS NOT NULL)`)
}
valExists = false
case qcode.OpEqID:
if len(v.ti.PrimaryCol) == 0 {
return fmt.Errorf("no primary key column defined for %s", v.sel.Table)
}
//fmt.Fprintf(w, `(("%s") =`, v.ti.PrimaryCol)
w.WriteString(`(("`)
w.WriteString(v.ti.PrimaryCol)
w.WriteString(`") =`)
case qcode.OpTsQuery:
if len(v.ti.TSVCol) == 0 {
return fmt.Errorf("no tsv column defined for %s", v.sel.Table)
}
//fmt.Fprintf(w, `(("%s") @@ to_tsquery('%s'))`, v.ti.TSVCol, val.Val)
w.WriteString(`(("`)
w.WriteString(v.ti.TSVCol)
w.WriteString(`") @@ to_tsquery('`)
w.WriteString(val.Val)
w.WriteString(`'))`)
valExists = false
2019-03-24 14:57:29 +01:00
default:
return fmt.Errorf("[Where] unexpected op code %d", val.Op)
}
if valExists {
if val.Type == qcode.ValList {
renderList(w, val)
} else {
renderVal(w, val, v.vars)
}
w.WriteString(`)`)
2019-03-24 14:57:29 +01:00
}
default:
2019-05-13 01:27:26 +02:00
return fmt.Errorf("12: unexpected value %v (%t)", intf, intf)
2019-03-24 14:57:29 +01:00
}
}
return nil
}
func renderOrderBy(w *bytes.Buffer, sel *qcode.Select) error {
w.WriteString(` ORDER BY `)
2019-03-24 14:57:29 +01:00
for i := range sel.OrderBy {
2019-05-13 01:27:26 +02:00
if i != 0 {
w.WriteString(`, `)
2019-05-13 01:27:26 +02:00
}
2019-03-24 14:57:29 +01:00
ob := sel.OrderBy[i]
switch ob.Order {
case qcode.OrderAsc:
//fmt.Fprintf(w, `"%s_%d.ob.%s" ASC`, sel.Table, sel.ID, ob.Col)
tableIDColSuffix(w, sel.Table, sel.ID, ob.Col, "_ob")
w.WriteString(` ASC`)
2019-03-24 14:57:29 +01:00
case qcode.OrderDesc:
//fmt.Fprintf(w, `"%s_%d.ob.%s" DESC`, sel.Table, sel.ID, ob.Col)
tableIDColSuffix(w, sel.Table, sel.ID, ob.Col, "_ob")
w.WriteString(` DESC`)
2019-03-24 14:57:29 +01:00
case qcode.OrderAscNullsFirst:
//fmt.Fprintf(w, `"%s_%d.ob.%s" ASC NULLS FIRST`, sel.Table, sel.ID, ob.Col)
tableIDColSuffix(w, sel.Table, sel.ID, ob.Col, "_ob")
w.WriteString(` ASC NULLS FIRST`)
2019-03-24 14:57:29 +01:00
case qcode.OrderDescNullsFirst:
//fmt.Fprintf(w, `%s_%d.ob.%s DESC NULLS FIRST`, sel.Table, sel.ID, ob.Col)
tableIDColSuffix(w, sel.Table, sel.ID, ob.Col, "_ob")
w.WriteString(` DESC NULLLS FIRST`)
2019-03-24 14:57:29 +01:00
case qcode.OrderAscNullsLast:
//fmt.Fprintf(w, `"%s_%d.ob.%s ASC NULLS LAST`, sel.Table, sel.ID, ob.Col)
tableIDColSuffix(w, sel.Table, sel.ID, ob.Col, "_ob")
w.WriteString(` ASC NULLS LAST`)
2019-03-24 14:57:29 +01:00
case qcode.OrderDescNullsLast:
//fmt.Fprintf(w, `%s_%d.ob.%s DESC NULLS LAST`, sel.Table, sel.ID, ob.Col)
tableIDColSuffix(w, sel.Table, sel.ID, ob.Col, "_ob")
w.WriteString(` DESC NULLS LAST`)
2019-03-24 14:57:29 +01:00
default:
2019-05-13 06:05:08 +02:00
return fmt.Errorf("13: unexpected value %v", ob.Order)
2019-03-24 14:57:29 +01:00
}
}
return nil
}
func (v selectBlock) renderDistinctOn(w *bytes.Buffer) {
io.WriteString(w, `DISTINCT ON (`)
2019-03-24 14:57:29 +01:00
for i := range v.sel.DistinctOn {
2019-05-13 01:27:26 +02:00
if i != 0 {
w.WriteString(`, `)
2019-03-24 14:57:29 +01:00
}
//fmt.Fprintf(w, `"%s_%d.ob.%s"`, v.sel.Table, v.sel.ID, v.sel.DistinctOn[i])
tableIDColSuffix(w, v.sel.Table, v.sel.ID, v.sel.DistinctOn[i], "_ob")
2019-03-24 14:57:29 +01:00
}
w.WriteString(`) `)
2019-03-24 14:57:29 +01:00
}
func renderList(w *bytes.Buffer, ex *qcode.Exp) {
2019-03-24 14:57:29 +01:00
io.WriteString(w, ` (`)
for i := range ex.ListVal {
2019-05-13 01:27:26 +02:00
if i != 0 {
w.WriteString(`, `)
2019-05-13 01:27:26 +02:00
}
2019-03-24 14:57:29 +01:00
switch ex.ListType {
case qcode.ValBool, qcode.ValInt, qcode.ValFloat:
w.WriteString(ex.ListVal[i])
2019-03-24 14:57:29 +01:00
case qcode.ValStr:
w.WriteString(`'`)
w.WriteString(ex.ListVal[i])
w.WriteString(`'`)
2019-03-24 14:57:29 +01:00
}
}
w.WriteString(`)`)
2019-03-24 14:57:29 +01:00
}
func renderVal(w *bytes.Buffer, ex *qcode.Exp, vars map[string]string) {
2019-03-24 14:57:29 +01:00
io.WriteString(w, ` (`)
switch ex.Type {
case qcode.ValBool, qcode.ValInt, qcode.ValFloat:
2019-04-19 07:55:03 +02:00
if len(ex.Val) != 0 {
w.WriteString(ex.Val)
2019-04-19 07:55:03 +02:00
} else {
w.WriteString(`''`)
2019-04-19 07:55:03 +02:00
}
2019-03-24 14:57:29 +01:00
case qcode.ValStr:
w.WriteString(`'`)
w.WriteString(ex.Val)
w.WriteString(`'`)
2019-03-24 14:57:29 +01:00
case qcode.ValVar:
if val, ok := vars[ex.Val]; ok {
w.WriteString(val)
2019-03-24 14:57:29 +01:00
} else {
//fmt.Fprintf(w, `'{{%s}}'`, ex.Val)
w.WriteString(`'{{`)
w.WriteString(ex.Val)
w.WriteString(`}}'`)
2019-03-24 14:57:29 +01:00
}
}
w.WriteString(`)`)
2019-03-24 14:57:29 +01:00
}
func funcPrefixLen(fn string) int {
switch {
case strings.HasPrefix(fn, "avg_"):
return 4
case strings.HasPrefix(fn, "count_"):
return 6
case strings.HasPrefix(fn, "max_"):
return 4
case strings.HasPrefix(fn, "min_"):
return 4
case strings.HasPrefix(fn, "sum_"):
return 4
case strings.HasPrefix(fn, "stddev_"):
return 7
case strings.HasPrefix(fn, "stddev_pop_"):
return 11
case strings.HasPrefix(fn, "stddev_samp_"):
return 12
case strings.HasPrefix(fn, "variance_"):
return 9
case strings.HasPrefix(fn, "var_pop_"):
return 8
case strings.HasPrefix(fn, "var_samp_"):
return 9
}
return 0
}
2019-05-13 01:27:26 +02:00
func hasBit(n uint32, pos uint16) bool {
val := n & (1 << pos)
return (val > 0)
}
func alias(w *bytes.Buffer, alias string) {
w.WriteString(` AS "`)
w.WriteString(alias)
w.WriteString(`"`)
}
func aliasWithID(w *bytes.Buffer, alias string, id int16) {
w.WriteString(` AS "`)
w.WriteString(alias)
w.WriteString(`_`)
int2string(w, id)
w.WriteString(`"`)
}
func aliasWithIDSuffix(w *bytes.Buffer, alias string, id int16, suffix string) {
w.WriteString(` AS "`)
w.WriteString(alias)
w.WriteString(`_`)
int2string(w, id)
w.WriteString(suffix)
w.WriteString(`"`)
}
func colWithAlias(w *bytes.Buffer, col, alias string) {
w.WriteString(`"`)
w.WriteString(col)
w.WriteString(`" AS "`)
w.WriteString(alias)
w.WriteString(`"`)
}
func colWithTable(w *bytes.Buffer, table, col string) {
w.WriteString(`"`)
w.WriteString(table)
w.WriteString(`"."`)
w.WriteString(col)
w.WriteString(`"`)
}
func colWithTableID(w *bytes.Buffer, table string, id int16, col string) {
w.WriteString(`"`)
w.WriteString(table)
w.WriteString(`_`)
int2string(w, id)
w.WriteString(`"."`)
w.WriteString(col)
w.WriteString(`"`)
}
func colWithTableIDAlias(w *bytes.Buffer, table string, id int16, col, alias string) {
w.WriteString(`"`)
w.WriteString(table)
w.WriteString(`_`)
int2string(w, id)
w.WriteString(`"."`)
w.WriteString(col)
w.WriteString(`" AS "`)
w.WriteString(alias)
w.WriteString(`"`)
}
func colWithTableIDSuffixAlias(w *bytes.Buffer, table string, id int16,
suffix, col, alias string) {
w.WriteString(`"`)
w.WriteString(table)
w.WriteString(`_`)
int2string(w, id)
w.WriteString(suffix)
w.WriteString(`"."`)
w.WriteString(col)
w.WriteString(`" AS "`)
w.WriteString(alias)
w.WriteString(`"`)
}
func tableIDColSuffix(w *bytes.Buffer, table string, id int16, col, suffix string) {
w.WriteString(`"`)
w.WriteString(table)
w.WriteString(`_`)
int2string(w, id)
w.WriteString(`_`)
w.WriteString(col)
w.WriteString(suffix)
w.WriteString(`"`)
}
const charset = "0123456789"
func int2string(w *bytes.Buffer, val int16) {
if val < 10 {
w.WriteByte(charset[val])
return
}
temp := int16(0)
val2 := val
for val2 > 0 {
temp *= 10
temp += val2 % 10
val2 = int16(math.Floor(float64(val2 / 10)))
}
val3 := temp
for val3 > 0 {
d := val3 % 10
val3 /= 10
w.WriteByte(charset[d])
}
}