01: /*
02: * Copyright 2002 (C) TJDO.
03: * All rights reserved.
04: *
05: * This software is distributed under the terms of the TJDO License version 1.0.
06: * See the terms of the TJDO License in the documentation provided with this software.
07: *
08: * $Id: TableExprAsSubquery.java,v 1.1 2002/11/24 06:02:47 jackknifebarber Exp $
09: */
10:
11: package com.triactive.jdo.store;
12:
13: import java.util.ArrayList;
14: import java.util.Iterator;
15:
16: /**
17: * A SQL table expression that joins superclass tables by constructing a
18: * parenthesized sub-SELECT statement.
19: *
20: * @author <a href="mailto:mmartin5@austin.rr.com">Mike Martin</a>
21: * @version $Revision: 1.1 $
22: *
23: * @see QueryStatement
24: */
25:
26: class TableExprAsSubquery extends TableExpression {
27: protected final ArrayList columns = new ArrayList();
28: protected boolean multipleTablesReferenced = false;
29:
30: public TableExprAsSubquery(QueryStatement qs, Table mainTable,
31: SQLIdentifier mainRangeVar) {
32: super (qs, mainTable, mainRangeVar);
33: }
34:
35: public String referenceColumn(Column col) {
36: assertNotFrozen();
37:
38: Table table = col.getTable();
39:
40: if (!table.equals(mainTable)) {
41: if (!(mainTable instanceof ClassBaseTable)
42: || !(table instanceof ClassBaseTable))
43: throw new TableMismatchException(col, mainTable);
44:
45: /*
46: * Since both tables are ClassBaseTables we assume that the column
47: * is a superclass field, meaning 'table' is a supertable of
48: * 'mainTable'. We set the flag indicating that this expression
49: * must become a subquery that joins the necessary tables.
50: */
51:
52: multipleTablesReferenced = true;
53: }
54:
55: if (!columns.contains(col))
56: columns.add(col);
57:
58: return mainRangeVar + "." + col.getName();
59: }
60:
61: public String toString() {
62: if (sqlText == null) {
63: StringBuffer sb = new StringBuffer();
64: SQLIdentifier mainTableName = mainTable.getName();
65:
66: if (!multipleTablesReferenced) {
67: sb.append(mainTableName);
68:
69: if (!mainRangeVar.equals(mainTableName))
70: sb.append(' ').append(mainRangeVar);
71: } else {
72: FetchStatement subQuery = new FetchStatement(
73: (ClassBaseTable) mainTable);
74:
75: Iterator i = columns.iterator();
76:
77: while (i.hasNext())
78: subQuery.select((Column) i.next());
79:
80: sb.append('(').append(subQuery).append(") ").append(
81: mainRangeVar);
82: }
83:
84: sqlText = sb.toString();
85: }
86:
87: return sqlText;
88: }
89: }
|