diff --git a/api/src/org/labkey/api/data/TableSelector.java b/api/src/org/labkey/api/data/TableSelector.java index 3bada4b5cc3..a3c5e7484a9 100644 --- a/api/src/org/labkey/api/data/TableSelector.java +++ b/api/src/org/labkey/api/data/TableSelector.java @@ -564,6 +564,26 @@ public Map> getAggregates(final List 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> getAggregates(final List 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>. + Map> results = new CaseInsensitiveHashMap<>(); + prepareAggregates(aggregates, maxCount) + .execute() + .forEach((fieldKey, fieldResults) -> results.put(fieldKey.toString(), fieldResults)); + return results; + } + + public PreparedAggregates prepareAggregates(final List 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 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 @@ -571,8 +591,7 @@ public Map> getAggregates(final List aggregates, boolean countStarOnly = aggregates.size() == 1 && aggregates.getFirst().isCountStar(); Collection 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; @@ -582,37 +601,75 @@ public Map> getAggregates(final List aggregates, try { - return resultSetFactory.handleResultSet((rs, conn) -> { - Map> 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 _aggregates; + private final Map _columnMap; + private final @Nullable SQLFragment _sql; + private final @Nullable Integer _statementMaxRows; + + private PreparedAggregates(List aggregates, Map 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> 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> 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; + }); } } diff --git a/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java b/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java index cdc2aff13c1..9b69975f32c 100644 --- a/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java +++ b/api/src/org/labkey/api/query/suggestions/SuggestionColumn.java @@ -44,6 +44,10 @@ public enum Type { BOOLEAN, DATE, FLOAT, INT, STRING } private boolean _partialMatch; private final List _nameExpressions = new ArrayList<>(); private @Nullable List _values; + private boolean _valuesFromData; + private boolean _valuesTruncated; + private boolean _valuesHaveBlank; + private @Nullable Long _distinctCount; private @Nullable List _shapes; // Number for numeric columns, LocalDate for date columns private @Nullable Object _min; @@ -176,6 +180,52 @@ public void setValues(@Nullable List 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 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 getShapes() { return _shapes; diff --git a/query/src/org/labkey/query/controllers/QueryController.java b/query/src/org/labkey/query/controllers/QueryController.java index b79d778fcb9..b7393493053 100644 --- a/query/src/org/labkey/query/controllers/QueryController.java +++ b/query/src/org/labkey/query/controllers/QueryController.java @@ -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 + { + @Override + public Object execute(FilterSuggestionsRequest request, BindException errors) + { + return FilterSuggestionService.getColumnFacets(getUser(), getContainer(), request); + } + } + private SimpleFilter getFilterFromQueryForm(QueryForm form) { QuerySettings settings = form.getQuerySettings(); diff --git a/query/src/org/labkey/query/suggestions/ColumnFact.java b/query/src/org/labkey/query/suggestions/ColumnFact.java index 5cd3f08ecb1..17ddaed21f7 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFact.java +++ b/query/src/org/labkey/query/suggestions/ColumnFact.java @@ -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 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 values, boolean truncated, boolean hasBlank) implements ColumnFact { public Values { diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java index 9b4508070f5..cf973c29889 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsCache.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsCache.java @@ -251,9 +251,9 @@ public static ColumnFactsCache get() * Sets cached facts on the columns, loading missing ones and waiting for them up to the budget. * @param filter bounds the rows read from the table, but not the junction tables that multi-valued lookups read * @param tokens each table's change token, or null when its facts must not be shared across users - * @return false when some fact wasn't available within the budget + * @return what the request still doesn't know about the facts it asked for */ - public boolean fill(@NotNull FilterSuggestionContext context, @Nullable Map parameters, @Nullable SimpleFilter filter, @NotNull FilterSuggestionColumns.Described described, + public FillResult fill(@NotNull FilterSuggestionContext context, @Nullable Map parameters, @Nullable SimpleFilter filter, @NotNull FilterSuggestionColumns.Described described, @NotNull Function tokens, long budgetMs) { long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(budgetMs); @@ -270,7 +270,7 @@ public boolean fill(@NotNull FilterSuggestionContext context, @Nullable Map plans = new ArrayList<>(); for (SuggestionColumn column : described.columns()) { - if (described.auditLogged().contains(column)) + if (described.auditLogged().contains(column) || isThroughLookup(column) || described.lookups().containsKey(column)) continue; Scope columnScope = userScope; if (isShared(column)) @@ -282,7 +282,7 @@ public boolean fill(@NotNull FilterSuggestionContext context, @Nullable Map> loads = new ArrayList<>(); @@ -311,7 +311,20 @@ record StatsGroup(Scope scope, @Nullable String columnToken) {} } } tagRequest(plans.size(), pending, failed, !finished); - return pending == 0; + return new FillResult(pending > 0, failed > 0); + } + + /** + * @param pending a fact hadn't loaded within the budget, so asking again later may answer it + * @param failed a fact's load failed, and the failure is cached: asking again won't answer it until it expires + */ + public record FillResult(boolean pending, boolean failed) + { + /** Every fact the request asked for is in hand, whether or not any of them failed. */ + public boolean complete() + { + return !pending; + } } /** Tags the request's span with how many columns' facts were ready, since the loads run in traces of their own */ @@ -323,6 +336,16 @@ private static void tagRequest(int columns, int pending, int failed, boolean bud TracedOperation.tagActiveSpan("labkey.suggestion.budget_exhausted", budgetExhausted); } + /** + * Whether the column's values are read through a lookup join, whose base column the query is free to prune: that + * has produced invalid SQL against nested queries, so the column falls back to the grid's own value query. + */ + private static boolean isThroughLookup(SuggestionColumn column) + { + ColumnInfo info = column.getColumnInfo(); + return info != null && info.getFieldKey().getParent() != null; + } + /** Whether the column's facts can follow the table's token, which shares them across users */ private static boolean isShared(SuggestionColumn column) { @@ -683,6 +706,8 @@ private FactState apply(Plan plan) } ColumnFact stats = _cache.get(plan.statsKey()); + if (stats instanceof ColumnFact.Stats st) + column.setDistinctCount(st.distinctCount()); if (plan.kind() != Kind.STRING) { // Stats that failed or haven't loaded yet leave the range unknown, so the column isn't treated as out of range @@ -703,7 +728,7 @@ private FactState applyValues(Plan plan) { ColumnFact values = _cache.get(plan.valuesKey()); if (values instanceof ColumnFact.Values v && !v.isOverflow()) - plan.column().setValues(v.values()); + plan.column().setValues(v.values(), v.truncated(), v.hasBlank()); return FactState.of(values); } @@ -917,7 +942,7 @@ public void testFactsAndCacheHit() TableInfo table = getTable(SAMPLE_TYPE); FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "token-1", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "token-1", 30_000).complete()); Map columns = byFieldKey(described); assertEquals(Set.of("red", "green", "blue"), Set.copyOf(Objects.requireNonNull(columns.get("color").getValues()))); @@ -944,7 +969,7 @@ public void testFactsAndCacheHit() int calls = source._calls.get(); FilterSuggestionColumns.Described again = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertTrue("Cached facts should need no wait", cache.fill(context(table, _user), null, null, again, _ -> "token-1", 0)); + assertTrue("Cached facts should need no wait", cache.fill(context(table, _user), null, null, again, _ -> "token-1", 0).complete()); assertEquals(calls, source._calls.get()); assertEquals(List.of("AAAA-999999"), byFieldKey(again).get("subject").getShapes()); } @@ -967,27 +992,30 @@ public void testSharingFollowsToken() TableInfo table = getTable(SAMPLE_TYPE); User other = UserManager.getGuestUser(); - assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> null, 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> null, 30_000).complete()); assertNotNull(cache.peek(context(table, _user), null, false, "values", "color")); assertNull("Facts of a table without a token must not cross users", cache.peek(context(table, other), null, false, "values", "color")); - assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull(cache.peek(context(table, other), "shared", true, "values", "color")); assertNull("A new token must miss", cache.peek(context(table, other), "changed", true, "values", "color")); } @Test - public void testLookupDataIsNotShared() + public void testLookupColumnsAreNotRead() { - ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(0)); + TestSource source = new TestSource(0); + ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, source); TableInfo table = getTable(SAMPLE_TYPE); String email = "CreatedBy/Email"; - FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of(email)); + FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("CreatedBy", email)); assertTrue(byFieldKey(described).containsKey(email)); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000)); - assertNotNull(cache.peek(context(table, _user), "shared", false, "values", email)); - assertNull("The table's token doesn't cover data reached through a lookup", cache.peek(context(table, UserManager.getGuestUser()), "shared", true, "values", email)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000).complete()); + assertEquals("A lookup's values are read through a join the query may prune", 0, source._calls.get()); + for (SuggestionColumn column : described.columns()) + assertNull(column.getFieldKey(), column.getValues()); + assertNull(cache.peek(context(table, _user), "shared", false, "values", email)); } @Test @@ -997,7 +1025,7 @@ public void testPerUserFactsFollowToken() TableInfo table = getTable(SAMPLE_TYPE); FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("viewer")); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "before", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "before", 30_000).complete()); assertNotNull(cache.peek(context(table, _user), "before", false, "values", "viewer")); assertNull("A per-user entry must miss once the table's token changes", cache.peek(context(table, _user), "after", false, "values", "viewer")); } @@ -1010,25 +1038,11 @@ public void testCalculatedDataIsNotShared() FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("viewer")); assertTrue(byFieldKey(described).containsKey("viewer")); - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000).complete()); assertNotNull(cache.peek(context(table, _user), "shared", false, "values", "viewer")); assertNull("A calculated value can depend on the user", cache.peek(context(table, UserManager.getGuestUser()), "shared", true, "values", "viewer")); } - @Test - public void testLookupValuesComeFromRows() - { - ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(0)); - TableInfo table = getTable(SAMPLE_TYPE); - FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("CreatedBy", "ModifiedBy")); - assertEquals(2, described.columns().size()); - assertTrue(described.lookups().isEmpty()); - - assertTrue(cache.fill(context(table, _user), null, null, described, _ -> "shared", 30_000)); - for (SuggestionColumn column : described.columns()) - assertEquals(column.getFieldKey(), List.of(_user.getDisplayName(_user)), column.getValues()); - } - @Test public void testGridFieldKeyIsTheRequestedColumn() { @@ -1047,7 +1061,7 @@ public void testUndeclaredParametersAreIgnored() ColumnFactsCache cache = new ColumnFactsCache(_testCache, _executor, new TestSource(0)); TableInfo table = getTable(SAMPLE_TYPE); - assertTrue(cache.fill(context(table, _user), Map.of("bogus", 1), null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), Map.of("bogus", 1), null, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull(cache.peek(context(table, _user), "shared", true, "values", "color")); } @@ -1069,7 +1083,7 @@ public void testAuditLoggedColumnsReadNoData() logged.add(copy); } - assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(logged, Map.of(), Set.of()), _ -> "token-2", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(logged, Map.of(), Set.of()), _ -> "token-2", 30_000).complete()); assertEquals(0, source._calls.get()); for (SuggestionColumn column : logged) { @@ -1089,7 +1103,7 @@ public void testColumnsReachedThroughAuditLoggedLookupsReadNoData() FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, null, List.of("CreatedBy")); SuggestionColumn createdBy = described.columns().getFirst(); - assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(described.columns(), described.lookups(), Set.of(createdBy)), _ -> "token-4", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, new FilterSuggestionColumns.Described(described.columns(), described.lookups(), Set.of(createdBy)), _ -> "token-4", 30_000).complete()); assertEquals(0, source._calls.get()); assertNull(createdBy.getValues()); } @@ -1102,7 +1116,7 @@ public void testBudget() throws Exception long start = System.currentTimeMillis(); FilterSuggestionColumns.Described cold = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertFalse(cache.fill(context(table, _user), null, null, cold, _ -> "token-3", 100)); + assertFalse(cache.fill(context(table, _user), null, null, cold, _ -> "token-3", 100).complete()); assertTrue("Budget not honored", System.currentTimeMillis() - start < 1_500); assertNull(byFieldKey(cold).get("color").getValues()); assertNull(byFieldKey(cold).get("concentration").getMin()); @@ -1111,7 +1125,7 @@ public void testBudget() throws Exception assertTrue(cache.awaitIdle(60_000)); FilterSuggestionColumns.Described warm = FilterSuggestionColumns.describe(table, null, FIELD_KEYS); - assertTrue("Late results should fill the cache", cache.fill(context(table, _user), null, null, warm, _ -> "token-3", 0)); + assertTrue("Late results should fill the cache", cache.fill(context(table, _user), null, null, warm, _ -> "token-3", 0).complete()); assertNotNull(byFieldKey(warm).get("color").getValues()); } @@ -1124,12 +1138,12 @@ public void testFilterBoundsFacts() SimpleFilter firstSubject = new SimpleFilter(FieldKey.fromParts("subject"), "SUBJ-000000"); FilterSuggestionColumns.Described filtered = FilterSuggestionColumns.describe(table, null, List.of("color", "thawCount")); - assertTrue(cache.fill(context(table, _user), null, firstSubject, filtered, _ -> "token-5", 30_000)); + assertTrue(cache.fill(context(table, _user), null, firstSubject, filtered, _ -> "token-5", 30_000).complete()); assertEquals(List.of("red"), byFieldKey(filtered).get("color").getValues()); assertEquals(List.of("0"), byFieldKey(filtered).get("thawCount").getValues()); FilterSuggestionColumns.Described unfiltered = FilterSuggestionColumns.describe(table, null, List.of("color")); - assertTrue(cache.fill(context(table, _user), null, null, unfiltered, _ -> "token-5", 30_000)); + assertTrue(cache.fill(context(table, _user), null, null, unfiltered, _ -> "token-5", 30_000).complete()); assertEquals("Filtered entries must not serve the unfiltered table", Set.of("red", "green", "blue"), Set.copyOf(Objects.requireNonNull(byFieldKey(unfiltered).get("color").getValues()))); } @@ -1147,13 +1161,13 @@ public void testFiltersBeyondTheTokenAreNotShared() ); for (SimpleFilter filter : unshared) { - assertTrue(filter.toString(), cache.fill(context(table, _user), null, filter, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(filter.toString(), cache.fill(context(table, _user), null, filter, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull(filter.toString(), cache.peek(context(table, _user), "shared", false, filter, "values", "color")); assertNull(filter.toString(), cache.peek(context(table, other), "shared", true, filter, "values", "color")); } SimpleFilter own = new SimpleFilter(FieldKey.fromParts("thawCount"), 0); - assertTrue(cache.fill(context(table, _user), null, own, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000)); + assertTrue(cache.fill(context(table, _user), null, own, FilterSuggestionColumns.describe(table, null, List.of("color")), _ -> "shared", 30_000).complete()); assertNotNull("A filter on the table's own columns follows its token", cache.peek(context(table, other), "shared", true, own, "values", "color")); } diff --git a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java index 5904d7c05dd..849d45553ab 100644 --- a/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java +++ b/query/src/org/labkey/query/suggestions/ColumnFactsLoader.java @@ -20,7 +20,6 @@ import org.labkey.api.data.Aggregate; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.QueryLogging; -import org.labkey.api.data.Results; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.Sort; @@ -32,7 +31,6 @@ import org.labkey.api.query.suggestions.SuggestionColumn; import java.math.BigDecimal; -import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; @@ -74,15 +72,22 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag byFieldKey.put(fieldKey, new Aggregates(min, max, distinct)); } - Map> results = new TableSelector(table, columns, filter, null) - .setNamedParameters(parameters) - .setQueryTimeout(QUERY_TIMEOUT_SECONDS) - .getAggregates(aggregates); + TableSelector.PreparedAggregates prepared; + // Parallel loads share this table; hold it only while generating SQL so scans run concurrently + // noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (table) + { + prepared = new TableSelector(table, columns, filter, null) + .setNamedParameters(parameters) + .setQueryTimeout(QUERY_TIMEOUT_SECONDS) + .prepareAggregates(aggregates); + } + Map> results = prepared.execute(); Map stats = new HashMap<>(); byFieldKey.forEach((fieldKey, aggs) -> { // Absent when the aggregate doesn't apply to the column's type; the caller records that as a failure - List columnResults = results.get(fieldKey.toString()); + List columnResults = results.get(fieldKey); if (columnResults == null) return; Object rawMin = getValue(columnResults, aggs.min()); @@ -94,37 +99,87 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag return stats; } + // Temporarily disabled to test platform PR #8368 in isolation +// /** +// * The column plus the lookup columns it is reached through. A display column's join reads its FK's base column, +// * and a query selects only the columns asked for, so requesting the display column alone leaves the join +// * pointing at one the inner select dropped. +// */ +// private static List withAncestors(QueryService service, TableInfo table, ColumnInfo column) +// { +// FieldKey parent = column.getFieldKey().getParent(); +// if (parent == null) +// return List.of(column); +// +// List ancestors = new ArrayList<>(); +// for (FieldKey key = parent; key != null; key = key.getParent()) +// ancestors.add(key); +// +// Map resolved = service.getColumns(table, ancestors); +// List columns = new ArrayList<>(); +// ancestors.forEach(key -> { +// ColumnInfo ancestor = resolved.get(key); +// if (ancestor != null) +// columns.add(ancestor); +// }); +// // Last, and the instance the caller passed: the outer select reads values by this column's own alias +// columns.add(column); +// return columns; +// } + @Override public @NotNull ColumnFact.Values loadValues(@NotNull TableInfo table, @NotNull ColumnInfo column, @NotNull SuggestionColumn.Type type, @NotNull Map parameters, @Nullable SimpleFilter filter) { QueryService service = QueryService.get(); QueryLogging queryLogging = new QueryLogging(); - SQLFragment selectSql = service.getSelectBuilder(table) - .columns(List.of(column)) - .filter(filter) - .queryLogging(queryLogging) - .distinct(true) - .buildSqlFragment(); - - SQLFragment sql = new SQLFragment("SELECT S.").appendIdentifier(column.getAlias()).append(" AS value FROM (") + SQLFragment selectSql; + // Parallel loads share this table; hold it only while generating SQL so scans run concurrently + // noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (table) + { + selectSql = service.getSelectBuilder(table) +// .columns(withAncestors(service, table, column)) + .columns(column) + .filter(filter) + .queryLogging(queryLogging) + .distinct(true) + .buildSqlFragment(); + } + + // Distinct again out here: the inner one covers every column it projects, which for a lookup includes the + // base column the join reads, so two base values sharing a display value would each yield a row + SQLFragment sql = new SQLFragment("SELECT DISTINCT S.").appendIdentifier(column.getAlias()).append(" AS value FROM (") .append(selectSql) - .append(") S WHERE S.").appendIdentifier(column.getAlias()).append(" IS NOT NULL"); - // One extra row for a blank value, which is dropped, and one to detect overflow - sql = table.getSqlDialect().limitRows(sql, ColumnFactsCache.DISTINCT_VALUE_LIMIT + 2); + .append(") S"); + // Two extra rows for a null and a blank value, which are dropped, and one to detect overflow + int limit = ColumnFactsCache.DISTINCT_VALUE_LIMIT + 3; + sql = table.getSqlDialect().limitRows(sql, limit); service.bindNamedParameters(sql, parameters); service.validateNamedParameters(sql); List values = new ArrayList<>(); int count = 0; + int rows = 0; + boolean truncated = false; + boolean hasBlank = false; for (String value : new SqlSelector(table.getSchema().getScope(), sql, queryLogging).setQueryTimeout(QUERY_TIMEOUT_SECONDS).getArrayList(String.class)) { + rows++; if (value == null || value.isBlank()) + { + hasBlank = true; continue; + } count++; if (value.length() <= MAX_VALUE_LENGTH) values.add(type == SuggestionColumn.Type.INT ? toIntegerString(value) : value); + else + truncated = true; } - return new ColumnFact.Values(count > ColumnFactsCache.DISTINCT_VALUE_LIMIT ? null : values); + // Every distinct blank-ish value is its own row and is dropped without counting, so a full fetch can hide + // values even when the count is under the limit. Then the list can't be trusted to be the whole set. + boolean overflow = count > ColumnFactsCache.DISTINCT_VALUE_LIMIT || rows == limit; + return new ColumnFact.Values(overflow ? null : values, truncated, hasBlank); } @Override @@ -133,27 +188,29 @@ record Aggregates(@Nullable Aggregate min, @Nullable Aggregate max, @Nullable Ag Map> shapes = new LinkedHashMap<>(); columns.forEach(column -> shapes.put(column.getFieldKey(), new LinkedHashSet<>())); - TableSelector selector = new TableSelector(table, columns, filter, getNewestFirstSort(table)) - .setMaxRows(SHAPE_SAMPLE_SIZE) - .setNamedParameters(parameters) - .setQueryTimeout(QUERY_TIMEOUT_SECONDS); - try (Results results = selector.getResults(false)) + Sort sort = getNewestFirstSort(table); + SqlSelector selector; + // Parallel loads share this table; hold it only while generating SQL so scans run concurrently + // noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (table) { - while (results.next()) + selector = QueryService.get().getSelectBuilder(table) + .columns(columns) + .filter(filter) + .sort(sort) + .maxRows(SHAPE_SAMPLE_SIZE) + .forceSort(true) + .buildSqlSelector(parameters); + } + selector.setQueryTimeout(QUERY_TIMEOUT_SECONDS).forEach(rs -> { + for (ColumnInfo column : columns) { - for (Map.Entry> entry : shapes.entrySet()) - { - Object value = results.getObject(entry.getKey()); - String text = value == null ? null : value.toString(); - if (text != null && !text.isBlank() && text.length() <= MAX_VALUE_LENGTH) - entry.getValue().add(FilterSuggestionRanker.getValueShape(text)); - } + Object value = rs.getObject(column.findColumn(rs)); + String text = value == null ? null : value.toString(); + if (text != null && !text.isBlank() && text.length() <= MAX_VALUE_LENGTH) + shapes.get(column.getFieldKey()).add(FilterSuggestionRanker.getValueShape(text)); } - } - catch (SQLException e) - { - throw new RuntimeException(e); - } + }); Map result = new HashMap<>(); shapes.forEach((fieldKey, columnShapes) -> result.put(fieldKey, new ColumnFact.Shapes(List.copyOf(columnShapes)))); diff --git a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java index 8e91943bc25..ade9affd691 100644 --- a/query/src/org/labkey/query/suggestions/FilterSuggestionService.java +++ b/query/src/org/labkey/query/suggestions/FilterSuggestionService.java @@ -26,6 +26,9 @@ import org.labkey.api.data.CompareType; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerFilter; +import org.labkey.api.data.DbScope; +import org.labkey.api.data.SQLFragment; +import org.labkey.api.data.SqlSelector; import org.labkey.api.data.PHI; import org.labkey.api.data.SimpleFilter; import org.labkey.api.data.TableInfo; @@ -33,6 +36,9 @@ import org.labkey.api.query.FieldKey; import org.labkey.api.query.QueryDefinition; import org.labkey.api.query.QueryForm; +import org.labkey.api.exp.property.Domain; +import org.labkey.api.exp.property.DomainKind; +import org.labkey.api.exp.query.SamplesSchema; import org.labkey.api.query.QueryService; import org.labkey.api.query.UserSchema; import org.labkey.api.query.suggestions.FilterSuggestionContext; @@ -53,6 +59,8 @@ import java.util.Set; import java.util.function.Function; +import static org.labkey.api.data.DataRegionSelection.MAX_QUERY_SELECTION_SIZE; + /** Backs query-getFilterSuggestions.api: resolves the table, describes its candidate columns, and ranks suggestions. */ public class FilterSuggestionService { @@ -113,12 +121,17 @@ private record Context(TableInfo table, Container container, User user) implemen } } - public static @NotNull FilterSuggestionsResponse getSuggestions(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) - { - SuggestionTerm term = SuggestionTerm.parse(request.term()); - if (term.isBlank()) - return new FilterSuggestionsResponse(List.of(), true); + /** The resolved table and the filter bounding the rows its facts are read from. */ + private record Resolved(@NotNull UserSchema schema, @NotNull TableInfo table, @Nullable SimpleFilter filter, boolean readsData) {} + /** + * The described columns carrying whatever facts loaded within the budget. + * @param failed a fact's load failed, so what's missing won't arrive by asking again + */ + private record Filled(@NotNull TableInfo table, @NotNull List columns, boolean complete, boolean failed) {} + + private static Resolved resolve(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) + { // Same checks and messages as QueryForm, so this fails like query-getQuery.api UserSchema schema = StringUtils.isBlank(request.schemaName()) ? null : QueryService.get().getUserSchema(user, container, request.schemaName()); QueryForm.ensureSchemaNotNull(schema); @@ -133,15 +146,17 @@ private record Context(TableInfo table, Container container, User user) implemen SimpleFilter filter = getFilter(request, container, user); // A filter on a column whose data may not be read would reveal it through the rows the filter selects boolean readsData = filter == null || isReadable(table, filter); + return new Resolved(schema, table, filter, readsData); + } - // No cached value or sample name is longer, so only the search can match - if (term.getRaw().length() > ColumnFactsLoader.MAX_VALUE_LENGTH) - return new FilterSuggestionsResponse(List.of(FilterSuggestion.search(term.getRaw())), true); - - FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, getView(schema, request, user), request.columns()); + private static Filled describeAndFill(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request, @NotNull Resolved resolved) + { + TableInfo table = resolved.table(); + FilterSuggestionColumns.Described described = FilterSuggestionColumns.describe(table, getView(resolved.schema(), request, user), request.columns()); List columns = described.columns(); boolean complete = true; + boolean failed = false; FilterSuggestionContext context = new Context(table, container, user); for (FilterSuggestionProvider provider : QueryService.get().getFilterSuggestionProviders()) { @@ -163,8 +178,20 @@ private record Context(TableInfo table, Container container, User user) implemen try { - if (readsData) - complete &= ColumnFactsCache.get().fill(context, request.parameters(), filter, described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); + if (resolved.readsData()) + { + if (hasChangeTokens(table)) + { + ColumnFactsCache.FillResult result = ColumnFactsCache.get().fill(context, request.parameters(), resolved.filter(), described, tokens, ColumnFactsCache.DEFAULT_BUDGET_MS); + complete &= result.complete(); + failed = result.failed(); + } + else + { + // Nothing was read, so don't let a caller read the columns' absent facts as "no values" + complete = false; + } + } } catch (RuntimeException e) { @@ -172,11 +199,147 @@ private record Context(TableInfo table, Container container, User user) implemen complete = false; } - List suggestions = FilterSuggestionRanker.rank(term, columns, getMaxSuggestions(request)); + return new Filled(table, columns, complete, failed); + } + + public static @NotNull FilterSuggestionsResponse getSuggestions(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) + { + SuggestionTerm term = SuggestionTerm.parse(request.term()); + if (term.isBlank()) + return new FilterSuggestionsResponse(List.of(), true); + + Resolved resolved = resolve(user, container, request); + + // No cached value or sample name is longer, so only the search can match + if (term.getRaw().length() > ColumnFactsLoader.MAX_VALUE_LENGTH) + return new FilterSuggestionsResponse(List.of(FilterSuggestion.search(term.getRaw())), true); + + Filled filled = describeAndFill(user, container, request, resolved); + List suggestions = FilterSuggestionRanker.rank(term, filled.columns(), getMaxSuggestions(request)); + tagResponse(filled.table(), suggestions.size(), filled.complete()); + return new FilterSuggestionsResponse(suggestions, filled.complete()); + } + + /** + * Backs query-getColumnFacets.api: what the server already knows about each requested column, so the faceted + * filter can list values, or decide not to ask for them, without a SELECT DISTINCT over the grid. + * + * @param values the column's values, when it has few enough to list; otherwise null. Only a list with + * valuesFromData set describes the rows the request selects. + * @param valuesFromData values were read from the data the request selects. False for a column whose values come + * from its definition, such as a boolean or Text Choice, where they are the options the + * column allows and some may match no row. + * @param distinctCount COUNT(DISTINCT), known even when values is null. Counted in SQL, so unlike values it + * includes blank strings and does not collapse numerically equal text; expect it to exceed + * values.size() by a little rather than treating a difference as truncation. + * @param truncated a value was too long to cache, so values is incomplete and callers must query instead + * @param hasBlank some row holds null or blank, which values never includes. Only meaningful with + * valuesFromData set. + */ + public record ColumnFacet( + @NotNull String fieldKey, + @NotNull String gridFieldKey, + @NotNull String type, + @Nullable List values, + boolean valuesFromData, + @Nullable Long distinctCount, + boolean truncated, + boolean hasBlank + ) + { + /** The facts this endpoint discloses, narrowed from everything the load gathered about the column. */ + static ColumnFacet of(@NotNull SuggestionColumn column) + { + return new ColumnFacet( + column.getFieldKey(), + column.getGridFieldKey(), + column.getType().name(), + column.getValues(), + // A multi-valued lookup's values come from its target table, unscoped by this request + column.isValuesFromData() && !column.isMultiValued(), + column.getDistinctCount(), + column.isValuesTruncated(), + column.isValuesHaveBlank() + ); + } + } + + /** + * @param largeTable the table behind the query holds more rows than any grid would list values for. A coarse + * answer rather than the row estimate itself, which spans containers the caller may not read. + * @param complete every fact the request asked for was loaded. False when the budget ran out, a load failed, + * or the request's own filters meant no data could be read at all. + */ + public record ColumnFacetsResponse(@NotNull List columns, boolean largeTable, boolean complete) {} + + public static @NotNull ColumnFacetsResponse getColumnFacets(@NotNull User user, @NotNull Container container, @NotNull FilterSuggestionsRequest request) + { + Resolved resolved = resolve(user, container, request); + Filled filled = describeAndFill(user, container, request, resolved); + + Long estimate = resolved.readsData() ? getProvisionedRowCount(resolved.table()) : null; + boolean largeTable = estimate != null && estimate > MAX_QUERY_SELECTION_SIZE; + + List facets = filled.columns().stream().map(ColumnFacet::of).toList(); + + // Nothing was read, so the facts say nothing about the data; don't let a caller read that as "no values". + // A failed load reads the same way: its column reports no values, which is not the same as having none. + boolean complete = filled.complete() && !filled.failed() && resolved.readsData(); + tagResponse(filled.table(), facets.size(), complete); + return new ColumnFacetsResponse(facets, largeTable, complete); + } + + private static void tagResponse(TableInfo table, int count, boolean complete) + { TracedOperation.tagActiveSpan("labkey.query", table.getPublicSchemaName() + "." + table.getPublicName()); - TracedOperation.tagActiveSpan("labkey.suggestion.count", suggestions.size()); + TracedOperation.tagActiveSpan("labkey.suggestion.count", count); TracedOperation.tagActiveSpan("labkey.suggestion.complete", complete); - return new FilterSuggestionsResponse(suggestions, complete); + } + + /** + * Postgres' own estimate for the table a provisioned domain is stored in, which costs one catalog lookup. It + * covers every container the domain spans, because that is the table a value list scans. + * + * @return null for a query with no provisioned table behind it, before that table has ever been analyzed, or on + * any other database + */ + private static @Nullable Long getProvisionedRowCount(TableInfo table) + { + Domain domain = table.getDomain(); + DomainKind kind = domain == null ? null : domain.getDomainKind(); + String schemaName = kind == null ? null : kind.getStorageSchemaName(); + String tableName = domain == null ? null : domain.getStorageTableName(); + if (schemaName == null || tableName == null) + return null; + + DbScope scope = kind.getScope(); + if (scope == null || !scope.getSqlDialect().isPostgreSQL()) + return null; + + try + { + // reltuples is a float; cast in SQL because the selector has no getter for Float + SQLFragment sql = SQLFragment.unsafe( + "SELECT CAST(reltuples AS BIGINT) FROM pg_class WHERE oid = to_regclass(quote_ident(?) || '.' || quote_ident(?))", + schemaName, tableName); + Long estimate = new SqlSelector(scope, sql).getObject(Long.class); + // -1 means never analyzed in Postgres 14 and later; older versions report 0, indistinguishable from empty + return estimate == null || estimate < 0 ? null : estimate; + } + catch (RuntimeException e) + { + LOG.warn("Unable to estimate the row count for {}", table.getName(), e); + return null; + } + } + + /** + * Whether a data change to the table moves a change token, which every cached fact is keyed by. Only sample tables + * supply one, so facts read from anything else would be served stale until they aged out. + */ + private static boolean hasChangeTokens(TableInfo table) + { + return SamplesSchema.SCHEMA_NAME.equalsIgnoreCase(table.getPublicSchemaName()); } /** The first non-null token from a provider that handles the table; null keeps its facts per user. */