use of org.datanucleus.store.query.expression.Expression in project datanucleus-rdbms by datanucleus.
the class QueryToSQLMapper method compileHaving.
/**
* Method to compile the having clause of the query into the SQLStatement.
* @param stmt SELECT statement
*/
protected void compileHaving(SelectStatement stmt) {
if (compilation.getExprHaving() != null) {
// Apply any having to the statement
compileComponent = CompilationComponent.HAVING;
Expression havingExpr = compilation.getExprHaving();
Object havingEval = havingExpr.evaluate(this);
if (!(havingEval instanceof BooleanExpression)) {
// Non-boolean having clause should be user exception
throw new NucleusUserException(Localiser.msg("021051", havingExpr));
}
stmt.setHaving((BooleanExpression) havingEval);
compileComponent = null;
}
}
use of org.datanucleus.store.query.expression.Expression in project datanucleus-rdbms by datanucleus.
the class QueryToSQLMapper method processInvokeExpression.
/**
* Internal method to handle the processing of an InvokeExpression.
* @param expr The InvokeExpression
* @param invokedSqlExpr The SQLExpression that we are invoking the method on.
* @return The resultant SQLExpression
*/
protected SQLExpression processInvokeExpression(InvokeExpression expr, SQLExpression invokedSqlExpr) {
if (invokedSqlExpr instanceof NullLiteral) {
// We cannot invoke anything on a null TODO Handle this "NPE"
NucleusLogger.QUERY.warn("Compilation of InvokeExpression needs to invoke method \"" + expr.getOperation() + "\" on " + invokedSqlExpr + " but not possible");
}
String operation = expr.getOperation();
if (invokedSqlExpr instanceof MapExpression && operation.equals("contains") && compilation.getQueryLanguage().equalsIgnoreCase(Query.LANGUAGE_JPQL)) {
// JPQL "MEMBER OF" will be passed through from generic compilation as "contains" since we don't know types at that point
operation = "containsValue";
}
// Process the arguments for invoking
List args = expr.getArguments();
List sqlExprArgs = null;
if (args != null) {
sqlExprArgs = new ArrayList<SQLExpression>();
Iterator<Expression> iter = args.iterator();
while (iter.hasNext()) {
Expression argExpr = iter.next();
if (argExpr instanceof PrimaryExpression) {
processPrimaryExpression((PrimaryExpression) argExpr);
SQLExpression argSqlExpr = stack.pop();
if (compileComponent == CompilationComponent.RESULT && operation.equalsIgnoreCase("count") && stmt.getNumberOfTableGroups() > 1) {
if (argSqlExpr.getSQLTable() == stmt.getPrimaryTable() && argSqlExpr.getJavaTypeMapping() == stmt.getPrimaryTable().getTable().getIdMapping()) {
// Result with "count(this)" and joins to other groups, so enforce distinct
argSqlExpr.distinct();
}
}
sqlExprArgs.add(argSqlExpr);
} else if (argExpr instanceof ParameterExpression) {
processParameterExpression((ParameterExpression) argExpr);
sqlExprArgs.add(stack.pop());
} else if (argExpr instanceof InvokeExpression) {
processInvokeExpression((InvokeExpression) argExpr);
sqlExprArgs.add(stack.pop());
} else if (argExpr instanceof Literal) {
processLiteral((Literal) argExpr);
sqlExprArgs.add(stack.pop());
} else if (argExpr instanceof DyadicExpression) {
// Evaluate using this evaluator
argExpr.evaluate(this);
sqlExprArgs.add(stack.pop());
} else if (argExpr instanceof VariableExpression) {
processVariableExpression((VariableExpression) argExpr);
sqlExprArgs.add(stack.pop());
} else if (argExpr instanceof CaseExpression) {
processCaseExpression((CaseExpression) argExpr);
sqlExprArgs.add(stack.pop());
} else {
throw new NucleusException("Dont currently support invoke expression argument " + argExpr);
}
}
if (operation.equals("INDEX")) {
// Special case of index expression
List<Expression> indexArgs = expr.getArguments();
if (indexArgs == null || indexArgs.size() > 1) {
throw new NucleusException("Can only use INDEX with single argument");
}
PrimaryExpression indexExpr = (PrimaryExpression) indexArgs.get(0);
String joinAlias = indexExpr.getId();
String collExprName = joinAlias;
if (explicitJoinPrimaryByAlias != null) {
collExprName = explicitJoinPrimaryByAlias.get(joinAlias);
if (collExprName == null) {
throw new NucleusException("Unable to locate primary expression for alias " + joinAlias);
}
}
// Find an expression for the collection field
List<String> tuples = new ArrayList<>();
StringTokenizer primTokenizer = new StringTokenizer(collExprName, ".");
while (primTokenizer.hasMoreTokens()) {
String token = primTokenizer.nextToken();
tuples.add(token);
}
PrimaryExpression collPrimExpr = new PrimaryExpression(tuples);
processPrimaryExpression(collPrimExpr);
SQLExpression collSqlExpr = stack.pop();
sqlExprArgs.add(collSqlExpr);
}
}
// Invoke the method
SQLExpression sqlExpr = null;
if (invokedSqlExpr instanceof org.datanucleus.store.rdbms.sql.expression.SubqueryExpression) {
if (operation.equalsIgnoreCase("isEmpty")) {
// Special case of {subquery}.isEmpty(), equates to "NOT EXISTS (subquery)"
org.datanucleus.store.rdbms.sql.expression.SubqueryExpression subquerySqlExpr = (org.datanucleus.store.rdbms.sql.expression.SubqueryExpression) invokedSqlExpr;
SQLStatement subStmt = subquerySqlExpr.getSubqueryStatement();
SQLExpression subqueryNotExistsExpr = new BooleanSubqueryExpression(stmt, "EXISTS", subStmt).not();
stack.push(subqueryNotExistsExpr);
return subqueryNotExistsExpr;
} else if (operation.equalsIgnoreCase("size")) {
// {subquery}.size() should simply be changed to have a subquery of "SELECT COUNT(*) FROM ..."
throw new NucleusUserException("Attempt to invoke method `" + operation + "` on Subquery. This is not supported. Change the subquery to return COUNT() instead.");
}
throw new NucleusUserException("Attempt to invoke method `" + operation + "` on Subquery. This is not supported");
}
if (invokedSqlExpr != null) {
sqlExpr = invokedSqlExpr.invoke(operation, sqlExprArgs);
} else {
sqlExpr = exprFactory.invokeMethod(stmt, null, operation, null, sqlExprArgs);
}
stack.push(sqlExpr);
return sqlExpr;
}
use of org.datanucleus.store.query.expression.Expression in project datanucleus-rdbms by datanucleus.
the class QueryToSQLMapper method processCreatorExpression.
/* (non-Javadoc)
* @see org.datanucleus.query.evaluator.AbstractExpressionEvaluator#processCreatorExpression(org.datanucleus.query.expression.CreatorExpression)
*/
@Override
protected Object processCreatorExpression(CreatorExpression expr) {
String className = expr.getId();
Class cls = null;
try {
cls = clr.classForName(className);
} catch (ClassNotResolvedException cnre) {
if (importsDefinition != null) {
cls = importsDefinition.resolveClassDeclaration(className, clr, null);
}
}
List<SQLExpression> ctrArgExprs = null;
List<String> ctrArgAliases = null;
boolean hasAliases = false;
List args = expr.getArguments();
if (args != null) {
Class[] ctrArgTypes = new Class[args.size()];
boolean[] ctrArgTypeCheck = new boolean[args.size()];
ctrArgExprs = new ArrayList<>(args.size());
ctrArgAliases = new ArrayList<>(args.size());
Iterator iter = args.iterator();
int i = 0;
while (iter.hasNext()) {
Expression argExpr = (Expression) iter.next();
String argAlias = argExpr.getAlias();
if (argAlias != null) {
hasAliases = true;
}
SQLExpression sqlExpr = (SQLExpression) evaluate(argExpr);
// TODO Cater for "SQL_function" mapping on to ANY type of constructor argument at that position since we don't know the precise type
if (argExpr instanceof InvokeExpression && ((InvokeExpression) argExpr).getOperation().equalsIgnoreCase("SQL_function")) {
ctrArgTypeCheck[i] = false;
} else {
ctrArgTypeCheck[i] = true;
}
ctrArgExprs.add(sqlExpr);
ctrArgAliases.add(argAlias != null ? argAlias : "####");
if (sqlExpr instanceof NewObjectExpression) {
ctrArgTypes[i] = ((NewObjectExpression) sqlExpr).getNewClass();
} else if (sqlExpr.getJavaTypeMapping() instanceof DatastoreIdMapping || sqlExpr.getJavaTypeMapping() instanceof PersistableMapping) {
ctrArgTypes[i] = clr.classForName(sqlExpr.getJavaTypeMapping().getType());
} else {
ctrArgTypes[i] = sqlExpr.getJavaTypeMapping().getJavaType();
}
i++;
}
// Check that this class has the required constructor
Constructor ctr = ClassUtils.getConstructorWithArguments(cls, ctrArgTypes, ctrArgTypeCheck);
if (ctr == null) {
throw new NucleusUserException(Localiser.msg("021033", className, StringUtils.objectArrayToString(ctrArgTypes)));
}
}
// TODO Retain the selected constructor (above)
NewObjectExpression newExpr = new NewObjectExpression(stmt, cls, ctrArgExprs);
if (hasAliases) {
newExpr.setArgAliases(ctrArgAliases);
}
stack.push(newExpr);
return newExpr;
}
use of org.datanucleus.store.query.expression.Expression in project datanucleus-rdbms by datanucleus.
the class JPQLQuery method compileQueryUpdate.
/**
* Method to compile the query for RDBMS for a bulk update.
* @param parameterValues The parameter values (if any)
* @param candidateCmd Meta-data for the candidate class
*/
protected void compileQueryUpdate(Map parameterValues, AbstractClassMetaData candidateCmd) {
Expression[] updateExprs = compilation.getExprUpdate();
if (updateExprs == null || updateExprs.length == 0) {
// Nothing to update
return;
}
// Generate statement for candidate and related classes in this inheritance tree
RDBMSStoreManager storeMgr = (RDBMSStoreManager) getStoreManager();
DatastoreClass candidateTbl = storeMgr.getDatastoreClass(candidateCmd.getFullClassName(), clr);
if (candidateTbl == null) {
// TODO Using subclass-table, so find the table(s) it can be persisted into
throw new NucleusDataStoreException("Bulk update of " + candidateCmd.getFullClassName() + " not supported since candidate has no table of its own");
}
// Find tables potentially affected by this UPDATE statement
List<BulkTable> tables = new ArrayList<>();
tables.add(new BulkTable(candidateTbl, true));
if (candidateTbl.getSuperDatastoreClass() != null) {
DatastoreClass tbl = candidateTbl;
while (tbl.getSuperDatastoreClass() != null) {
tbl = tbl.getSuperDatastoreClass();
tables.add(new BulkTable(tbl, false));
}
}
List<SQLStatement> stmts = new ArrayList<>();
List<Boolean> stmtCountFlags = new ArrayList<>();
for (BulkTable bulkTable : tables) {
// Generate statement for candidate
DatastoreClass table = bulkTable.table;
Map<String, Object> extensions = null;
if (!storeMgr.getDatastoreAdapter().supportsOption(DatastoreAdapter.UPDATE_DELETE_STATEMENT_ALLOW_TABLE_ALIAS_IN_WHERE_CLAUSE)) {
extensions = new HashMap<>();
extensions.put(SQLStatement.EXTENSION_SQL_TABLE_NAMING_STRATEGY, "table-name");
}
UpdateStatement stmt = new UpdateStatement(storeMgr, table, null, null, extensions);
stmt.setClassLoaderResolver(clr);
stmt.setCandidateClassName(candidateCmd.getFullClassName());
JavaTypeMapping multitenancyMapping = table.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false);
if (multitenancyMapping != null) {
// Multi-tenancy restriction
SQLExpression tenantExpr = stmt.getSQLExpressionFactory().newExpression(stmt, stmt.getPrimaryTable(), multitenancyMapping);
SQLExpression tenantVal = stmt.getSQLExpressionFactory().newLiteral(stmt, multitenancyMapping, ec.getTenantId());
stmt.whereAnd(tenantExpr.eq(tenantVal), true);
}
// TODO Discriminator restriction?
JavaTypeMapping softDeleteMapping = table.getSurrogateMapping(SurrogateColumnType.SOFTDELETE, false);
if (softDeleteMapping != null) {
// Soft-delete restriction
SQLExpression softDeleteExpr = stmt.getSQLExpressionFactory().newExpression(stmt, stmt.getPrimaryTable(), softDeleteMapping);
SQLExpression softDeleteVal = stmt.getSQLExpressionFactory().newLiteral(stmt, softDeleteMapping, Boolean.FALSE);
stmt.whereAnd(softDeleteExpr.eq(softDeleteVal), true);
}
Set<String> options = new HashSet<>();
options.add(QueryToSQLMapper.OPTION_CASE_INSENSITIVE);
options.add(QueryToSQLMapper.OPTION_EXPLICIT_JOINS);
if (// Default to false for "IS NULL" with null param
getBooleanExtensionProperty(EXTENSION_USE_IS_NULL_WHEN_EQUALS_NULL_PARAM, false)) {
options.add(QueryToSQLMapper.OPTION_NULL_PARAM_USE_IS_NULL);
}
QueryToSQLMapper sqlMapper = new QueryToSQLMapper(stmt, compilation, parameterValues, null, null, candidateCmd, subclasses, getFetchPlan(), ec, null, options, extensions);
setMapperJoinTypes(sqlMapper);
sqlMapper.compile();
if (stmt.hasUpdates()) {
stmts.add(stmt);
stmtCountFlags.add(bulkTable.useInCount);
datastoreCompilation.setStatementParameters(stmt.getSQLText().getParametersForStatement());
datastoreCompilation.setPrecompilable(sqlMapper.isPrecompilable());
}
}
datastoreCompilation.clearStatements();
Iterator<SQLStatement> stmtIter = stmts.iterator();
Iterator<Boolean> stmtCountFlagsIter = stmtCountFlags.iterator();
while (stmtIter.hasNext()) {
SQLStatement stmt = stmtIter.next();
Boolean useInCount = stmtCountFlagsIter.next();
if (stmts.size() == 1) {
useInCount = true;
}
datastoreCompilation.addStatement(stmt, stmt.getSQLText().toSQL(), useInCount);
}
}
Aggregations