Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.logging.Level;

/**
Expand All @@ -39,7 +38,6 @@ public class FetchFromClusterExecutionStep extends AbstractExecutionStep {
public static final Object ORDER_DESC = "DESC";
private final QueryPlanningInfo queryPlanning;
private final int bucketId;
private final Set<String> projectedProperties;
private Object order;
private long totalFetched = 0L;
private boolean warnedAboutSkippedRecords;
Expand All @@ -55,7 +53,6 @@ public FetchFromClusterExecutionStep(final int bucketId, final QueryPlanningInfo
super(context);
this.bucketId = bucketId;
this.queryPlanning = queryPlanning;
this.projectedProperties = queryPlanning != null ? queryPlanning.projectedProperties : null;
this.order = order;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ public class FetchFromTypeWithFilterStep extends AbstractExecutionStep {

private String typeName;
private WhereClause whereClause;
private Set<String> projectedProperties;
private boolean orderByRidAsc = false;
private boolean orderByRidDesc = false;
private List<ExecutionStep> subSteps = new ArrayList<>();
Expand All @@ -51,13 +50,11 @@ private FetchFromTypeWithFilterStep(final CommandContext context) {
super(context);
}

public FetchFromTypeWithFilterStep(final String typeName, final Set<String> clusters,
final WhereClause whereClause, final Set<String> projectedProperties,
public FetchFromTypeWithFilterStep(final String typeName, final Set<String> clusters, final WhereClause whereClause,
final CommandContext context, final Boolean ridOrder) {
super(context);
this.typeName = typeName;
this.whereClause = whereClause;
this.projectedProperties = projectedProperties;

if (Boolean.TRUE.equals(ridOrder))
orderByRidAsc = true;
Expand Down Expand Up @@ -92,7 +89,7 @@ else if (orderByRidDesc) {

for (final int bucketId : bucketIds) {
if (bucketId > 0) {
final ScanWithFilterStep step = new ScanWithFilterStep(bucketId, whereClause, projectedProperties, context);
final ScanWithFilterStep step = new ScanWithFilterStep(bucketId, whereClause, context);
if (orderByRidAsc)
step.setOrder(FetchFromClusterExecutionStep.ORDER_ASC);
else if (orderByRidDesc)
Expand Down Expand Up @@ -180,8 +177,6 @@ public String prettyPrint(final int depth, final int indent) {
final String ind = ExecutionStepInternal.getIndent(depth, indent);
builder.append(ind);
builder.append("+ FETCH FROM TYPE ").append(typeName).append(" WITH FILTER");
if (projectedProperties != null)
builder.append(" [projected: ").append(String.join(", ", projectedProperties)).append("]");
if (context.isProfiling())
builder.append(" (").append(getCostFormatted()).append(")");
builder.append("\n");
Expand Down Expand Up @@ -217,7 +212,6 @@ public ExecutionStep copy(final CommandContext context) {
result.whereClause = this.whereClause;
result.orderByRidAsc = this.orderByRidAsc;
result.orderByRidDesc = this.orderByRidDesc;
result.projectedProperties = this.projectedProperties;
result.subSteps = this.subSteps.stream().map(x -> ((ExecutionStepInternal) x).copy(context)).collect(Collectors.toList());
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,6 @@ public class QueryPlanningInfo {
boolean projectionsCalculated = false;
AndBlock ridRangeConditions;

/**
* Set of property names required by this query (from SELECT, WHERE, GROUP BY, ORDER BY).
* When null, all properties are needed (e.g., SELECT *).
* Used for column projection pushdown to avoid deserializing unused properties.
*/
Set<String> projectedProperties;

