diff --git a/datafusion/physical-expr/src/equivalence/properties/mod.rs b/datafusion/physical-expr/src/equivalence/properties/mod.rs index 8cc37f464af81..a47e8e7af24bd 100644 --- a/datafusion/physical-expr/src/equivalence/properties/mod.rs +++ b/datafusion/physical-expr/src/equivalence/properties/mod.rs @@ -1563,9 +1563,26 @@ impl EquivalenceProperties { /// Projects constraints according to the given projection mapping. /// - /// This function takes a projection mapping and extracts column indices of - /// target columns. It then projects the constraints to only include - /// relationships between columns that exist in the projected output. + /// A primary key or unique constraint is propagated only when the projection + /// includes every column that forms the key as a plain column reference. + /// Their indices are remapped to their positions in the output schema. + /// + /// # Example + /// + /// The original scan has columns `[a, b]`, with `a` as the primary key. + /// + /// The required projection is `[b, a]`, so the constraints must be updated. + /// Column `a` remains the primary key, but the constraint's physical + /// representation is updated to match the projected schema: + /// + /// ```text + /// Original: [a, b] constraints=[PrimaryKey([0])] + /// Projected: [b, a] constraints=[PrimaryKey([1])] + /// ``` + /// + /// Projecting `[b, a + 1]` instead drops the constraint because `a` is not + /// projected directly. This function does not infer constraints on computed + /// expressions. /// /// # Parameters /// @@ -1574,18 +1591,27 @@ impl EquivalenceProperties { /// /// # Returns /// - /// Returns an optional `Constraints` object containing only the constraints - /// that are valid for the projected columns (if any exists). + /// Returns `Some` containing the propagated constraints if at least one + /// constraint survives the projection, or `None` if none do. fn projected_constraints(&self, mapping: &ProjectionMapping) -> Option { - let indices = mapping - .iter() - .flat_map(|(_, targets)| { - targets.iter().filter_map(|(target, _)| { - target.downcast_ref::().map(|c| c.index()) - }) - }) - .collect::>(); - self.constraints.project(&indices) + // Source column index of each output column, `usize::MAX` if the + // output is not a plain column + let mut source_indices = vec![]; + for (source, targets) in mapping.iter() { + let Some(source) = source.downcast_ref::() else { + continue; + }; + for (target, _) in targets.iter() { + if let Some(target) = target.downcast_ref::() { + let index = target.index(); + if source_indices.len() <= index { + source_indices.resize(index + 1, usize::MAX); + } + source_indices[index] = source.index(); + } + } + } + self.constraints.project(&source_indices) } /// Projects these equivalence properties onto `output_schema` according to diff --git a/datafusion/sqllogictest/test_files/order.slt b/datafusion/sqllogictest/test_files/order.slt index bb93634f5bbbb..da3a34fe69a16 100644 --- a/datafusion/sqllogictest/test_files/order.slt +++ b/datafusion/sqllogictest/test_files/order.slt @@ -1926,6 +1926,43 @@ physical_plan DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/ statement ok drop table table_with_ordered_pk; +# A PRIMARY KEY must stay on its own column when the scan drops columns +# before it, otherwise the sort on (d, a) is wrongly removed +statement ok +COPY (VALUES (0, 3, 0, 10, 1), (0, 1, 0, 11, 1), (0, 2, 0, 12, 1), (0, 9, 0, 13, 2), (0, 5, 0, 14, 2)) +TO 'test_files/scratch/order/pk_dropped_columns.csv' +STORED AS CSV +OPTIONS ('format.has_header' 'false'); + +statement ok +CREATE EXTERNAL TABLE pk_dropped_columns (a0 INT, a INT, b INT, c INT, d INT, PRIMARY KEY (c)) +STORED AS CSV +WITH ORDER (d ASC) +OPTIONS ('format.has_header' 'false') +LOCATION 'test_files/scratch/order/pk_dropped_columns.csv'; + +query IIII +SELECT a, b, c, d FROM pk_dropped_columns ORDER BY d, a; +---- +1 0 11 1 +2 0 12 1 +3 0 10 1 +5 0 14 2 +9 0 13 2 + +query TT +EXPLAIN SELECT a, b, c, d FROM pk_dropped_columns ORDER BY d, a; +---- +logical_plan +01)Sort: pk_dropped_columns.d ASC NULLS LAST, pk_dropped_columns.a ASC NULLS LAST +02)--TableScan: pk_dropped_columns projection=[a, b, c, d] +physical_plan +01)SortExec: expr=[d@3 ASC NULLS LAST, a@0 ASC NULLS LAST], preserve_partitioning=[false] +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/order/pk_dropped_columns.csv]]}, projection=[a, b, c, d], output_ordering=[d@3 ASC NULLS LAST], constraints=[PrimaryKey([3])], file_type=csv, has_header=false + +statement ok +drop table pk_dropped_columns; + statement ok set datafusion.execution.target_partitions = 1;