Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 81 additions & 24 deletions api/src/org/labkey/api/data/TableSelector.java
Original file line number Diff line number Diff line change
Expand Up @@ -564,15 +564,34 @@ public Map<String, List<Result>> getAggregates(final List<Aggregate> aggregates)
* @param maxCount when > 0 and the only aggregate is COUNT(*), bounds the inner select to maxCount + 1 rows so the database can stop early.
*/
public Map<String, List<Result>> getAggregates(final List<Aggregate> aggregates, int maxCount)
{
// Results already arrive keyed by FieldKey, so only the String conversion needs to be removed in order
// to support a return type of Map<FieldKey, List<Aggregate.Result>>.
Map<String, List<Result>> results = new CaseInsensitiveHashMap<>();
prepareAggregates(aggregates, maxCount)
.execute()
.forEach((fieldKey, fieldResults) -> results.put(fieldKey.toString(), fieldResults));
return results;
}

public PreparedAggregates prepareAggregates(final List<Aggregate> aggregates)
{
return prepareAggregates(aggregates, 0);
}

/**
* Generates the aggregate SQL now and runs it on {@link PreparedAggregates#execute()}, so a caller can serialize SQL generation without holding a lock while the query runs.
* @param maxCount when > 0 and the only aggregate is COUNT(*), bounds the inner select to maxCount + 1 rows so the database can stop early.
*/
public PreparedAggregates prepareAggregates(final List<Aggregate> aggregates, int maxCount)
{
// If we are only asking for the COUNT(*) aggregate, then we don't need to include all of the table columns in the subselect.
// This can make a big performance difference for Sample Type and Data Class tables as they can then skip
// the join between the exp schema base table and the materialized table for the given table.
boolean countStarOnly = aggregates.size() == 1 && aggregates.getFirst().isCountStar();
Collection<ColumnInfo> aggColumns = countStarOnly ? getRowCountingSelectColumns(_table) : _columns;

final AggregateSqlFactory sqlFactory = new AggregateSqlFactory(_filter, aggregates, aggColumns);
ResultSetFactory resultSetFactory = new ExecutingResultSetFactory(sqlFactory);
AggregateSqlFactory sqlFactory = new AggregateSqlFactory(_filter, aggregates, aggColumns);

// Setting _maxRows threads LIMIT maxCount + 1 through TableSqlFactory.getSql() into the inner select; restore it after.
boolean cap = maxCount > 0 && countStarOnly;
Expand All @@ -582,37 +601,75 @@ public Map<String, List<Result>> getAggregates(final List<Aggregate> aggregates,

try
{
return resultSetFactory.handleResultSet((rs, conn) -> {
Map<String, List<Result>> results = new CaseInsensitiveHashMap<>();
return new PreparedAggregates(aggregates, sqlFactory._columnMap, sqlFactory.getSql(), sqlFactory.getStatementMaxRows());
}
finally
{
if (cap)
_maxRows = maxRows;
}
}

/** Aggregate SQL generated by {@link #prepareAggregates(List, int)}, run against this selector's scope and settings. */
public class PreparedAggregates
{
private final List<Aggregate> _aggregates;
private final Map<FieldKey, ColumnInfo> _columnMap;
private final @Nullable SQLFragment _sql;
private final @Nullable Integer _statementMaxRows;

private PreparedAggregates(List<Aggregate> aggregates, Map<FieldKey, ColumnInfo> columnMap, @Nullable SQLFragment sql, @Nullable Integer statementMaxRows)
{
_aggregates = aggregates;
_columnMap = columnMap;
_sql = sql;
_statementMaxRows = statementMaxRows;
}

/** Null when no aggregate applies to its column, in which case {@link #execute()} returns an empty map without querying. */
public @Nullable SQLFragment getSql()
{
return _sql;
}

// null == rs is the short-circuit case... SqlFactory didn't find any aggregate columns, so
// query wasn't executed. Just return an empty map in this case.
if (null != rs)
public Map<FieldKey, List<Result>> execute()
{
SqlFactory sqlFactory = new BaseSqlFactory()
{
// Issue 17536: Issue a warning instead of blowing up if there is no result row containing the aggregate values.
if (!rs.next())
@Override
public @Nullable SQLFragment getSql()
{
LOG.warn("Expected a non-empty resultset from aggregate query.");
return _sql;
}
else

@Override
public @Nullable Integer getStatementMaxRows()
{
for (Aggregate agg : aggregates)
{
if (!results.containsKey(agg.getFieldKey().toString()))
results.put(agg.getFieldKey().toString(), new ArrayList<>());
return _statementMaxRows;
}
};

return new ExecutingResultSetFactory(sqlFactory).handleResultSet((rs, _) -> {
Map<FieldKey, List<Result>> results = new LinkedHashMap<>();

results.get(agg.getFieldKey().toString()).add(agg.getResult(rs, sqlFactory._columnMap, getScope().getSqlDialect()));
// null == rs is the short-circuit case... SqlFactory didn't find any aggregate columns, so
// query wasn't executed. Just return an empty map in this case.
if (null != rs)
{
// Issue 17536: Issue a warning instead of blowing up if there is no result row containing the aggregate values.
if (!rs.next())
{
LOG.warn("Expected a non-empty resultset from aggregate query.");
}
else
{
for (Aggregate agg : _aggregates)
results.computeIfAbsent(agg.getFieldKey(), _ -> new ArrayList<>()).add(agg.getResult(rs, _columnMap, getScope().getSqlDialect()));
}
}
}

return results;
});
}
finally
{
if (cap)
_maxRows = maxRows;
return results;
});
}
}

Expand Down
50 changes: 50 additions & 0 deletions api/src/org/labkey/api/query/suggestions/SuggestionColumn.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ public enum Type { BOOLEAN, DATE, FLOAT, INT, STRING }
private boolean _partialMatch;
private final List<String> _nameExpressions = new ArrayList<>();
private @Nullable List<String> _values;
private boolean _valuesFromData;
private boolean _valuesTruncated;
private boolean _valuesHaveBlank;
private @Nullable Long _distinctCount;
private @Nullable List<String> _shapes;
// Number for numeric columns, LocalDate for date columns
private @Nullable Object _min;
Expand Down Expand Up @@ -176,6 +180,52 @@ public void setValues(@Nullable List<String> values)
_values = values;
}

