}
Map aliases = new HashMap();
List tables = new ArrayList();
for (Iterator tableIter = pQuery.getSelectTableReferences(); tableIter.hasNext(); ) {
TableReference tableReference = (TableReference) tableIter.next();
Table.Name alias = tableReference.getAlias();
if (alias != null) {
if (aliases.containsKey(alias.getName())) {
throw new NullPointerException("The alias " + alias +
" is used twice for the tables " +
((TableReference) aliases.get(alias)).getTable().getName() +
" and " + tableReference.getTable().getName());
}
aliases.put(alias.getName(), tableReference);
}
tables.add(tableReference);
}
if (tables.size() > 1) {
// Make sure that all tables have an alias
for (Iterator iter = tables.iterator(); iter.hasNext(); ) {
TableReference tableReference = (TableReference) iter.next();
if (tableReference.getAlias() == null) {
String alias = getUniqueAlias(tableReference.getTable().getName().getName(), aliases);
aliases.put(alias, tableReference);
if (!alias.equals(tableReference.getTable().getName().getName())) {
tableReference.setAlias(alias);
}
}
}
}
// Create a Map of all column names, that may be referenced.
// maps key is the column name, and the maps value is the
// number of possible references. In other words: If an entry
// in the map has a value > 1, then its column name must be
// qualified, because it is used in multiple tables.
Map columnNames = new HashMap();
for (int i = 0; i < tables.size(); i++) {
TableReference table = (TableReference) tables.get(i);
for (Iterator iter = table.getTable().getColumns(); iter.hasNext(); ) {
Column col = (Column) iter.next();
String key = col.getName().toString().toUpperCase();
Integer num = (Integer) columnNames.get(key);
if (num == null) {
num = new Integer(1);
} else {
num = new Integer(num.intValue() + 1);
}
columnNames.put(key, num);
}
}
Iterator columnIter = pQuery.getResultColumns();
if (!columnIter.hasNext()) {
sb.append(" *");
} else {
boolean first = true;
do {
ColumnReference column = (ColumnReference) columnIter.next();
if (first) {
sb.append(" ");
first = false;
} else {
sb.append(", ");
}
sb.append(getColumnAlias(columnNames, column));
} while (columnIter.hasNext());
}
if (tables.size() > 0) {
sb.append(" FROM ");
for (int i = 0; i < tables.size(); i++) {
TableReference table = (TableReference) tables.get(i);
if (i == 0) {
sb.append(getTableAlias(table));
} else {
sb.append(getJoinAlias(columnNames, (JoinReference) table));
}