/** INTERNAL: Find the alias for a given table */
  public DatabaseTable aliasForTable(DatabaseTable table) {
    DatabaseMapping mapping = getMapping();
    if (isAttribute()
        || ((mapping != null)
            && (mapping.isAggregateObjectMapping() || mapping.isTransformationMapping()))) {
      return ((DataExpression) getBaseExpression()).aliasForTable(table);
    }

    // "ref" and "structure" mappings, no table printed in the FROM clause, need to get the table
    // alias form the parent table
    if ((mapping != null) && (mapping.isReferenceMapping() || mapping.isStructureMapping())) {
      DatabaseTable alias =
          getBaseExpression().aliasForTable(mapping.getDescriptor().getTables().firstElement());
      alias.setName(alias.getName() + "." + mapping.getField().getName());
      return alias;
    }

    // For direct-collection mappings the alias is store on the table expression.
    if ((mapping != null) && (mapping.isDirectCollectionMapping())) {
      if (tableAliases != null) {
        DatabaseTable aliasedTable = tableAliases.keyAtValue(table);
        if (aliasedTable != null) {
          return aliasedTable;
        }
      }
      return getTable(table).aliasForTable(table);
    }

    return super.aliasForTable(table);
  }