/**
* Values read from the column's data, with what the read couldn't represent.
*
* @param truncated a value was too long to keep, so values is incomplete
* @param hasBlank some row holds null or blank; blanks are never in values
*/
public void setValues(@Nullable List<String> values, boolean truncated, boolean hasBlank)
{
_values = values;
_valuesFromData = true;
_valuesTruncated = truncated;
_valuesHaveBlank = hasBlank;
}

/**
* The values were read from the column's data. False for a column whose values come from its definition, such as
* a boolean or Text Choice: those are the options the column allows, which some may match no row.
*/
public boolean isValuesFromData()
{
return _valuesFromData;
}

/** Some row holds null or blank; blanks are never in {@link #getValues()}. */
public boolean isValuesHaveBlank()
{
return _valuesHaveBlank;
}

/** A value was too long to keep, so {@link #getValues()} is incomplete. */
public boolean isValuesTruncated()
{
return _valuesTruncated;
}

/** COUNT(DISTINCT), known even when the column has too many values to list. Null when not loaded. */
public @Nullable Long getDistinctCount()
{
return _distinctCount;
}

public void setDistinctCount(@Nullable Long distinctCount)
{
_distinctCount = distinctCount;
}

public @Nullable List<String> getShapes()
{
return _shapes;
Expand Down
13 changes: 13 additions & 0 deletions query/src/org/labkey/query/controllers/QueryController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4177,6 +4177,19 @@ public Object execute(FilterSuggestionsRequest request, BindException errors)
}
}

/** Cached per-column values and distinct counts, so the faceted filter can skip its SELECT DISTINCT. */
@Marshal(Marshaller.Jackson)
@RequiresPermission(ReadPermission.class)
@Action(ActionType.SelectData.class)
public static class GetColumnFacetsAction extends ReadOnlyApiAction<FilterSuggestionsRequest>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This appears to be handing back information for all columns when the client only ever is looking at a single column. Consider adding a "column" or "facetColumn" to the request parameters so that the server only returns information for that column (when specified).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a very appealing idea. I evaluated this but I think I'm gonna hold off on this one. The reason is per column response means each time the user changes a field selection on the filter panel, a different api request is needed. With the current implementation, a single request handles all fields on the filter panel. Changing fields on the filter panel might not be a common scenario, but it still is not clear trade off for smaller payload vs fewer requests.

{
@Override
public Object execute(FilterSuggestionsRequest request, BindException errors)
{
return FilterSuggestionService.getColumnFacets(getUser(), getContainer(), request);
}
}

private SimpleFilter getFilterFromQueryForm(QueryForm form)
{
QuerySettings settings = form.getQuerySettings();
Expand Down
8 changes: 6 additions & 2 deletions query/src/org/labkey/query/suggestions/ColumnFact.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,12 @@ public sealed interface ColumnFact
*/
record Stats(@Nullable Object min, @Nullable Object max, @Nullable Long distinctCount, boolean rangeUnknown) implements ColumnFact {}

/** @param values null when the column has more than {@link ColumnFactsCache#DISTINCT_VALUE_LIMIT} distinct values */
record Values(@Nullable List<String> values) implements ColumnFact
/**
* @param values null when the column has more than {@link ColumnFactsCache#DISTINCT_VALUE_LIMIT} distinct values
* @param truncated a value was too long to keep, so the list is incomplete even though it didn't overflow
* @param hasBlank some row holds null or blank; blanks are left out of values but callers may still offer them
*/
record Values(@Nullable List<String> values, boolean truncated, boolean hasBlank) implements ColumnFact
{
public Values
{
Expand Down
Loading