01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.expression;
07:
08: import java.sql.SQLException;
09:
10: import org.h2.command.dml.Query;
11: import org.h2.engine.Session;
12: import org.h2.result.LocalResult;
13: import org.h2.table.ColumnResolver;
14: import org.h2.table.TableFilter;
15: import org.h2.value.Value;
16: import org.h2.value.ValueBoolean;
17:
18: /**
19: * An 'exists' condition as in WHERE EXISTS(SELECT ...)
20: */
21: public class ConditionExists extends Condition {
22:
23: private final Query query;
24:
25: public ConditionExists(Query query) {
26: this .query = query;
27: }
28:
29: public Value getValue(Session session) throws SQLException {
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: public Expression optimize(Session session) throws SQLException {
38: query.prepare();
39: return this ;
40: }
41:
42: public String getSQL() {
43: StringBuffer buff = new StringBuffer();
44: buff.append("EXISTS(");
45: buff.append(query.getPlanSQL());
46: buff.append(")");
47: return buff.toString();
48: }
49:
50: public void updateAggregate(Session session) {
51: // TODO exists: is it allowed that the subquery contains aggregates?
52: // probably not
53: // select id from test group by id having exists (select * from test2
54: // where id=count(test.id))
55: }
56:
57: public void mapColumns(ColumnResolver resolver, int level)
58: throws SQLException {
59: query.mapColumns(resolver, level + 1);
60: }
61:
62: public void setEvaluatable(TableFilter tableFilter, boolean b) {
63: query.setEvaluatable(tableFilter, b);
64: }
65:
66: public boolean isEverything(ExpressionVisitor visitor) {
67: return query.isEverything(visitor);
68: }
69:
70: public int getCost() {
71: return 10 + (int) (10 * query.getCost());
72: }
73:
74: }
|