1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.expression; |
7 | |
8 | import org.h2.command.dml.Query; |
9 | import org.h2.engine.Session; |
10 | import org.h2.result.LocalResult; |
11 | import org.h2.table.ColumnResolver; |
12 | import org.h2.table.TableFilter; |
13 | import org.h2.util.StringUtils; |
14 | import org.h2.value.Value; |
15 | import org.h2.value.ValueBoolean; |
16 | |
17 | /** |
18 | * An 'exists' condition as in WHERE EXISTS(SELECT ...) |
19 | */ |
20 | public class ConditionExists extends Condition { |
21 | |
22 | private final Query query; |
23 | |
24 | public ConditionExists(Query query) { |
25 | this.query = query; |
26 | } |
27 | |
28 | @Override |
29 | public Value getValue(Session session) { |
30 | query.setSession(session); |
31 | LocalResult result = query.query(1); |
32 | session.addTemporaryResult(result); |
33 | boolean r = result.getRowCount() > 0; |
34 | return ValueBoolean.get(r); |
35 | } |
36 | |
37 | @Override |
38 | public Expression optimize(Session session) { |
39 | query.prepare(); |
40 | return this; |
41 | } |
42 | |
43 | @Override |
44 | public String getSQL() { |
45 | return "EXISTS(\n" + StringUtils.indent(query.getPlanSQL(), 4, false) + ")"; |
46 | } |
47 | |
48 | @Override |
49 | public void updateAggregate(Session session) { |
50 | // TODO exists: is it allowed that the subquery contains aggregates? |
51 | // probably not |
52 | // select id from test group by id having exists (select * from test2 |
53 | // where id=count(test.id)) |
54 | } |
55 | |
56 | @Override |
57 | public void mapColumns(ColumnResolver resolver, int level) { |
58 | query.mapColumns(resolver, level + 1); |
59 | } |
60 | |
61 | @Override |
62 | public void setEvaluatable(TableFilter tableFilter, boolean b) { |
63 | query.setEvaluatable(tableFilter, b); |
64 | } |
65 | |
66 | @Override |
67 | public boolean isEverything(ExpressionVisitor visitor) { |
68 | return query.isEverything(visitor); |
69 | } |
70 | |
71 | @Override |
72 | public int getCost() { |
73 | return query.getCostAsExpression(); |
74 | } |
75 | |
76 | } |