String varName = varSym.getQualifiedName();
if (hasSQLTableMappingForAlias(varName))
{
// Variable already found
SQLTableMapping tblMapping = getSQLTableMappingForAlias(varName);
SQLExpression sqlExpr = exprFactory.newExpression(tblMapping.table.getSQLStatement(),
tblMapping.table, tblMapping.mapping);
stack.push(sqlExpr);
return sqlExpr;
}
else if (compilation.getCompilationForSubquery(varName) != null)
{
// Subquery variable
QueryCompilation subCompilation = compilation.getCompilationForSubquery(varName);
AbstractClassMetaData subCmd = ec.getMetaDataManager().getMetaDataForClass(subCompilation.getCandidateClass(), ec.getClassLoaderResolver());
// Create subquery statement, using any provided alias if possible
String subAlias = null;
if (subCompilation.getCandidateAlias() != null && !subCompilation.getCandidateAlias().equals(candidateAlias))
{
subAlias = subCompilation.getCandidateAlias();
}
StatementResultMapping subqueryResultMapping = new StatementResultMapping();
// TODO Fix "avg(something)" arg - not essential but is a hack right now
SQLStatement subStmt = RDBMSQueryUtils.getStatementForCandidates(stmt, subCmd,
null, ec, subCompilation.getCandidateClass(), true, "avg(something)", subAlias, null);
QueryToSQLMapper sqlMapper = new QueryToSQLMapper(subStmt, subCompilation, parameters,
null, subqueryResultMapping, subCmd, fetchPlan, ec, importsDefinition, options,
extensionsByName);
sqlMapper.setParentMapper(this);
sqlMapper.compile();
if (subqueryResultMapping.getNumberOfResultExpressions() > 1)
{
throw new NucleusUserException("Number of result expressions in subquery should be 1");
}
SQLExpression subExpr = null;
// TODO Cater for subquery select of its own candidate
if (subqueryResultMapping.getNumberOfResultExpressions() == 0)
{
subExpr = new org.datanucleus.store.rdbms.sql.expression.SubqueryExpression(stmt, subStmt);
}
else
{
JavaTypeMapping subMapping =
((StatementMappingIndex)subqueryResultMapping.getMappingForResultExpression(0)).getMapping();
if (subMapping instanceof TemporalMapping)
{
subExpr = new TemporalSubqueryExpression(stmt, subStmt);
}
else if (subMapping instanceof StringMapping)
{
subExpr = new StringSubqueryExpression(stmt, subStmt);
}
else
{
subExpr = new NumericSubqueryExpression(stmt, subStmt);
}
if (subExpr.getJavaTypeMapping() == null)
{
subExpr.setJavaTypeMapping(subMapping);
}
}
stack.push(subExpr);
return subExpr;
}
else if (stmt.getParentStatement() != null && parentMapper != null &&
parentMapper.candidateAlias != null && parentMapper.candidateAlias.equals(varName))
{
// Variable in subquery linking back to parent query
SQLExpression varExpr = exprFactory.newExpression(stmt.getParentStatement(),
stmt.getParentStatement().getPrimaryTable(),
stmt.getParentStatement().getPrimaryTable().getTable().getIdMapping());
stack.push(varExpr);
return varExpr;
}