fix where exists

parent 70827217
......@@ -35,6 +35,7 @@ const (
var (
_ plan = (*crossJoinDefaultPlan)(nil)
_ plan = (*distinctDefaultPlan)(nil)
_ plan = (*emptyFieldsPlan)(nil)
_ plan = (*explainDefaultPlan)(nil)
_ plan = (*filterDefaultPlan)(nil)
_ plan = (*fullJoinDefaultPlan)(nil)
......@@ -2820,3 +2821,16 @@ func (r *selectDummyPlan) do(ctx *execCtx, f func(id interface{}, data []interfa
_, err = f(nil, r.fields)
return
}
type emptyFieldsPlan struct {
*nullPlan
}
func (r *emptyFieldsPlan) do(ctx *execCtx, f func(id interface{}, data []interface{}) (bool, error)) (err error) {
v := make([]interface{}, len(r.fields))
for i := range v {
v[i] = ""
}
_, err = f(nil, v)
return
}
......@@ -336,6 +336,18 @@ type whereRset struct {
exists bool
}
func (r *whereRset) String() string {
s := ""
if r.sel != nil {
if r.exists {
s += " EXISTS "
}
s += "(" + strings.TrimSuffix(r.sel.String(), ";") + ")"
return s
}
return r.expr.String()
}
func (r *whereRset) planBinOp(x *binaryOperation) (plan, error) {
p := r.src
ok, cn := isColumnExpression(x.l)
......@@ -516,6 +528,33 @@ func (r *whereRset) planUnaryOp(x *unaryOperation) (plan, error) {
}
func (r *whereRset) plan(ctx *execCtx) (plan, error) {
if r.sel != nil {
var exists bool
p, err := r.sel.plan(ctx)
if err != nil {
return nil, err
}
err = p.do(ctx, func(i interface{}, data []interface{}) (bool, error) {
if len(data) > 0 {
exists = true
}
return true, nil
})
if err != nil {
return nil, err
}
if r.exists && exists {
return p, nil
}
np := &nullPlan{fields: p.fieldNames()}
return &emptyFieldsPlan{nullPlan: np}, nil
}
return r.planExpr(ctx)
}
func (r *whereRset) planExpr(ctx *execCtx) (plan, error) {
if r.expr == nil {
return &nullPlan{}, nil
}
expr, err := r.expr.clone(ctx.arg)
if err != nil {
return nil, err
......
......@@ -759,7 +759,7 @@ func (s *selectStmt) String() string {
if s.where != nil {
b.WriteString(" WHERE ")
b.WriteString(s.where.expr.String())
b.WriteString(s.where.String())
}
if s.group != nil {
b.WriteString(" GROUP BY ")
......@@ -800,7 +800,7 @@ func (s *selectStmt) plan(ctx *execCtx) (plan, error) { //LATER overlapping goro
r = &selectDummyPlan{fields: fds}
}
if w := s.where; w != nil {
if r, err = (&whereRset{expr: w.expr, src: r}).plan(ctx); err != nil {
if r, err = (&whereRset{expr: w.expr, src: r, sel: w.sel, exists: w.exists}).plan(ctx); err != nil {
return nil, err
}
}
......
......@@ -8403,3 +8403,17 @@ SELECT 42;
┌Evaluate 42 as "",
└Output field names [""]
---- 1348
SELECT * FROM t WHERE EXISTS (SELECT * FROM t WHERE i == 2);
┌Iterate all rows of table "t"
└Output field names ["i"]
┌Filter on i == 2
│Possibly useful indices
│CREATE INDEX xt_i ON t(i);
└Output field names ["i"]
---- 1349
SELECT * FROM t WHERE EXISTS (SELECT * FROM t WHERE i == 2);
┌Iterate no rows
└Output field names ["i"]
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment