001: /*
002: * Copyright 2002 (C) TJDO.
003: * All rights reserved.
004: *
005: * This software is distributed under the terms of the TJDO License version 1.0.
006: * See the terms of the TJDO License in the documentation provided with this software.
007: *
008: * $Id: FetchStatement.java,v 1.2 2002/10/17 21:00:55 pierreg0 Exp $
009: */
010:
011: package com.triactive.jdo.store;
012:
013: import java.util.ArrayList;
014: import java.util.Iterator;
015:
016: class FetchStatement {
017: protected final ClassBaseTable mainTable;
018: protected final ArrayList selected = new ArrayList();
019: protected final ArrayList super tables = new ArrayList();
020:
021: protected StringBuffer conditionList = new StringBuffer();
022:
023: public FetchStatement(ClassBaseTable mainTable) {
024: this .mainTable = mainTable;
025: }
026:
027: public int select(Column col) {
028: String columnID = referenceColumn(col);
029:
030: if (!selected.contains(columnID))
031: selected.add(columnID);
032:
033: return selected.indexOf(columnID) + 1;
034: }
035:
036: public String referenceColumn(Column col) {
037: ClassBaseTable t = (ClassBaseTable) col.getTable();
038:
039: if (!t.equals(mainTable) && !super tables.contains(t))
040: super tables.add(t);
041:
042: return t.getName().toString() + '.' + col.getName().toString();
043: }
044:
045: public void andCondition(String condition) {
046: if (conditionList.length() > 0)
047: conditionList.append(" AND ");
048:
049: conditionList.append('(').append(condition).append(')');
050: }
051:
052: public String toString() {
053: StringBuffer stmt = new StringBuffer("SELECT ");
054:
055: Iterator i = selected.iterator();
056:
057: while (i.hasNext()) {
058: stmt.append(i.next());
059:
060: if (i.hasNext())
061: stmt.append(',');
062: }
063:
064: SQLIdentifier mainTableName = mainTable.getName();
065: String mainTableColumnID = referenceColumn(mainTable
066: .getIDMapping().getColumn());
067: StringBuffer joinConditions = new StringBuffer();
068:
069: stmt.append(" FROM ").append(mainTableName);
070:
071: i = super tables.iterator();
072:
073: while (i.hasNext()) {
074: ClassBaseTable super table = (ClassBaseTable) i.next();
075: String super tableColumnID = referenceColumn(super table
076: .getIDMapping().getColumn());
077:
078: stmt.append(',').append(super table.getName());
079:
080: if (joinConditions.length() > 0)
081: joinConditions.append(" AND ");
082:
083: joinConditions.append(mainTableColumnID).append(" = ")
084: .append(super tableColumnID);
085: }
086:
087: if (joinConditions.length() > 0) {
088: if (conditionList.length() > 0)
089: conditionList = joinConditions.append(" AND (").append(
090: conditionList).append(')');
091: else
092: conditionList = joinConditions;
093: }
094:
095: if (conditionList.length() > 0)
096: stmt.append(" WHERE ").append(conditionList);
097:
098: return stmt.toString();
099: }
100: }
|