public QueryPlanningInfo copy() {
//TODO check what has to be copied and what can be just referenced as it is
final QueryPlanningInfo result = new QueryPlanningInfo();
Expand Down Expand Up @@ -109,7 +102,6 @@ public QueryPlanningInfo copy() {
result.orderApplied = this.orderApplied;
result.projectionsCalculated = this.projectionsCalculated;
result.ridRangeConditions = this.ridRangeConditions;
result.projectedProperties = this.projectedProperties;

return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,45 +26,34 @@
import com.arcadedb.query.sql.parser.WhereClause;

import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.logging.Level;

/**
* A combined scan + filter step that evaluates the WHERE predicate immediately after loading each record,
* avoiding the overhead of creating ResultInternal wrappers for records that don't match the filter.
* <p>
* When {@code projectedProperties} is set, matching records are returned with only the projected properties
* deserialized, using a two-phase approach:
* <ol>
* <li>Filter phase: WHERE predicate accesses only the fields it references (lazy deserialization)</li>
* <li>Projection phase: only the SELECT-listed properties are deserialized from the binary buffer</li>
* </ol>
* Fields that appear in both WHERE and SELECT are deserialized only once (the lazy cache in ImmutableDocument).
* A surviving record is handed downstream as a plain wrapper around the {@link ImmutableDocument}
* it was read from, so every column is still deserialized one at a time, on demand, and only if something actually asks
* for it. This step used to carry a second "column projection push-down" phase that pre-extracted the SELECT-listed
* columns into the row instead; it was unreachable by construction and has been removed - see issue #5756 and the note
* on {@code SelectExecutionPlanner#handleTypeAsTarget}.
*/
public class ScanWithFilterStep extends AbstractExecutionStep {

private final int bucketId;
private final WhereClause whereClause;
private final Set<String> projectedProperties;
private Object order;
private long totalFetched = 0L;
private long totalFiltered = 0L;
private boolean warnedAboutSkippedRecords;

private Iterator<Record> iterator;

public ScanWithFilterStep(final int bucketId, final WhereClause whereClause, final Set<String> projectedProperties,
final CommandContext context) {
public ScanWithFilterStep(final int bucketId, final WhereClause whereClause, final CommandContext context) {
super(context);
this.bucketId = bucketId;
this.whereClause = whereClause;
this.projectedProperties = projectedProperties;
}

public ScanWithFilterStep(final int bucketId, final WhereClause whereClause, final CommandContext context) {
this(bucketId, whereClause, null, context);
}

public void setOrder(final Object order) {
Expand Down Expand Up @@ -96,7 +85,7 @@ private void fetchNextItem() {
final Record record = iterator.next();
totalFetched++;

// Phase 1: Evaluate WHERE on the full document (uses lazy per-field deserialization)
// Evaluate WHERE on the document itself: every field access is lazily deserialized on demand
final ResultInternal candidate = new ResultInternal(record);

// Set $current before WHERE evaluation so method calls (e.g. split()) resolve correctly
Expand All @@ -105,18 +94,7 @@ private void fetchNextItem() {
final long filterBegin = context.isProfiling() ? System.nanoTime() : 0;
try {
if (whereClause.matchesFilters(candidate, context)) {
// Phase 2: If projectedProperties is set, extract only needed columns
if (projectedProperties != null && record instanceof ImmutableDocument immutableDoc) {
final String[] fieldNames = projectedProperties.toArray(new String[0]);
final Map<String, Object> props = immutableDoc.propertiesAsMap(fieldNames);
final ResultInternal projected = new ResultInternal(context.getDatabase());
projected.setElement(immutableDoc);
for (final Map.Entry<String, Object> entry : props.entrySet())
projected.setProperty(entry.getKey(), entry.getValue());
nextItem = projected;
} else
nextItem = candidate;

nextItem = candidate;
context.setVariable("current", nextItem);
return;
}
Expand Down Expand Up @@ -181,8 +159,6 @@ private void warnIfRecordsSkipped() {
public String prettyPrint(final int depth, final int indent) {
String result = ExecutionStepInternal.getIndent(depth, indent) + "+ SCAN WITH FILTER BUCKET " + bucketId
+ " (" + context.getDatabase().getSchema().getBucketById(bucketId).getName() + ")";
if (projectedProperties != null)
result += " [projected: " + String.join(", ", projectedProperties) + "]";
if (context.isProfiling())
result += " (" + getCostFormatted() + ")";
result += "\n" + ExecutionStepInternal.getIndent(depth, indent) + " " + whereClause;
Expand All @@ -196,8 +172,7 @@ public boolean canBeCached() {

@Override
public ExecutionStep copy(final CommandContext context) {
final ScanWithFilterStep copy = new ScanWithFilterStep(this.bucketId, this.whereClause.copy(), this.projectedProperties,
context);
final ScanWithFilterStep copy = new ScanWithFilterStep(this.bucketId, this.whereClause.copy(), context);
copy.setOrder(this.order);
return copy;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,66 +167,6 @@ private void init(final CommandContext context) {
// literal-only comparisons, so the verdict holds for every execution that reuses the cached plan.
if (info.whereClause != null && info.whereClause.isAlwaysTrue(context))
info.whereClause = null;

info.projectedProperties = computeProjectedProperties(info);
}

/**
* Computes the set of property names required by this query for column projection pushdown.
* Analyzes SELECT projections, WHERE clause, GROUP BY, and ORDER BY to determine the minimal
* set of properties that need to be deserialized from storage.
*
* @return the set of required property names, or null if all properties are needed (e.g., SELECT *)
*/
private static Set<String> computeProjectedProperties(final QueryPlanningInfo info) {
// If there's no projection or it contains *, we need all properties
if (info.projection == null)
return null;

for (final ProjectionItem item : info.projection.getItems())
if (item.isAll())
return null;

final Set<String> result = new HashSet<>();

// Extract from SELECT projections
for (final ProjectionItem item : info.projection.getItems()) {
if (item.getExpression() != null && item.getExpression().isBaseIdentifier())
result.add(item.getExpression().getDefaultAlias().getStringValue());
else if (item.getExpression() != null)
// Complex expression: we can't determine the exact fields needed, need all
return null;
}

// Extract from WHERE clause
if (info.whereClause != null) {
// WHERE can reference arbitrary fields, so we need all properties if we can't analyze it
// For safety, return null to indicate all properties needed
return null;
}

// Extract from GROUP BY
if (info.groupBy != null) {
for (final Expression expr : info.groupBy.getItems()) {
if (expr.isBaseIdentifier())
result.add(expr.getDefaultAlias().getStringValue());
else
return null;
}
}

// Extract from ORDER BY
if (info.orderBy != null) {
for (final OrderByItem item : info.orderBy.getItems()) {
final String alias = item.getAlias();
if (alias != null)
result.add(alias);
else
return null;
}
}

return result.isEmpty() ? null : result;
}

public InternalExecutionPlan createExecutionPlan(final CommandContext context, final boolean useCache) {
Expand Down Expand Up @@ -1983,14 +1923,21 @@ else if (isOrderByRidDesc(info))

// Predicate pushdown: if there's a WHERE clause and no index was used, integrate the filter
// directly into the scan step to avoid separate FilterStep overhead.
// Also passes projectedProperties so that only SELECT-listed fields are deserialized
// for matching records (two-phase deserialization optimization).
// Only the predicate is pushed down, never the column list. A column projection push-down used to ride along
// here, and it was unreachable by construction: it was computed only when the statement had no WHERE clause,
// while this step exists only because it has one (issue #5756). Reviving it is not just a matter of widening
// that computation - the row it built carried the projected columns as content AND the record as element, and
// ResultInternal reads those two stores with different precedences, so any column left out of the projected
// set answered null to getProperty() while hasProperty() still said true. Every downstream consumer of a
// column the SELECT does not name - a per-record LET, an ORDER BY alias, a subquery - would have read that
// null as the stored value. Deserialization is already per-column and on demand (ImmutableDocument.get()),
// so there is no "materialize everything then discard it" cost here to reclaim.
// Skip pushdown when WHERE references LET variables ($), since LET is evaluated after fetch.
final boolean whereRefersToLet = info.perRecordLetClause != null && info.whereClause != null
&& info.whereClause.toString().contains("$");
if (info.whereClause != null && info.whereClause.baseExpression != null && !whereRefersToLet) {
final FetchFromTypeWithFilterStep fetcher = new FetchFromTypeWithFilterStep(identifier.getStringValue(), effectiveClusters,
info.whereClause, info.projectedProperties, context, orderByRidAsc);
info.whereClause, context, orderByRidAsc);
if (orderByRidAsc != null)
info.orderApplied = true;
plan.chain(fetcher);
Expand Down
Loading
Loading