/** * Returns a JPQL query modified according to the given tree of conditions. * @param query JPQL query * @param condition root condition. If null, the query is returned as is. */ public String processQuery(String query, @Nullable Condition condition) { if (condition == null) { return query; } QueryTransformer transformer = queryTransformerFactory.transformer(query); String joins = generateJoins(condition); String where = generateWhere(condition); if (!Strings.isNullOrEmpty(joins)) { transformer.addJoinAndWhere(joins, where); } else { transformer.addWhere(where); } return transformer.getResult(); }
protected String replaceInCollectionParam(String query, String paramName) { QueryTransformer transformer = queryTransformerFactory.transformer(query); transformer.replaceInCondition(paramName); return transformer.getResult(); }
protected String replaceCaseInsensitiveParam(String query, String paramName) { QueryTransformer transformer = queryTransformerFactory.transformer(query); transformer.handleCaseInsensitiveParam(paramName); return transformer.getResult(); }
if (!effectiveEntityName.equals(entityName)) { QueryTransformer transformer = queryTransformerFactory.transformer(result); transformer.replaceEntityName(effectiveEntityName); result = transformer.getResult(); rebuildParser = true; if (dbmsFeatures.useOrderByForPaging()) { QueryTransformer transformer = queryTransformerFactory.transformer(result); transformer.addOrderByIdIfNotExists(metadata.getTools().getPrimaryKeyName(effectiveMetaClass)); result = transformer.getResult(); rebuildParser = true; transformer.replaceWithSelectEntityVariable("tempEntityAlias"); transformer.addFirstSelectionSource(String.format("%s tempEntityAlias", nestedEntityName)); transformer.addWhereAsIs(String.format("tempEntityAlias.id = %s.id", nestedEntityPath)); transformer.addEntityInGroupBy("tempEntityAlias"); result = transformer.getResult();
/** * Apply security constraints for query to select reports available by roles and screen restrictions */ public void applySecurityPolicies(LoadContext lc, @Nullable String screen, @Nullable User user) { QueryTransformer transformer = queryTransformerFactory.transformer(lc.getQuery().getQueryString()); if (screen != null) { transformer.addWhereAsIs("r.screensIdx like :screen escape '\\'"); lc.getQuery().setParameter("screen", wrapIdxParameterForSearch(screen)); } if (user != null) { List<UserRole> userRoles = user.getUserRoles(); boolean superRole = userRoles.stream().anyMatch(userRole -> userRole.getRole().getType() == RoleType.SUPER); if (!superRole) { StringBuilder roleCondition = new StringBuilder("r.rolesIdx is null"); for (int i = 0; i < userRoles.size(); i++) { UserRole ur = userRoles.get(i); String paramName = "role" + (i + 1); roleCondition.append(" or r.rolesIdx like :").append(paramName).append(" escape '\\'"); lc.getQuery().setParameter(paramName, wrapIdxParameterForSearch(ur.getRole().getId().toString())); } transformer.addWhereAsIs(roleCondition.toString()); } } lc.getQuery().setQueryString(transformer.getResult()); }
transformer.replaceOrderBy(!asc, allSortProperties.toArray(new String[0])); return transformer.getResult(); } else { return queryString;
public void restrictByPreviousResults(UUID sessionId, int queryKey) { QueryTransformer transformer = QueryTransformerFactory.createTransformer(queryString); MetaClass metaClass = metadata.getClassNN(entityName); MetaProperty primaryKey = metadata.getTools().getPrimaryKeyProperty(metaClass); if (primaryKey == null) throw new IllegalStateException(String.format("Entity %s has no primary key", entityName)); Class type = primaryKey.getJavaType(); String entityIdField; if (UUID.class.equals(type)) { entityIdField = "entityId"; } else if (Long.class.equals(type)) { entityIdField = "longEntityId"; } else if (Integer.class.equals(type)) { entityIdField = "intEntityId"; } else if (String.class.equals(type)) { entityIdField = "stringEntityId"; } else { throw new IllegalStateException( String.format("Unsupported primary key type: %s for %s", type.getSimpleName(), entityName)); } transformer.addJoinAndWhere( ", sys$QueryResult _qr", String.format("_qr.%s = {E}.%s and _qr.sessionId = :_qr_sessionId and _qr.queryKey = %s", entityIdField, primaryKey.getName(), queryKey) ); queryString = transformer.getResult(); this.queryParams.put("_qr_sessionId", sessionId); }
protected CollectionDatasource<Entity<Object>, Object> createOptionsDataSource(MetaClass metaClass) { CollectionDatasource ds = DsBuilder.create() .setMetaClass(metaClass) .setViewName(entityView) .buildCollectionDatasource(); ds.setRefreshOnComponentValueChange(true); ((DatasourceImplementation) ds).initialized(); if (!StringUtils.isBlank(entityWhere)) { QueryTransformer transformer = QueryTransformerFactory.createTransformer( "select e from " + metaClass.getName() + " e"); transformer.addWhere(entityWhere); String q = transformer.getResult(); ds.setQuery(q); } // TODO filter ds // if (WindowParams.DISABLE_AUTO_REFRESH.getBool(datasource.getDsContext().getFrameContext())) { // if (ds instanceof CollectionDatasource.Suspendable) // ((CollectionDatasource.Suspendable) ds).refreshIfNotSuspended(); // else ds.refresh(); // } return ds; }
QueryTransformer transformer = QueryTransformerFactory.createTransformer( context.getQuery().getQueryString()); ensureDistinct = transformer.removeDistinct(); if (ensureDistinct) { context.getQuery().setQueryString(transformer.getResult()); } else { QueryTransformer transformer = QueryTransformerFactory.createTransformer(context.getQuery().getQueryString()); transformer.replaceWithCount(); context.getQuery().setQueryString(transformer.getResult());
@SuppressWarnings("unchecked") @Override public int getCount() { if (loader == null) { return container.getItems().size(); } if (loader instanceof CollectionLoader) { return (int) dataManager.getCount(((CollectionLoader) loader).createLoadContext()); } else if (loader instanceof KeyValueCollectionLoader) { ValueLoadContext context = ((KeyValueCollectionLoader) loader).createLoadContext(); QueryTransformer transformer = QueryTransformerFactory.createTransformer(context.getQuery().getQueryString()); // TODO it doesn't work for query containing scalars in select transformer.replaceWithCount(); context.getQuery().setQueryString(transformer.getResult()); context.setProperties(Collections.singletonList("cnt")); List<KeyValueEntity> list = dataManager.loadValues(context); Number count = list.get(0).getValue("cnt"); return count == null ? 0 : count.intValue(); } else { log.warn("Unsupported loader type: {}", loader.getClass().getName()); return 0; } }
transformer.replaceWithSelectId(metadata.getTools().getPrimaryKeyName(metadata.getClassNN(entityName))); transformer.removeOrderBy(); String queryString = transformer.getResult();
protected void processConstraint(QueryTransformer transformer, ConstraintData constraint, String entityName) { String join = constraint.getJoin(); String where = constraint.getWhereClause(); try { if (StringUtils.isBlank(join)) { if (!StringUtils.isBlank(where)) { transformer.addWhere(where); } } else { transformer.addJoinAndWhere(join, where); } } catch (JpqlSyntaxException e) { log.error("Syntax errors found in constraint's JPQL expressions. Entity [{}]. Constraint ID [{}].", entityName, constraint.getId(), e); throw new RowLevelSecurityException( "Syntax errors found in constraint's JPQL expressions. Please see the logs.", entityName); } catch (Exception e) { log.error("An error occurred when applying security constraint. Entity [{}]. Constraint ID [{}].", entityName, constraint.getId(), e); throw new RowLevelSecurityException( "An error occurred when applying security constraint. Please see the logs.", entityName); } }
protected void applyConstraints(Query query) { boolean constraintsApplied = security.applyConstraints(query); if (constraintsApplied && singleResult) { QueryParser parser = QueryTransformerFactory.createParser(query.getQueryString()); if (parser.isQueryWithJoins()) { QueryTransformer transformer = QueryTransformerFactory.createTransformer(query.getQueryString()); transformer.addDistinct(); query.setQueryString(transformer.getResult()); } } if (constraintsApplied && log.isDebugEnabled()) log.debug("Constraints applied: {}", printQuery(query.getQueryString())); }
@Override public boolean applyConstraints(Query query) { QueryParser parser = QueryTransformerFactory.createParser(query.getQueryString()); String entityName = parser.getEntityName(); List<ConstraintData> constraints = getConstraints(metadata.getClassNN(entityName), constraint -> constraint.getCheckType().database() && (constraint.getOperationType() == ConstraintOperationType.READ || constraint.getOperationType() == ConstraintOperationType.ALL)); if (constraints.isEmpty()) return false; QueryTransformer transformer = QueryTransformerFactory.createTransformer(query.getQueryString()); for (ConstraintData constraint : constraints) { processConstraint(transformer, constraint, entityName); } query.setQueryString(transformer.getResult()); for (String paramName : transformer.getAddedParams()) { setQueryParam(query, paramName); } return true; }
QueryTransformer transformer = queryTransformerFactory.transformer( context.getQuery().getQueryString()); ensureDistinct = transformer.removeDistinct(); if (ensureDistinct) { context.getQuery().setQueryString(transformer.getResult());
/** * Apply constraints for query to select reports which have input parameter with class matching inputValueMetaClass */ public void applyPoliciesByEntityParameters(LoadContext lc, @Nullable MetaClass inputValueMetaClass) { if (inputValueMetaClass != null) { QueryTransformer transformer = queryTransformerFactory.transformer(lc.getQuery().getQueryString()); StringBuilder parameterTypeCondition = new StringBuilder("r.inputEntityTypesIdx like :type escape '\\'"); lc.getQuery().setParameter("type", wrapIdxParameterForSearch(inputValueMetaClass.getName())); List<MetaClass> ancestors = inputValueMetaClass.getAncestors(); for (int i = 0; i < ancestors.size(); i++) { MetaClass metaClass = ancestors.get(i); String paramName = "type" + (i + 1); parameterTypeCondition.append(" or r.inputEntityTypesIdx like :").append(paramName).append(" escape '\\'"); lc.getQuery().setParameter(paramName, wrapIdxParameterForSearch(metaClass.getName())); } transformer.addWhereAsIs(String.format("(%s)", parameterTypeCondition.toString())); lc.getQuery().setQueryString(transformer.getResult()); } }
protected void setSortDirection(LoadContext.Query q) { boolean asc = Sortable.Order.ASC.equals(sortInfos[0].getOrder()); MetaPropertyPath propertyPath = sortInfos[0].getPropertyPath(); String[] sortProperties = null; if (metadata.getTools().isPersistent(propertyPath)) { sortProperties = getSortPropertiesForPersistentAttribute(propertyPath); } else { // a non-persistent attribute List<String> relProperties = metadata.getTools().getRelatedProperties(propertyPath.getMetaProperty()); if (!relProperties.isEmpty()) { List<String> sortPropertiesList = new ArrayList<>(relProperties.size()); for (String relProp : relProperties) { String[] ppCopy = Arrays.copyOf(propertyPath.getPath(), propertyPath.getPath().length); ppCopy[ppCopy.length - 1] = relProp; MetaPropertyPath relPropertyPath = propertyPath.getMetaProperties()[0].getDomain().getPropertyPath(Joiner.on(".").join(ppCopy)); String[] sortPropertiesForRelProperty = getSortPropertiesForPersistentAttribute(relPropertyPath); if (sortPropertiesForRelProperty != null) Collections.addAll(sortPropertiesList, sortPropertiesForRelProperty); } if (!sortPropertiesList.isEmpty()) sortProperties = sortPropertiesList.toArray(new String[sortPropertiesList.size()]); } } if (sortProperties != null && sortProperties.length != 0) { QueryTransformer transformer = QueryTransformerFactory.createTransformer(q.getQueryString()); transformer.replaceOrderBy(!asc, sortProperties); String jpqlQuery = transformer.getResult(); q.setQueryString(jpqlQuery); } }
public String processQuery(String query, Map<String, Object> paramValues) { Set<String> params = new HashSet<>(); for (Map.Entry<String, Object> entry : paramValues.entrySet()) { if (paramValueIsOk(entry.getValue())) params.add(entry.getKey()); } query = TemplateHelper.processTemplate(query, paramValues); if (isActual(root, params)) { Condition refined = refine(root, params); if (refined != null) { QueryTransformer transformer = QueryTransformerFactory.createTransformer(query); String where = new FilterJpqlGenerator().generateJpql(refined); if (!StringUtils.isBlank(where)) { Set<String> joins = refined.getJoins(); if (!joins.isEmpty()) { String joinsStr = joins.stream().collect(Collectors.joining(" ")); transformer.addJoinAndWhere(joinsStr, where); } else { transformer.addWhere(where); } } return transformer.getResult(); } } return query; }
QueryTransformer transformer = QueryTransformerFactory.createTransformer(baseQueryString); if (StringUtils.isNotBlank(constraint.getJoinClause())) { transformer.addJoinAndWhere(constraint.getJoinClause(), constraint.getWhereClause()); } else { transformer.addWhere(constraint.getWhereClause()); .setMaxResults(0) .buildCollectionDatasource(); datasource.setQuery(transformer.getResult()); datasource.refresh();