Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add exists subquery support. #144

Merged
merged 15 commits into from
Sep 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 2 additions & 13 deletions expression/expressions/cmp_subquery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,6 @@ var _ = Suite(&testCompSubQuerySuite{})
type testCompSubQuerySuite struct {
}

func (s *testCompSubQuerySuite) convert(v interface{}) interface{} {
switch x := v.(type) {
case nil:
return nil
case int:
return int64(x)
}

return v
}

func (s *testCompSubQuerySuite) TestCompSubQuery(c *C) {
tbl := []struct {
lhs interface{}
Expand Down Expand Up @@ -128,11 +117,11 @@ func (s *testCompSubQuerySuite) TestCompSubQuery(c *C) {
}

for _, t := range tbl {
lhs := s.convert(t.lhs)
lhs := convert(t.lhs)

rhs := make([][]interface{}, 0, len(t.rhs))
for _, v := range t.rhs {
rhs = append(rhs, []interface{}{s.convert(v)})
rhs = append(rhs, []interface{}{convert(v)})
}

sq := newMockSubQuery(rhs, []string{"c"})
Expand Down
78 changes: 78 additions & 0 deletions expression/expressions/exists_subquery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2015 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package expressions

import (
"fmt"

"github.com/juju/errors"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/expression"
)

// ExistsSubQuery is the expression for "exists (select ...)".
// https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html
type ExistsSubQuery struct {
// Sel is the sub query.
Sel *SubQuery
}

// Clone implements the Expression Clone interface.
func (es *ExistsSubQuery) Clone() (expression.Expression, error) {
sel, err := es.Sel.Clone()
if err != nil {
return nil, errors.Trace(err)
}

return &ExistsSubQuery{Sel: sel.(*SubQuery)}, nil
}

// IsStatic implements the Expression IsStatic interface.
func (es *ExistsSubQuery) IsStatic() bool {
return es.Sel.IsStatic()
}

// String implements the Expression String interface.
func (es *ExistsSubQuery) String() string {
return fmt.Sprintf("EXISTS %s", es.Sel)
}

// Eval implements the Expression Eval interface.
func (es *ExistsSubQuery) Eval(ctx context.Context, args map[interface{}]interface{}) (interface{}, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if next returns value, we can hold this value for later Eval, so that we don't need to run sub query again.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it, my fault.

if es.Sel.Value != nil {
return true, nil
}

p, err := es.Sel.Plan(ctx)
if err != nil {
return nil, errors.Trace(err)
}
defer p.Close()

r, err := p.Next(ctx)
if err != nil {
return nil, errors.Trace(err)
}
if r != nil {
es.Sel.Value = r
return true, nil
}

return false, nil
}

// NewExistsSubQuery creates a ExistsSubQuery object.
func NewExistsSubQuery(sel *SubQuery) *ExistsSubQuery {
return &ExistsSubQuery{Sel: sel}
}
101 changes: 101 additions & 0 deletions expression/expressions/exists_subquery_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright 2015 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package expressions

import (
. "github.com/pingcap/check"
"github.com/pingcap/tidb/parser/opcode"
"github.com/pingcap/tidb/util/types"
)

var _ = Suite(&testExistsSubQuerySuite{})

type testExistsSubQuerySuite struct {
}

func (s *testExistsSubQuerySuite) TestExistsSubQuery(c *C) {
// Test exists subquery.
tbl := []struct {
in []interface{}
result int64 // 0 for false, 1 for true.
}{
{[]interface{}{1}, 1},
{[]interface{}{nil}, 1},
{[]interface{}{}, 0},
}

for _, t := range tbl {
in := make([][]interface{}, 0, len(t.in))
for _, v := range t.in {
in = append(in, []interface{}{convert(v)})
}

sq := newMockSubQuery(in, []string{"c"})
expr := NewExistsSubQuery(sq)

c.Assert(expr.IsStatic(), IsFalse)

exprc, err := expr.Clone()
c.Assert(err, IsNil)

str := exprc.String()
c.Assert(len(str), Greater, 0)

v, err := exprc.Eval(nil, nil)
c.Assert(err, IsNil)

val, err := types.ToBool(v)
c.Assert(err, IsNil)
c.Assert(val, Equals, t.result)
}

// Test not exists subquery.
tbl = []struct {
in []interface{}
result int64 // 0 for false, 1 for true.
}{
{[]interface{}{1}, 0},
{[]interface{}{nil}, 0},
{[]interface{}{}, 1},
}
for _, t := range tbl {
in := make([][]interface{}, 0, len(t.in))
for _, v := range t.in {
in = append(in, []interface{}{convert(v)})
}

sq := newMockSubQuery(in, []string{"c"})
es := NewExistsSubQuery(sq)

c.Assert(es.IsStatic(), IsFalse)

str := es.String()
c.Assert(len(str), Greater, 0)

expr := NewUnaryOperation(opcode.Not, es)

exprc, err := expr.Clone()
c.Assert(err, IsNil)

str = exprc.String()
c.Assert(len(str), Greater, 0)

v, err := exprc.Eval(nil, nil)
c.Assert(err, IsNil)

val, err := types.ToBool(v)
c.Assert(err, IsNil)
c.Assert(val, Equals, t.result)
}
}
11 changes: 10 additions & 1 deletion expression/expressions/expression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,8 @@ func (s *mockStatement) String() string {
}

type mockPlan struct {
rset *mockRecordset
rset *mockRecordset
cursor int
}

func newMockPlan(rset *mockRecordset) *mockPlan {
Expand Down Expand Up @@ -205,9 +206,17 @@ func (p *mockPlan) Filter(ctx context.Context, expr expression.Expression) (plan
}

func (p *mockPlan) Next(ctx context.Context) (row *plan.Row, err error) {
if p.cursor == len(p.rset.rows) {
return
}
row = &plan.Row{
Data: p.rset.rows[p.cursor],
}
p.cursor++
return
}

func (p *mockPlan) Close() error {
p.cursor = 0
return nil
}
8 changes: 4 additions & 4 deletions expression/expressions/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ func MentionedAggregateFuncs(e expression.Expression) []expression.Expression {

func mentionedAggregateFuncs(e expression.Expression, m *[]expression.Expression) {
switch x := e.(type) {
case Value, *Value, *Variable,
*Default, *Ident, *SubQuery, *Position:
case Value, *Value, *Variable, *Default,
*Ident, *SubQuery, *Position, *ExistsSubQuery:
// nop
case *BinaryOperation:
mentionedAggregateFuncs(x.L, m)
Expand Down Expand Up @@ -240,8 +240,8 @@ func ContainAggregateFunc(e expression.Expression) bool {

func mentionedColumns(e expression.Expression, m map[string]bool, names *[]string) {
switch x := e.(type) {
case Value, *Value, *Variable,
*Default, *SubQuery, *Position:
case Value, *Value, *Variable, *Default,
*SubQuery, *Position, *ExistsSubQuery:
// nop
case *BinaryOperation:
mentionedColumns(x.L, m, names)
Expand Down
9 changes: 9 additions & 0 deletions expression/expressions/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,12 @@ func (s *testHelperSuite) TestIsCurrentTimeExpr(c *C) {
v = IsCurrentTimeExpr(CurrentTimeExpr)
c.Assert(v, IsTrue)
}

func convert(v interface{}) interface{} {
switch x := v.(type) {
case int:
return int64(x)
}

return v
}
7 changes: 7 additions & 0 deletions expression/expressions/unary.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,13 @@ func (u *UnaryOperation) String() string {
switch u.V.(type) {
case *BinaryOperation:
return fmt.Sprintf("%s(%s)", u.Op, u.V)
case *ExistsSubQuery:
switch u.Op {
case opcode.Not:
return fmt.Sprintf("NOT %s", u.V)
default:
return fmt.Sprintf("%s%s", u.Op, u.V)
}
default:
switch u.Op {
case opcode.Not:
Expand Down
5 changes: 4 additions & 1 deletion parser/parser.y
Original file line number Diff line number Diff line change
Expand Up @@ -1764,7 +1764,10 @@ Operand:
values := append([]expression.Expression{$2.(expression.Expression)}, $4.([]expression.Expression)...)
$$ = &expressions.Row{Values: values}
}

| "EXISTS" SubSelect
{
$$ = &expressions.ExistsSubQuery{Sel: $2.(*expressions.SubQuery)}
}

OrderBy:
"ORDER" "BY" OrderByList
Expand Down
9 changes: 9 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,15 @@ func (s *testParserSuite) TestParser0(c *C) {
{"SELECT 1 > ALL (select 1)", true},
{"SELECT 1 > SOME (select 1)", true},

// For exists subquery
{"SELECT EXISTS select 1", false},
{"SELECT EXISTS (select 1)", true},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no not exists test?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add not exists test here too.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it.

{"SELECT + EXISTS (select 1)", true},
{"SELECT - EXISTS (select 1)", true},
{"SELECT NOT EXISTS (select 1)", true},
{"SELECT + NOT EXISTS (select 1)", false},
{"SELECT - NOT EXISTS (select 1)", false},

// For update statement
{"UPDATE t SET id = id + 1 ORDER BY id DESC;", true},
{"UPDATE items,month SET items.price=month.price WHERE items.id=month.id;", true},
Expand Down