use of org.adempiere.ad.expression.api.IStringExpression in project metasfresh-webui-api by metasfresh.
the class SqlViewSelectData method selectRowIdsByIdPageBuilder.
@Builder(builderMethodName = "selectRowIdsByPage", builderClassName = "SelectRowIdsByPageBuilder")
private SqlAndParams selectRowIdsByIdPageBuilder(@NonNull final ViewEvaluationCtx viewEvalCtx, @NonNull final ViewId viewId, final int firstRowZeroBased, final int pageLength) {
Check.assume(firstRowZeroBased >= 0, "firstRow >= 0 but it was {}", firstRowZeroBased);
Check.assume(pageLength > 0, "pageLength > 0 but it was {}", pageLength);
final String viewSelectionId = viewId.getViewId();
// NOTE: firstRow is 0-based while SeqNo are 1-based
final int firstSeqNo = firstRowZeroBased + 1;
final int lastSeqNo = firstRowZeroBased + pageLength;
final IStringExpression sqlSelectRowIdsByPage = getSqlSelectRowIdsByPage();
final String sql = sqlSelectRowIdsByPage.evaluate(viewEvalCtx.toEvaluatee(), OnVariableNotFound.Fail);
return SqlAndParams.of(sql, viewSelectionId, firstSeqNo, lastSeqNo);
}
use of org.adempiere.ad.expression.api.IStringExpression in project metasfresh-webui-api by metasfresh.
the class SqlViewSelectionQueryBuilder method buildSqlCreateSelectionFromSelectionLines.
public SqlAndParams buildSqlCreateSelectionFromSelectionLines(final ViewEvaluationCtx viewEvalCtx, final ViewId newViewId, final List<DocumentQueryOrderBy> orderBys) {
final String lineTableName = getTableName();
final String lineTableAlias = getTableAlias();
final SqlViewKeyColumnNamesMap keyColumnNamesMap = getSqlViewKeyColumnNamesMap();
final String lineKeyColumnName = keyColumnNamesMap.getSingleKeyColumnName();
final SqlOrderByBindings sqlOrderByBindings = fieldName -> {
if (keyColumnNamesMap.isKeyPartFieldName(fieldName)) {
return ConstantStringExpression.of("sl." + keyColumnNamesMap.getWebuiSelectionColumnNameForKeyColumnName(fieldName));
} else if (isGroupBy(fieldName)) {
return getFieldOrderBy(fieldName);
} else if (isAggregated(fieldName)) {
return ConstantStringExpression.of(getSqlAggregatedColumn(fieldName));
} else {
// shall not happen
return null;
}
};
final List<DocumentQueryOrderBy> orderBysEffective = orderBys.stream().flatMap(this::flatMapEffectiveFieldNames).filter(orderBy -> keyColumnNamesMap.isKeyPartFieldName(orderBy.getFieldName()) || isGroupBy(orderBy.getFieldName()) || isAggregated(orderBy.getFieldName())).collect(ImmutableList.toImmutableList());
final IStringExpression sqlOrderByExpr = SqlDocumentOrderByBuilder.newInstance(sqlOrderByBindings).buildSqlOrderBy(orderBysEffective);
final String sqlOrderBy;
if (sqlOrderByExpr == null || sqlOrderByExpr.isNullExpression()) {
sqlOrderBy = keyColumnNamesMap.getWebuiSelectionColumnNamesCommaSeparated("sl");
} else {
sqlOrderBy = sqlOrderByExpr.evaluate(viewEvalCtx.toEvaluatee(), OnVariableNotFound.Fail);
}
final String sqlFrom = "SELECT " + "\n sl." + I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID + "\n, " + keyColumnNamesMap.getWebuiSelectionColumnNamesCommaSeparated("sl") + "\n FROM " + I_T_WEBUI_ViewSelectionLine.Table_Name + " sl " + "\n INNER JOIN " + lineTableName + " " + lineTableAlias + " ON (" + lineTableAlias + "." + lineKeyColumnName + " = sl." + I_T_WEBUI_ViewSelectionLine.COLUMNNAME_Line_ID + // join lines
")" + "\n WHERE " + I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID + "=?" + "\n GROUP BY " + "\n sl." + I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID + "\n, " + keyColumnNamesMap.getWebuiSelectionColumnNamesCommaSeparated("sl") + "\n, " + getGroupByFieldNamesCommaSeparated() + "\n ORDER BY " + sqlOrderBy;
final String sqlCreateSelectionFromLines = "INSERT INTO " + I_T_WEBUI_ViewSelection.Table_Name + "(" + "\n " + I_T_WEBUI_ViewSelection.COLUMNNAME_UUID + "\n, " + keyColumnNamesMap.getWebuiSelectionColumnNamesCommaSeparated() + "\n, " + // SeqNo
I_T_WEBUI_ViewSelection.COLUMNNAME_Line + "\n)" + "\n SELECT " + "\n sl." + I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID + "\n , " + keyColumnNamesMap.getWebuiSelectionColumnNamesCommaSeparated("sl") + // SeqNo
"\n , row_number() OVER ()" + "\n FROM (" + sqlFrom + ") sl";
final List<Object> sqlCreateSelectionFromLinesParams = Arrays.asList(newViewId.getViewId());
return SqlAndParams.of(sqlCreateSelectionFromLines, sqlCreateSelectionFromLinesParams);
}
use of org.adempiere.ad.expression.api.IStringExpression in project metasfresh-webui-api by metasfresh.
the class BoardDescriptorRepository method retrieveCards.
private List<BoardCard> retrieveCards(final int boardId, final Collection<Integer> onlyCardIds) {
final BoardDescriptor boardDescriptor = getBoardDescriptor(boardId);
final String keyColumnName = boardDescriptor.getKeyColumnName();
final String userIdColumnName = boardDescriptor.getUserIdColumnName();
//
final List<Object> sqlParams = new ArrayList<>();
final CompositeStringExpression.Builder sqlExpr;
{
final IStringExpression sqlSelectDocument = buildSqlSelectDocument(boardDescriptor);
final String tableAlias = "r";
final String keyColumnNameFQ = tableAlias + "." + keyColumnName;
final String userIdColumnNameFQ = tableAlias + "." + userIdColumnName;
final SqlLookupDescriptor documentLookup = SqlLookupDescriptor.cast(boardDescriptor.getDocumentLookupDescriptorProvider().provideForScope(LookupScope.DocumentField));
sqlExpr = IStringExpression.composer().append("SELECT ").append("\n a." + I_WEBUI_Board_RecordAssignment.COLUMNNAME_WEBUI_Board_Lane_ID).append("\n, a." + I_WEBUI_Board_RecordAssignment.COLUMNNAME_Record_ID).append("\n, (").append(documentLookup.getSqlForFetchingDisplayNameByIdExpression(keyColumnNameFQ)).append(") AS card$caption").append("\n, u." + I_AD_User.COLUMNNAME_AD_User_ID + " AS card$user_id").append("\n, u." + I_AD_User.COLUMNNAME_Avatar_ID + " AS card$user_avatar_id").append("\n, u." + I_AD_User.COLUMNNAME_Name + " AS card$user_fullname").append(// all exported document fields
"\n, " + tableAlias + ".*").append("\n FROM ").append(I_WEBUI_Board_RecordAssignment.Table_Name).append(" a").append("\n INNER JOIN (").append(sqlSelectDocument).append(") " + tableAlias + " ON (" + keyColumnNameFQ + " =a." + I_WEBUI_Board_RecordAssignment.COLUMNNAME_Record_ID + ")").append("\n LEFT OUTER JOIN " + I_AD_User.Table_Name + " u ON (u." + I_AD_User.COLUMNNAME_AD_User_ID + " = " + userIdColumnNameFQ + ")").append("\n WHERE ").append("\n a." + I_WEBUI_Board_RecordAssignment.COLUMNNAME_WEBUI_Board_ID + "=?");
sqlParams.add(boardId);
if (!onlyCardIds.isEmpty()) {
sqlExpr.append("\n AND ").append(DB.buildSqlList(I_WEBUI_Board_RecordAssignment.COLUMNNAME_Record_ID, onlyCardIds, sqlParams));
}
}
final String sql = sqlExpr.build().evaluate(Evaluatees.empty(), OnVariableNotFound.Fail);
return retrieveCardsFromSql(sql, sqlParams, boardDescriptor);
}
use of org.adempiere.ad.expression.api.IStringExpression in project metasfresh-webui-api by metasfresh.
the class KPIDataLoader method loadData.
private void loadData(final KPIDataResult.Builder data, final TimeRange timeRange) {
logger.trace("Loading data for {}", timeRange);
//
// Create query evaluation context
final Evaluatee evalCtx = Evaluatees.mapBuilder().put("MainFromMillis", data.getRange().getFromMillis()).put("MainToMillis", data.getRange().getToMillis()).put("FromMillis", timeRange.getFromMillis()).put("ToMillis", timeRange.getToMillis()).build().andComposeWith(Evaluatees.ofCtx(Env.getCtx()));
//
// Resolve esQuery's variables
final IStringExpression esQuery = kpi.getESQuery();
final String esQueryParsed = esQuery.evaluate(evalCtx, OnVariableNotFound.Preserve);
//
// Execute the query
final SearchResponse response;
try {
logger.trace("Executing: \n{}", esQueryParsed);
response = elasticsearchClient.prepareSearch(kpi.getESSearchIndex()).setTypes(kpi.getESSearchTypes()).setSource(esQueryParsed).get();
logger.trace("Got response: \n{}", response);
} catch (final NoNodeAvailableException e) {
// elastic search transport error => nothing to do about it
throw e;
} catch (final Exception e) {
throw new AdempiereException("Failed executing query for " + this + ": " + e.getLocalizedMessage() + "\nQuery: " + esQueryParsed, e);
}
// Fetch data
try {
final List<Aggregation> aggregations = response.getAggregations().asList();
for (final Aggregation agg : aggregations) {
if (agg instanceof MultiBucketsAggregation) {
final String aggName = agg.getName();
final MultiBucketsAggregation multiBucketsAggregation = (MultiBucketsAggregation) agg;
for (final Bucket bucket : multiBucketsAggregation.getBuckets()) {
final Object key = dataSetValueKeyExtractor.apply(bucket, timeRange);
for (final KPIField field : kpi.getFields()) {
final Object value = field.getBucketValueExtractor().extractValue(aggName, bucket);
final Object jsonValue = formatValue(field, value);
if (jsonValue == null) {
continue;
}
final String fieldName = fieldNameExtractor.apply(field, timeRange);
data.putValue(aggName, key, fieldName, jsonValue);
}
//
// Make sure the groupByField's value is present in our dataSet value.
// If not exist, we can use the key as it's value.
final KPIField groupByField = kpi.getGroupByFieldOrNull();
if (groupByField != null) {
data.putValueIfAbsent(aggName, key, groupByField.getFieldName(), key);
}
}
} else if (agg instanceof NumericMetricsAggregation.SingleValue) {
final NumericMetricsAggregation.SingleValue singleValueAggregation = (NumericMetricsAggregation.SingleValue) agg;
// N/A
final String key = "NO_KEY";
for (final KPIField field : kpi.getFields()) {
final Object value;
if ("value".equals(field.getESPathAsString())) {
value = singleValueAggregation.value();
} else {
throw new IllegalStateException("Only ES path ending with 'value' allowed for field: " + field);
}
final Object jsonValue = field.convertValueToJson(value);
data.putValue(agg.getName(), key, field.getFieldName(), jsonValue);
}
} else {
new AdempiereException("Aggregation type not supported: " + agg.getClass()).throwIfDeveloperModeOrLogWarningElse(logger);
}
}
} catch (final Exception e) {
throw new AdempiereException(e.getLocalizedMessage() + "\n KPI: " + this + "\n Query: " + esQueryParsed + "\n Response: " + response, e);
}
}
use of org.adempiere.ad.expression.api.IStringExpression in project metasfresh-webui-api by metasfresh.
the class SqlDocumentOrderByBuilder method buildSqlOrderBy.
private final IStringExpression buildSqlOrderBy(final DocumentQueryOrderBy orderBy) {
final String fieldName = orderBy.getFieldName();
final IStringExpression sqlExpression = bindings.getFieldOrderBy(fieldName);
return buildSqlOrderBy(sqlExpression, orderBy.isAscending(), orderBy.isNullsLast());
}
Aggregations