-
Notifications
You must be signed in to change notification settings - Fork 1
/
union.go
304 lines (276 loc) · 8.27 KB
/
union.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2016 The Cockroach Authors.
//
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package sql
import (
"fmt"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
)
// UnionClause constructs a planNode from a UNION/INTERSECT/EXCEPT expression.
func (p *planner) UnionClause(
ctx context.Context, n *parser.UnionClause, desiredTypes []parser.Type,
) (planNode, error) {
var emitAll = false
var emit unionNodeEmit
switch n.Type {
case parser.UnionOp:
if n.All {
emitAll = true
} else {
emit = make(unionNodeEmitDistinct)
}
case parser.IntersectOp:
if n.All {
emit = make(intersectNodeEmitAll)
} else {
emit = make(intersectNodeEmitDistinct)
}
case parser.ExceptOp:
if n.All {
emit = make(exceptNodeEmitAll)
} else {
emit = make(exceptNodeEmitDistinct)
}
default:
return nil, errors.Errorf("%v is not supported", n.Type)
}
left, err := p.newPlan(ctx, n.Left, desiredTypes)
if err != nil {
return nil, err
}
right, err := p.newPlan(ctx, n.Right, desiredTypes)
if err != nil {
return nil, err
}
leftColumns := planColumns(left)
rightColumns := planColumns(right)
if len(leftColumns) != len(rightColumns) {
return nil, fmt.Errorf("each %v query must have the same number of columns: %d vs %d",
n.Type, len(leftColumns), len(rightColumns))
}
for i := 0; i < len(leftColumns); i++ {
l := leftColumns[i]
r := rightColumns[i]
// TODO(dan): This currently checks whether the types are exactly the same,
// but Postgres is more lenient:
// http://www.postgresql.org/docs/9.5/static/typeconv-union-case.html.
if !(l.Typ.Equivalent(r.Typ) || l.Typ == parser.TypeNull || r.Typ == parser.TypeNull) {
return nil, fmt.Errorf("%v types %s and %s cannot be matched", n.Type, l.Typ, r.Typ)
}
if l.Hidden != r.Hidden {
return nil, fmt.Errorf("%v types cannot be matched", n.Type)
}
}
node := &unionNode{
right: right,
left: left,
emitAll: emitAll,
emit: emit,
scratch: make([]byte, 0),
}
return node, nil
}
// unionNode is a planNode whose rows are the result of one of three set
// operations (UNION, INTERSECT, or EXCEPT) on left and right. There are two
// variations of each set operation: distinct, which always returns unique
// results, and all, which does no uniqueing.
//
// Ordering of rows is expected to be handled externally to unionNode.
// TODO(dan): In the long run, this is insufficient. If we know both left and
// right are ordered the same way, we can do the set logic without the map
// state. Additionally, if the unionNode has an ordering then we can hint it
// down to left and right and force the condition for this first optimization.
//
// All six of the operations can be completed without cacheing rows by iterating
// one side then the other and keeping counts of unique rows in a map. Because
// EXCEPT needs to iterate the right side first, and the other two don't care,
// we always read right before left.
//
// The emit logic for each op is represented by implementors of the
// unionNodeEmit interface. The emitRight method is called for each row output
// by the right side and passed a hashable representation of the row. If it
// returns true, the row is emitted. After all right rows are examined, then
// each left row is passed to emitLeft in the same way.
//
// An example: intersectNodeEmitAll
// VALUES (1), (1), (1), (2), (2) INTERSECT ALL VALUES (1), (3), (1)
// ----
// 1
// 1
// There are three 1s on the left and two 1s on the right, so we emit 1, 1.
// Nothing else is in both.
// emitRight: For each row, increment the map entry.
// emitLeft: For each row, if the row is not present in the map, it was not in
// both, don't emit. Otherwise, if the count for the row was > 0, emit and
// decrement the entry. Otherwise, the row was on the right, but we've
// already emitted as many as were on the right, don't emit.
type unionNode struct {
right, left planNode
emitAll bool // emitAll is a performance optimization for UNION ALL.
emit unionNodeEmit
scratch []byte
}
func (n *unionNode) Values() parser.Datums {
if n.right != nil {
return n.right.Values()
}
if n.left != nil {
return n.left.Values()
}
return nil
}
func (n *unionNode) readRight(params runParams) (bool, error) {
next, err := n.right.Next(params)
for ; next; next, err = n.right.Next(params) {
if n.emitAll {
return true, nil
}
n.scratch = n.scratch[:0]
if n.scratch, err = sqlbase.EncodeDatums(n.scratch, n.right.Values()); err != nil {
return false, err
}
// TODO(dan): Sending the entire encodeDTuple to be stored in the map would
// use a lot of memory for big rows or big resultsets. Consider using a hash
// of the bytes instead.
if n.emit.emitRight(n.scratch) {
return true, nil
}
}
if err != nil {
return false, err
}
n.right.Close(params.ctx)
n.right = nil
return n.readLeft(params)
}
func (n *unionNode) readLeft(params runParams) (bool, error) {
next, err := n.left.Next(params)
for ; next; next, err = n.left.Next(params) {
if n.emitAll {
return true, nil
}
n.scratch = n.scratch[:0]
if n.scratch, err = sqlbase.EncodeDatums(n.scratch, n.left.Values()); err != nil {
return false, err
}
if n.emit.emitLeft(n.scratch) {
return true, nil
}
}
if err != nil {
return false, err
}
n.left.Close(params.ctx)
n.left = nil
return false, nil
}
func (n *unionNode) Start(params runParams) error {
if err := n.right.Start(params); err != nil {
return err
}
return n.left.Start(params)
}
func (n *unionNode) Next(params runParams) (bool, error) {
if err := params.p.cancelChecker.Check(); err != nil {
return false, err
}
if n.right != nil {
return n.readRight(params)
}
if n.left != nil {
return n.readLeft(params)
}
return false, nil
}
func (n *unionNode) Close(ctx context.Context) {
if n.right != nil {
n.right.Close(ctx)
n.right = nil
}
if n.left != nil {
n.left.Close(ctx)
n.left = nil
}
}
// unionNodeEmit represents the emitter logic for one of the six combinations of
// UNION/INTERSECT/EXCEPT and ALL/DISTINCT. As right and then left are iterated,
// state is kept and used to compute the set operation as well as distinctness.
type unionNodeEmit interface {
emitRight([]byte) bool
emitLeft([]byte) bool
}
type unionNodeEmitDistinct map[string]int
type intersectNodeEmitAll map[string]int
type intersectNodeEmitDistinct map[string]int
type exceptNodeEmitAll map[string]int
type exceptNodeEmitDistinct map[string]int
// NB: the compiler optimizes out the string allocation in
// `myMap[string(myBytes)]`. See:
// https://github.com/golang/go/commit/f5f5a8b6209f84961687d993b93ea0d397f5d5bf
func (e unionNodeEmitDistinct) emitRight(b []byte) bool {
_, ok := e[string(b)]
e[string(b)] = 1
return !ok
}
func (e unionNodeEmitDistinct) emitLeft(b []byte) bool {
_, ok := e[string(b)]
e[string(b)] = 1
return !ok
}
func (e intersectNodeEmitAll) emitRight(b []byte) bool {
e[string(b)]++
return false
}
func (e intersectNodeEmitAll) emitLeft(b []byte) bool {
if v, ok := e[string(b)]; ok && v > 0 {
e[string(b)]--
return true
}
return false
}
func (e intersectNodeEmitDistinct) emitRight(b []byte) bool {
e[string(b)]++
return false
}
func (e intersectNodeEmitDistinct) emitLeft(b []byte) bool {
if v, ok := e[string(b)]; ok && v > 0 {
e[string(b)] = 0
return true
}
return false
}
func (e exceptNodeEmitAll) emitRight(b []byte) bool {
e[string(b)]++
return false
}
func (e exceptNodeEmitAll) emitLeft(b []byte) bool {
if v, ok := e[string(b)]; ok && v > 0 {
e[string(b)]--
return false
}
return true
}
func (e exceptNodeEmitDistinct) emitRight(b []byte) bool {
e[string(b)]++
return false
}
func (e exceptNodeEmitDistinct) emitLeft(b []byte) bool {
if _, ok := e[string(b)]; !ok {
e[string(b)] = 0
return true
}
return false
}