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.engine.Session; |
9 | import org.h2.table.ColumnResolver; |
10 | import org.h2.table.TableFilter; |
11 | import org.h2.value.Value; |
12 | import org.h2.value.ValueNull; |
13 | |
14 | /** |
15 | * A NOT condition. |
16 | */ |
17 | public class ConditionNot extends Condition { |
18 | |
19 | private Expression condition; |
20 | |
21 | public ConditionNot(Expression condition) { |
22 | this.condition = condition; |
23 | } |
24 | |
25 | @Override |
26 | public Expression getNotIfPossible(Session session) { |
27 | return condition; |
28 | } |
29 | |
30 | @Override |
31 | public Value getValue(Session session) { |
32 | Value v = condition.getValue(session); |
33 | if (v == ValueNull.INSTANCE) { |
34 | return v; |
35 | } |
36 | return v.convertTo(Value.BOOLEAN).negate(); |
37 | } |
38 | |
39 | @Override |
40 | public void mapColumns(ColumnResolver resolver, int level) { |
41 | condition.mapColumns(resolver, level); |
42 | } |
43 | |
44 | @Override |
45 | public Expression optimize(Session session) { |
46 | Expression e2 = condition.getNotIfPossible(session); |
47 | if (e2 != null) { |
48 | return e2.optimize(session); |
49 | } |
50 | Expression expr = condition.optimize(session); |
51 | if (expr.isConstant()) { |
52 | Value v = expr.getValue(session); |
53 | if (v == ValueNull.INSTANCE) { |
54 | return ValueExpression.getNull(); |
55 | } |
56 | return ValueExpression.get(v.convertTo(Value.BOOLEAN).negate()); |
57 | } |
58 | condition = expr; |
59 | return this; |
60 | } |
61 | |
62 | @Override |
63 | public void setEvaluatable(TableFilter tableFilter, boolean b) { |
64 | condition.setEvaluatable(tableFilter, b); |
65 | } |
66 | |
67 | @Override |
68 | public String getSQL() { |
69 | return "(NOT " + condition.getSQL() + ")"; |
70 | } |
71 | |
72 | @Override |
73 | public void updateAggregate(Session session) { |
74 | condition.updateAggregate(session); |
75 | } |
76 | |
77 | @Override |
78 | public void addFilterConditions(TableFilter filter, boolean outerJoin) { |
79 | if (outerJoin) { |
80 | // can not optimize: |
81 | // select * from test t1 left join test t2 on t1.id = t2.id where |
82 | // not t2.id is not null |
83 | // to |
84 | // select * from test t1 left join test t2 on t1.id = t2.id and |
85 | // t2.id is not null |
86 | return; |
87 | } |
88 | super.addFilterConditions(filter, outerJoin); |
89 | } |
90 | |
91 | @Override |
92 | public boolean isEverything(ExpressionVisitor visitor) { |
93 | return condition.isEverything(visitor); |
94 | } |
95 | |
96 | @Override |
97 | public int getCost() { |
98 | return condition.getCost(); |
99 | } |
100 | |
101 | } |