diff --git a/src/duckdb/extension/json/json_functions/json_normalize.cpp b/src/duckdb/extension/json/json_functions/json_normalize.cpp index 3fb1e28b7..71be0af44 100644 --- a/src/duckdb/extension/json/json_functions/json_normalize.cpp +++ b/src/duckdb/extension/json/json_functions/json_normalize.cpp @@ -44,14 +44,16 @@ static void SortKeys(yyjson_mut_val *v) { pairs.emplace_back(key, child_val); } - // Sort by key string - std::sort(pairs.begin(), pairs.end(), - [](const std::pair &a, - const std::pair &b) { - const auto a_key = string_t(unsafe_yyjson_get_str(a.first), unsafe_yyjson_get_len(a.first)); - const auto b_key = string_t(unsafe_yyjson_get_str(b.first), unsafe_yyjson_get_len(b.first)); - return a_key < b_key; - }); + // Preserve the encounter order of equal keys for first-match lookups. + std::stable_sort(pairs.begin(), pairs.end(), + [](const std::pair &a, + const std::pair &b) { + const auto a_key = + string_t(unsafe_yyjson_get_str(a.first), unsafe_yyjson_get_len(a.first)); + const auto b_key = + string_t(unsafe_yyjson_get_str(b.first), unsafe_yyjson_get_len(b.first)); + return a_key < b_key; + }); // Recursively sort nested values for (auto &pair : pairs) { @@ -107,7 +109,7 @@ static void NormalizeFunction(DataChunk &args, ExpressionState &state, Vector &r ScalarFunctionSet JSONFunctions::GetNormalizeFunction() { ScalarFunctionSet set("json_normalize"); - ScalarFunction func({}, LogicalType::VARCHAR, NormalizeFunction, nullptr, nullptr, JSONFunctionLocalState::Init); + ScalarFunction func({}, LogicalType::JSON(), NormalizeFunction, nullptr, nullptr, JSONFunctionLocalState::Init); func.GetSignature().AddParameter("json", LogicalType::JSON()); diff --git a/src/duckdb/extension/parquet/include/thrift_tools.hpp b/src/duckdb/extension/parquet/include/thrift_tools.hpp index 6acf55002..d2e5ee620 100644 --- a/src/duckdb/extension/parquet/include/thrift_tools.hpp +++ b/src/duckdb/extension/parquet/include/thrift_tools.hpp @@ -132,7 +132,8 @@ struct ReadHeadComparator { struct ReadAheadBuffer { explicit ReadAheadBuffer(CachingFileHandle &file_handle_p, uint64_t accepted_column_gap = ReadHeadComparator::DEFAULT_ACCEPTED_COLUMN_GAP) - : merge_set(ReadHeadComparator(accepted_column_gap)), file_handle(file_handle_p) { + : merge_set(ReadHeadComparator(accepted_column_gap)), file_handle(file_handle_p), + file_size(file_handle.GetFileSize()) { } // The list of read heads. @@ -141,6 +142,7 @@ struct ReadAheadBuffer { std::set merge_set; CachingFileHandle &file_handle; + const idx_t file_size; idx_t total_size = 0; @@ -179,11 +181,10 @@ struct ReadAheadBuffer { merge_set.insert(&read_head); } - if (read_head.GetEnd() > file_handle.GetFileSize()) { + if (read_head.GetEnd() > file_size) { throw std::runtime_error("Prefetch registered for bytes outside file: " + file_handle.GetPath() + ", attempted range: [" + std::to_string(pos) + ", " + - std::to_string(read_head.GetEnd()) + - "), file size: " + std::to_string(file_handle.GetFileSize())); + std::to_string(read_head.GetEnd()) + "), file size: " + std::to_string(file_size)); } } @@ -225,7 +226,7 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra ThriftFileTransport(Context &context_p, CachingFileHandle &file_handle_p, bool prefetch_mode_p, uint64_t accepted_column_gap = ReadHeadComparator::DEFAULT_ACCEPTED_COLUMN_GAP) - : context(context_p), file_handle(file_handle_p), location(0), size(file_handle.GetFileSize()), + : context(context_p), file_handle(file_handle_p), location(0), ra_buffer(ReadAheadBuffer(file_handle, accepted_column_gap)), prefetch_mode(prefetch_mode_p) { } @@ -248,7 +249,8 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra } memcpy(buf, prefetch_buffer->GetData() + location - prefetch_buffer->location, len); } else if (prefetch_mode && len < PREFETCH_FALLBACK_BUFFERSIZE && len > 0) { - auto file_size = file_handle.GetFileSize(); + // Speculative prefetch must fit both the transport snapshot and the current file. + const auto file_size = MinValue(GetSize(), file_handle.GetFileSize()); if (location >= file_size) { file_handle.GetFileHandle()->Read(context, buf, len, location); location += len; @@ -340,7 +342,7 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra } idx_t GetSize() const { - return size; + return ra_buffer.file_size; } private: @@ -348,7 +350,6 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra CachingFileHandle &file_handle; idx_t location; - idx_t size; // Multi-buffer prefetch ReadAheadBuffer ra_buffer; diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index 36aa6aa8b..944424bfe 100644 --- a/src/duckdb/generated_extension_loader_package_build.cpp +++ b/src/duckdb/generated_extension_loader_package_build.cpp @@ -45,7 +45,7 @@ int32_t duckdb_extension_core_functions_describe(duckdb_extension_descriptor *de descriptor->version = 1; descriptor->name = "core_functions"; descriptor->extension_version = EXT_VERSION_CORE_FUNCTIONS; - descriptor->api_version = "v2.1.0-alpha59171"; + descriptor->api_version = "v2.1.0-alpha59204"; descriptor->entry_cpp = (void (*)(void))core_functions_duckdb_cpp_init; return 0; } @@ -78,7 +78,7 @@ int32_t duckdb_extension_parquet_describe(duckdb_extension_descriptor *descripto descriptor->version = 1; descriptor->name = "parquet"; descriptor->extension_version = EXT_VERSION_PARQUET; - descriptor->api_version = "v2.1.0-alpha59171"; + descriptor->api_version = "v2.1.0-alpha59204"; descriptor->entry_cpp = (void (*)(void))parquet_duckdb_cpp_init; return 0; } @@ -111,7 +111,7 @@ int32_t duckdb_extension_icu_describe(duckdb_extension_descriptor *descriptor) { descriptor->version = 1; descriptor->name = "icu"; descriptor->extension_version = EXT_VERSION_ICU; - descriptor->api_version = "v2.1.0-alpha59171"; + descriptor->api_version = "v2.1.0-alpha59204"; descriptor->entry_cpp = (void (*)(void))icu_duckdb_cpp_init; return 0; } @@ -144,7 +144,7 @@ int32_t duckdb_extension_json_describe(duckdb_extension_descriptor *descriptor) descriptor->version = 1; descriptor->name = "json"; descriptor->extension_version = EXT_VERSION_JSON; - descriptor->api_version = "v2.1.0-alpha59171"; + descriptor->api_version = "v2.1.0-alpha59204"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 636b5e351..fd293c613 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -181,9 +181,9 @@ #include "duckdb/optimizer/aggregate_rewrite.hpp" #include "duckdb/optimizer/build_probe_side_optimizer.hpp" #include "duckdb/optimizer/compressed_materialization.hpp" -#include "duckdb/optimizer/distinctness.hpp" #include "duckdb/optimizer/join_order/join_order_operator.hpp" #include "duckdb/optimizer/join_simplification.hpp" +#include "duckdb/optimizer/relation_properties.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics.hpp" #include "duckdb/optimizer/remove_unused_columns.hpp" #include "duckdb/optimizer/rule/like_optimizations.hpp" diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index 79ef33096..adfe22ad3 100644 --- a/src/duckdb/src/function/table/version/pragma_version.cpp +++ b/src/duckdb/src/function/table/version/pragma_version.cpp @@ -1,5 +1,5 @@ #ifndef DUCKDB_PATCH_VERSION -#define DUCKDB_PATCH_VERSION "0-alpha59171" +#define DUCKDB_PATCH_VERSION "0-alpha59204" #endif #ifndef DUCKDB_MINOR_VERSION #define DUCKDB_MINOR_VERSION 1 @@ -8,10 +8,10 @@ #define DUCKDB_MAJOR_VERSION 2 #endif #ifndef DUCKDB_VERSION -#define DUCKDB_VERSION "v2.1.0-alpha59171" +#define DUCKDB_VERSION "v2.1.0-alpha59204" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "0d4d6a99e5" +#define DUCKDB_SOURCE_ID "e7c006be8a" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp b/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp index 4ec9b4bf0..ecf234784 100644 --- a/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/apply_functional_dependencies.hpp @@ -10,7 +10,7 @@ #include "duckdb/planner/logical_operator_visitor.hpp" -#include "duckdb/optimizer/distinctness.hpp" +#include "duckdb/optimizer/relation_properties.hpp" #include "duckdb/planner/column_binding_map.hpp" namespace duckdb { @@ -18,16 +18,16 @@ namespace duckdb { struct BoundOrderByNode; //! Simplifies the keys of orderings and of window partitions / orderings using the unique column combinations of -//! their input. The unique column combinations themselves are inferred by Distinctness. +//! their input. The unique column combinations themselves are inferred by RelationProperties. class ApplyFunctionalDependencies : public LogicalOperatorVisitor { public: - ApplyFunctionalDependencies() : distinctness(DistinctnessPropagation::UNARY_OPERATORS) { + ApplyFunctionalDependencies() : properties(DistinctnessPropagation::UNARY_OPERATORS) { } //! The unique column combinations of the output of an operator static vector GetUniqueColumnCombinations(LogicalOperator &op) { - Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS); - return distinctness.GetUniqueSets(op); + RelationProperties properties(DistinctnessPropagation::UNARY_OPERATORS); + return properties.GetUniqueSets(op); } void VisitOperator(LogicalOperator &op) override; @@ -43,7 +43,7 @@ class ApplyFunctionalDependencies : public LogicalOperatorVisitor { //! The order keys and window partitions that this visitor rewrites are not read by the inference of unique sets, //! and no operator is replaced, so the cached unique sets stay valid during the visit - Distinctness distinctness; + RelationProperties properties; //! The unique column combinations of the input of the operator that is being simplified vector result; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp index 46edbc7a2..9feab99ef 100644 --- a/src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp @@ -8,8 +8,10 @@ #pragma once +#include "duckdb/common/helper.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/table_index.hpp" +#include "duckdb/common/unordered_map.hpp" #include @@ -53,4 +55,25 @@ class CTEDefinitionScope { lookup_t lookup; }; +//! A flat lexical overlay shared by iterative property and statistics walks. +class ScopedCTEDefinitions { +public: + ScopedCTEDefinitions(optional_ptr &active_scope, + optional_ptr outer); + ~ScopedCTEDefinitions(); + ScopedCTEDefinitions(const ScopedCTEDefinitions &) = delete; + ScopedCTEDefinitions &operator=(const ScopedCTEDefinitions &) = delete; + +public: + optional_ptr Push(LogicalOperator &op); + void Pop(LogicalOperator &op, optional_ptr previous); + +private: + optional_ptr &active_scope; + optional_ptr previous_scope; + const optional_ptr outer; + CTEDefinitionScope scope; + unordered_map> definitions; +}; + } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp index 60f4c924d..b872dda34 100644 --- a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp @@ -166,7 +166,7 @@ class DomainAnalysis { const vector empty_bindings; //! Shared estimators and lazy discovery caches use the same invalidation boundary. - Distinctness distinctness; + RelationProperties properties; RelationStatsExtractor statistics; unique_ptr filter_targets; unordered_map> scan_sources; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp index 687b7c202..22ed6b3d2 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp @@ -55,7 +55,7 @@ class JoinElimination : public LogicalOperatorVisitor { // 3. the join cannot change how often an outer row occurs in a way that is visible. There are two separate proofs: // a) the operators above ignore duplicates (PipelineInfo::ignores_duplicates): the join only repeats outer rows // b) every outer row matches at most one inner row: the inner side is distinct on the columns its equality - // conditions compare (Distinctness: a DISTINCT / GROUP BY, a PRIMARY KEY, also below filters and as the + // conditions compare (RelationProperties: a DISTINCT / GROUP BY, a PRIMARY KEY, also below filters and as the // result of an aggregate that was split into aggregates over a materialized CTE). This holds whatever is // above the join. A SINGLE join is only removed by this proof: it raises an error on a second match. unique_ptr Optimize(unique_ptr op); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp index 7690f32f3..7e1fad805 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp @@ -29,7 +29,7 @@ namespace duckdb { class JoinOrderOptimizer; class FilterInfo; class RelationStatsExtractor; -class Distinctness; +class RelationProperties; struct JoinOrderExtraction { vector> filters; @@ -105,7 +105,7 @@ class RelationManager { vector> &filter_operators, vector &pending_relations); bool RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats, - optional_ptr published_distinctness = nullptr); + optional_ptr published_properties = nullptr); optional_ptr GetJoinRelations(column_binding_set_t &column_bindings, JoinRelationSetManager &set_manager); void GetColumnBindingsFromExpression(const Expression &expression, column_binding_set_t &column_bindings); diff --git a/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_properties.hpp similarity index 78% rename from src/duckdb/src/include/duckdb/optimizer/distinctness.hpp rename to src/duckdb/src/include/duckdb/optimizer/relation_properties.hpp index 37861d271..333507a05 100644 --- a/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_properties.hpp @@ -1,7 +1,7 @@ //===----------------------------------------------------------------------===// // DuckDB // -// duckdb/optimizer/distinctness.hpp +// duckdb/optimizer/relation_properties.hpp // // //===----------------------------------------------------------------------===// @@ -14,6 +14,7 @@ #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/subquery/column_binding_layout.hpp" namespace duckdb { @@ -26,6 +27,14 @@ class LogicalGet; class LogicalOperator; class LogicalProjection; +//! One merge in a dependency-ordered sequence, with indices into the original requested columns. +//! A representative can itself be merged later: {1, 2}, {0, 1} is valid. Consumers that combine +//! numerical evidence must replay this order, rather than sort the merges or flatten representatives. +struct ColumnAlias { + idx_t representative; + idx_t alias; +}; + //! The operators that unique sets are forwarded through enum class DistinctnessPropagation : uint8_t { //! Filters, limits, orderings, windows and projections @@ -36,7 +45,8 @@ enum class DistinctnessPropagation : uint8_t { UNARY_OPERATORS_AND_JOINS }; -//! Structural proofs that the output of an operator has at most one row per value of a set of columns, where NULLs +//! Structural keys and direct aliases within an operator's output row stream. Statistics never establish a proof. +//! Unique sets have at most one row per value of a set of columns, where NULLs //! count as one value (like for DISTINCT and GROUP BY). This is the one place where unique sets are inferred. //! The sources are the groups of an aggregate with a single grouping set and the PRIMARY KEY / UNIQUE NOT NULL //! constraints of a scanned table. They are forwarded through operators that never duplicate rows (see @@ -45,7 +55,7 @@ enum class DistinctnessPropagation : uint8_t { //! bottom-up pass over a plan stays linear. After changing scanned columns, groups, projections or joins, discard //! the affected cached nodes and their ancestors with Invalidate before reusing the instance. Changing a resolved //! CTE definition also invalidates cached proofs for its references and their ancestors. -class Distinctness { +class RelationProperties { public: //! The maximum number of unique sets that a join forwards static constexpr idx_t MAX_UNIQUE_SETS = 32; @@ -53,17 +63,21 @@ class Distinctness { public: //! A context allows cast proofs that account for registered overrides. //! Supplying a CTE scope enables proofs through non-recursive CTE references. - explicit Distinctness(DistinctnessPropagation propagation, optional_ptr context = nullptr, - optional_ptr cte_scope = nullptr) + explicit RelationProperties(DistinctnessPropagation propagation, optional_ptr context = nullptr, + optional_ptr cte_scope = nullptr) : propagation(propagation), context(context), cte_scope(cte_scope) { } +public: //! Whether the output of the operator has at most one row per value of the keys bool IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys); //! Checks expression keys, including aliases and built-in injective casts. bool IsDistinctOn(LogicalOperator &op, const vector> &keys); //! The sets of columns the output of the operator is distinct on (cached) const vector &GetUniqueSets(LogicalOperator &op); + //! Proven alias merges in dependency order (see ColumnAlias). + //! Work is batched and independent of key inference; separate CTE references remain separate row streams. + vector GetColumnAliases(LogicalOperator &op, const vector &columns); //! Discard a changed node before refreshing it; callers must also discard all affected cached ancestors. void Invalidate(LogicalOperator &op); //! Gets the equality keys (= or IS NOT DISTINCT FROM) of the left (child_idx 0) or right (child_idx 1) side of a @@ -87,6 +101,7 @@ class Distinctness { const optional_ptr context; optional_ptr cte_scope; reference_map_t> unique_sets; + ColumnBindingLayoutCache layouts {ColumnBindingLayout::DuplicatePosition::FIRST}; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp index d4cf9770a..361e6e44d 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp @@ -115,7 +115,7 @@ struct RelationStats { //! Cumulative estimated fraction of rows retained from the most recent statistics source. //! Aggregation and DISTINCT establish a new source. CardinalityValue row_retention = 1; - //! Alternative unique keys from Distinctness, expressed as column indexes in this relation. + //! Alternative unique keys from RelationProperties, expressed as column indexes in this relation. vector> unique_keys; bool stats_initialized = false; Identifier table_name; diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp index e6c46cd9e..e0cdfd71e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp @@ -12,8 +12,9 @@ #include "duckdb/common/pair.hpp" #include "duckdb/common/reference_map.hpp" #include "duckdb/optimizer/cte_definition_scope.hpp" -#include "duckdb/optimizer/distinctness.hpp" +#include "duckdb/optimizer/relation_properties.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics.hpp" +#include "duckdb/planner/subquery/column_binding_layout.hpp" namespace duckdb { @@ -21,7 +22,6 @@ class ClientContext; class LogicalCTERef; class LogicalOperator; class JoinOrderSourceStats; -struct ColumnBindingLayout; using relation_stats_lookup_t = std::function(LogicalOperator &)>; @@ -34,7 +34,8 @@ class RelationStatsExtractor { CTEDefinitionScope::lookup_t cte_lookup = {}); //! Extract reads caller-owned facts and leaves missing entries unknown. RelationStatsExtractor(ClientContext &context, relation_stats_lookup_t lookup, - CTEDefinitionScope::lookup_t cte_lookup, optional_ptr distinctness = nullptr); + CTEDefinitionScope::lookup_t cte_lookup, + optional_ptr properties = nullptr); public: ClientContext &GetContext() const { @@ -49,9 +50,8 @@ class RelationStatsExtractor { //! Operator extraction counts and source capture apply to walking extractors. idx_t ExtractedOperatorCount() const; shared_ptr GetSourceStats(LogicalOperator &root); - Distinctness &GetDistinctness(); - optional_ptr GetPublishedDistinctness() const { - return lookup ? distinctness : nullptr; + optional_ptr GetPublishedProperties() const { + return lookup ? properties : nullptr; } //! Refine a grouping estimate using the domains of individual UNION arms. optional EstimateUnionGroups(LogicalOperator &input, vector groups); @@ -79,7 +79,6 @@ class RelationStatsExtractor { private: bool CanRefineUnionGroups(LogicalOperator &op); - const ColumnBindingLayout &GetGroupInputLayout(LogicalOperator &op); bool MapProjectionGroups(LogicalOperator &op, vector &groups); vector PrepareGroupEstimate(LogicalOperator &op, vector groups, GroupEstimate &estimate); optional ExtractInternal(LogicalOperator &op); @@ -102,14 +101,13 @@ class RelationStatsExtractor { shared_ptr source_stats; shared_ptr inherited_source_stats; - //! Distinctness proofs can be shared with the caller or owned by this extractor. - unique_ptr owned_distinctness; - optional_ptr distinctness; + //! Caller-owned proofs retain their propagation policy and lifetime. + optional_ptr properties; //! UNION grouping estimates by operator and key set, and their reusable input mappings. reference_map_t, GroupEstimate, GroupHash>> group_estimates; reference_map_t union_group_inputs; - reference_map_t> group_input_layouts; + ColumnBindingLayoutCache group_input_layouts {ColumnBindingLayout::DuplicatePosition::LAST}; reference_map_t> projection_groups; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/remove_redundant_distinct.hpp b/src/duckdb/src/include/duckdb/optimizer/remove_redundant_distinct.hpp index f812ed159..3f87d8e17 100644 --- a/src/duckdb/src/include/duckdb/optimizer/remove_redundant_distinct.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/remove_redundant_distinct.hpp @@ -9,7 +9,7 @@ #pragma once #include "duckdb/common/unique_ptr.hpp" -#include "duckdb/optimizer/distinctness.hpp" +#include "duckdb/optimizer/relation_properties.hpp" namespace duckdb { @@ -20,7 +20,7 @@ class LogicalOperator; //! groups, it is replaced by a projection of the groups. class RemoveRedundantDistinct { public: - RemoveRedundantDistinct() : distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS) { + RemoveRedundantDistinct() : properties(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS) { } void VisitOperator(unique_ptr &op); @@ -28,7 +28,7 @@ class RemoveRedundantDistinct { private: //! The operators are visited bottom-up, so the unique sets of an operator are only computed (and cached) after //! the operator and everything below it has been visited: an aggregate is replaced before it is asked about - Distinctness distinctness; + RelationProperties properties; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp b/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp index 6271ca4d8..2c2535197 100644 --- a/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp +++ b/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp @@ -8,18 +8,25 @@ #pragma once #include "duckdb/common/exception.hpp" +#include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/reference_map.hpp" +#include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/string.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/planner/column_binding_map.hpp" namespace duckdb { +class Expression; +class LogicalOperator; + struct ColumnBindingLayout { enum class DuplicatePosition { FIRST, LAST }; explicit ColumnBindingLayout(vector bindings_p, string error_context_p = "output layout", DuplicatePosition duplicate_position = DuplicatePosition::LAST) : bindings(std::move(bindings_p)), error_context(std::move(error_context_p)) { + positions.reserve(bindings.size()); for (idx_t i = 0; i < bindings.size(); i++) { if (duplicate_position == DuplicatePosition::FIRST) { positions.emplace(bindings[i], i); @@ -29,6 +36,14 @@ struct ColumnBindingLayout { } } + optional_idx TryGetPosition(const ColumnBinding &binding) const { + auto entry = positions.find(binding); + return entry == positions.end() ? optional_idx() : optional_idx(entry->second); + } + + //! Only an uncorrelated column reference; casts and positional references have separate admission rules. + optional_idx GetDirectColumnPosition(const Expression &expression) const; + idx_t GetPosition(const ColumnBinding &binding) const { auto entry = positions.find(binding); if (entry == positions.end()) { @@ -87,4 +102,22 @@ struct ColumnBindingLayout { string error_context; }; +//! Binding layouts are independent of property propagation policy and CTE resolution. +class ColumnBindingLayoutCache { +public: + explicit ColumnBindingLayoutCache(ColumnBindingLayout::DuplicatePosition duplicate_position) + : duplicate_position(duplicate_position) { + } + +public: + //! Composed join outputs are transient: retaining every joined prefix can require quadratic space. + shared_ptr Get(LogicalOperator &op); + //! Call for a changed operator and affected ancestors before reusing their layouts. + void Invalidate(LogicalOperator &op); + +private: + const ColumnBindingLayout::DuplicatePosition duplicate_position; + reference_map_t> layouts; +}; + } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp index 2c40a3879..72084848b 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp @@ -123,7 +123,7 @@ struct CachingFileHandle { shared_ptr EnsureCachedFileCurrent(); //! Whether validation metadata permits using cached blocks. bool CanUseCache(); - bool CanUseCache(const CacheValidationInfo &cached) const DUCKDB_REQUIRES(file_handle_mutex); + bool CanUseCache(const CacheValidationInfo &cached) const DUCKDB_REQUIRES_SHARED(file_handle_mutex); //! Read without caching, splitting large reads of cacheable files into parallel reads of at most a block. void ReadUncached(data_ptr_t buffer, idx_t nr_bytes, idx_t location); //! Reconcile cached blocks with validation metadata observed while reading them. @@ -147,14 +147,14 @@ struct CachingFileHandle { //! Cache validation mode for this file CacheValidationMode validate; //! Associated cached file. - shared_ptr cached_file; + shared_ptr cached_file DUCKDB_GUARDED_BY(file_handle_mutex); - //! Used to ensure file handle and cached file metadata is only initialized once. - annotated_mutex file_handle_mutex; + //! Protects handle initialization, cache adoption and the validation snapshot. + annotated_shared_mutex file_handle_mutex; //! File handle for the internal filesystem. - shared_ptr file_handle; + shared_ptr file_handle DUCKDB_GUARDED_BY(file_handle_mutex); //! Metadata snapshot taken with a single Stats call when the file handle is opened. - CacheValidationInfo validation_info; + CacheValidationInfo validation_info DUCKDB_GUARDED_BY(file_handle_mutex); //! Current position (if non-seeking reads) idx_t position; diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp index b07302f28..8667a2b75 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp @@ -80,7 +80,7 @@ class ExternalFileCache { const string path; const idx_t generation; - mutable annotated_mutex map_lock; + mutable annotated_shared_mutex map_lock; //! Non-overlapping cached blocks, keyed by file offset. map> blocks DUCKDB_GUARDED_BY(map_lock); //! Incremented whenever the blocks of the file are dropped. @@ -88,7 +88,7 @@ class ExternalFileCache { //! Memory reserved for the metadata of the blocks. TempBufferPoolReservation block_reservation DUCKDB_GUARDED_BY(map_lock); - mutable annotated_mutex meta_lock; + mutable annotated_shared_mutex meta_lock; //! Metadata for validating the cached blocks against the current file. CacheValidationInfo validation_info DUCKDB_GUARDED_BY(meta_lock); bool can_seek DUCKDB_GUARDED_BY(meta_lock) = false; diff --git a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp index 8994029b3..52b9392e5 100644 --- a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp +++ b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp @@ -10,7 +10,7 @@ namespace duckdb { void ApplyFunctionalDependencies::VisitLogicalOrder(LogicalOrder &order) { - result = distinctness.GetUniqueSets(*order.children[0]); + result = properties.GetUniqueSets(*order.children[0]); VisitOrderBys(order.orders); } @@ -174,7 +174,7 @@ void ApplyFunctionalDependencies::VisitOperator(LogicalOperator &op) { VisitLogicalOrder(op.Cast()); break; case LogicalOperatorType::LOGICAL_WINDOW: - result = distinctness.GetUniqueSets(*op.children[0]); + result = properties.GetUniqueSets(*op.children[0]); VisitOperatorExpressions(op); break; default: diff --git a/src/duckdb/src/optimizer/column_origin.cpp b/src/duckdb/src/optimizer/column_origin.cpp index 56066d260..e0acf7a15 100644 --- a/src/duckdb/src/optimizer/column_origin.cpp +++ b/src/duckdb/src/optimizer/column_origin.cpp @@ -1,6 +1,6 @@ #include "duckdb/optimizer/column_origin.hpp" -#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/subquery/column_binding_layout.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" @@ -124,12 +124,8 @@ vector> ColumnOriginHelper::GetTableColumnOrigins(Lo if (projection.children.size() != 1) { return {}; } - auto child_bindings = projection.children[0]->GetColumnBindings(); - column_binding_map_t child_indices; - child_indices.reserve(child_bindings.size()); - for (idx_t index = 0; index < child_bindings.size(); index++) { - child_indices.emplace(child_bindings[index], index); - } + ColumnBindingLayout layout(projection.children[0]->GetColumnBindings(), "column origin", + ColumnBindingLayout::DuplicatePosition::FIRST); for (auto &index : indices) { if (!index.IsValid()) { continue; @@ -137,10 +133,9 @@ vector> ColumnOriginHelper::GetTableColumnOrigins(Lo auto &expression = *projection.expressions[index.GetIndex()]; if (expression.GetExpressionClass() == ExpressionClass::BOUND_REF) { auto child_index = expression.Cast().Index(); - index = child_index < child_bindings.size() ? optional_idx(child_index) : optional_idx(); + index = child_index < layout.bindings.size() ? optional_idx(child_index) : optional_idx(); } else if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { - auto entry = child_indices.find(expression.Cast().Binding()); - index = entry != child_indices.end() ? optional_idx(entry->second) : optional_idx(); + index = layout.TryGetPosition(expression.Cast().Binding()); } else { index = optional_idx(); } diff --git a/src/duckdb/src/optimizer/cte_definition_scope.cpp b/src/duckdb/src/optimizer/cte_definition_scope.cpp new file mode 100644 index 000000000..28ca42402 --- /dev/null +++ b/src/duckdb/src/optimizer/cte_definition_scope.cpp @@ -0,0 +1,44 @@ +#include "duckdb/optimizer/cte_definition_scope.hpp" + +#include "duckdb/planner/operator/logical_materialized_cte.hpp" + +namespace duckdb { + +ScopedCTEDefinitions::ScopedCTEDefinitions(optional_ptr &active_scope, + optional_ptr outer) + : active_scope(active_scope), previous_scope(active_scope), outer(outer), scope([this](TableIndex index) { + auto entry = definitions.find(index); + return entry == definitions.end() ? (this->outer ? this->outer->Find(index) : nullptr) + : optional_ptr(entry->second); + }) { + active_scope = scope; +} + +ScopedCTEDefinitions::~ScopedCTEDefinitions() { + active_scope = previous_scope; +} + +optional_ptr ScopedCTEDefinitions::Push(LogicalOperator &op) { + if (op.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || op.children.size() != 2) { + return nullptr; + } + auto index = op.Cast().table_index; + auto entry = definitions.find(index); + optional_ptr previous = entry == definitions.end() ? nullptr : &entry->second.get(); + definitions.insert_or_assign(index, *op.children[0]); + return previous; +} + +void ScopedCTEDefinitions::Pop(LogicalOperator &op, optional_ptr previous) { + if (op.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || op.children.size() != 2) { + return; + } + auto index = op.Cast().table_index; + if (previous) { + definitions.insert_or_assign(index, *previous); + } else { + definitions.erase(index); + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp index 91a684b3c..dffd2f9a9 100644 --- a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp @@ -42,7 +42,7 @@ namespace duckdb { DomainAnalysis::DomainAnalysis(ClientContext &context_p) - : context(context_p), distinctness(DistinctnessPropagation::UNARY_OPERATORS, context_p), + : context(context_p), properties(DistinctnessPropagation::UNARY_OPERATORS, context_p), statistics( context_p, [this](LogicalOperator &op) { return Stats(op); }, [this](TableIndex index) -> optional_ptr { @@ -50,7 +50,7 @@ DomainAnalysis::DomainAnalysis(ClientContext &context_p) return owner && owner->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE ? owner->children[0].get() : nullptr; }, - distinctness) { + properties) { } DomainAnalysis::~DomainAnalysis() = default; @@ -361,7 +361,7 @@ void DomainAnalysis::Summarize(LogicalOperator &op) { } CaptureColumns(op, result); CaptureKeys(op, result); - distinctness.GetUniqueSets(op); + properties.GetUniqueSets(op); auto stats = EstimateStats(op, result); if (stats) { result.maximum_rows = stats->max_cardinality; @@ -595,7 +595,7 @@ optional_idx DomainAnalysis::BindingIndex(LogicalOperator &op, ColumnBinding bin } bool DomainAnalysis::IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys) { - return distinctness.IsDistinctOn(op, keys); + return properties.IsDistinctOn(op, keys); } optional_idx DomainAnalysis::ReferenceIndex(const Expression &expression, LogicalOperator &op) const { diff --git a/src/duckdb/src/optimizer/join_elimination.cpp b/src/duckdb/src/optimizer/join_elimination.cpp index d6cfe7ca2..b7f904105 100644 --- a/src/duckdb/src/optimizer/join_elimination.cpp +++ b/src/duckdb/src/optimizer/join_elimination.cpp @@ -3,7 +3,7 @@ #include "duckdb/common/enums/logical_operator_type.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/vector.hpp" -#include "duckdb/optimizer/distinctness.hpp" +#include "duckdb/optimizer/relation_properties.hpp" #include "duckdb/planner/column_binding.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -200,9 +200,9 @@ bool JoinElimination::TryEliminateJoin(unique_ptr &op) { // and so does a filter on the inner side, pushed into a scan or not: it only removes inner rows. // The plan below this join is not rewritten any more, so the unique sets are inferred on a stable plan column_binding_set_t inner_keys; - Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS); - is_removable = Distinctness::GetJoinEqualityKeys(join, inner_idx, inner_keys) && - distinctness.IsDistinctOn(*join.children[inner_idx], inner_keys); + RelationProperties properties(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS); + is_removable = RelationProperties::GetJoinEqualityKeys(join, inner_idx, inner_keys) && + properties.IsDistinctOn(*join.children[inner_idx], inner_keys); } if (is_removable) { op = LogicalJoin::PromoteJoinSide(std::move(join.children[outer_idx]), std::move(outer_projection_map)); diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index 957643c0b..0fc04f4c7 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -3,7 +3,7 @@ #include "duckdb/common/enums/join_type.hpp" #include "duckdb/common/enums/logical_operator_type.hpp" #include "duckdb/common/string_util.hpp" -#include "duckdb/optimizer/distinctness.hpp" +#include "duckdb/optimizer/relation_properties.hpp" #include "duckdb/optimizer/join_order/join_order_optimizer.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" @@ -95,7 +95,7 @@ const SingleJoinRelation &RelationManager::GetRelation(RelationIndex index) cons } bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats, - optional_ptr published_distinctness) { + optional_ptr published_properties) { D_ASSERT(!parent || parent->children.size() >= 2); if (!stats.stats_initialized || !stats.MatchesBindings(op.GetColumnBindings())) { stats_complete = false; @@ -107,13 +107,12 @@ bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptrrecursive_properties.depends_on_recursive_input; } RelationIndex relation_id(relations.size()); - Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, context, - cte_scope ? &*cte_scope : nullptr); - auto &unique_sets = - published_distinctness ? published_distinctness->GetUniqueSets(op) : distinctness.GetUniqueSets(op); + RelationProperties properties(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, context, + cte_scope ? &*cte_scope : nullptr); + auto &unique_sets = published_properties ? published_properties->GetUniqueSets(op) : properties.GetUniqueSets(op); auto &unique_keys = relation->stats.unique_keys; unique_keys.clear(); - unique_keys.reserve(MinValue(unique_sets.size(), Distinctness::MAX_UNIQUE_SETS)); + unique_keys.reserve(MinValue(unique_sets.size(), RelationProperties::MAX_UNIQUE_SETS)); for (auto &bindings : unique_sets) { vector key; key.reserve(bindings.size()); @@ -127,7 +126,7 @@ bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr GetInjectiveColumnBinding(const Expression &expre return GetInjectiveColumnBinding(BoundCastExpression::Child(cast), context); } -bool Distinctness::IsDistinctOn(LogicalOperator &op, const vector> &keys) { +bool RelationProperties::IsDistinctOn(LogicalOperator &op, const vector> &keys) { column_binding_set_t bindings; for (auto &key : keys) { auto binding = GetInjectiveColumnBinding(*key, context); @@ -65,7 +65,7 @@ bool Distinctness::IsDistinctOn(LogicalOperator &op, const vector current = op; reference_set_t visited_ctes; while (!keys.empty()) { @@ -98,7 +98,8 @@ bool Distinctness::IsDistinctOnProjectedKeys(LogicalOperator &op, column_binding if (!definition) { return false; } - auto bindings = definition->GetColumnBindings(); + auto layout = layouts.Get(*definition); + const auto &bindings = layout->bindings; if (bindings.size() != ref.chunk_types.size()) { return false; } @@ -116,11 +117,12 @@ bool Distinctness::IsDistinctOnProjectedKeys(LogicalOperator &op, column_binding return false; } -void Distinctness::Invalidate(LogicalOperator &op) { +void RelationProperties::Invalidate(LogicalOperator &op) { unique_sets.erase(op); + layouts.Invalidate(op); } -bool Distinctness::IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys) { +bool RelationProperties::IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys) { if (keys.empty()) { return false; } @@ -140,7 +142,8 @@ bool Distinctness::IsDistinctOn(LogicalOperator &op, const column_binding_set_t return false; } -bool Distinctness::GetJoinEqualityKeys(const LogicalComparisonJoin &join, idx_t child_idx, column_binding_set_t &keys) { +bool RelationProperties::GetJoinEqualityKeys(const LogicalComparisonJoin &join, idx_t child_idx, + column_binding_set_t &keys) { keys.clear(); for (auto &cond : join.conditions) { // other conditions only filter the matches @@ -161,7 +164,7 @@ bool Distinctness::GetJoinEqualityKeys(const LogicalComparisonJoin &join, idx_t return !keys.empty(); } -bool Distinctness::IsDistinctOnJoinKeys(LogicalComparisonJoin &join, idx_t child_idx) { +bool RelationProperties::IsDistinctOnJoinKeys(LogicalComparisonJoin &join, idx_t child_idx) { column_binding_set_t keys; if (!GetJoinEqualityKeys(join, child_idx, keys)) { return false; @@ -169,7 +172,7 @@ bool Distinctness::IsDistinctOnJoinKeys(LogicalComparisonJoin &join, idx_t child return IsDistinctOn(*join.children[child_idx], keys); } -vector Distinctness::ComputeJoinUniqueSets(LogicalComparisonJoin &join) { +vector RelationProperties::ComputeJoinUniqueSets(LogicalComparisonJoin &join) { vector result; switch (join.join_type) { case JoinType::SEMI: @@ -203,7 +206,7 @@ vector Distinctness::ComputeJoinUniqueSets(LogicalComparis } } -const vector &Distinctness::GetUniqueSets(LogicalOperator &op) { +const vector &RelationProperties::GetUniqueSets(LogicalOperator &op) { auto entry = unique_sets.find(op); if (entry != unique_sets.end()) { return entry->second; @@ -214,7 +217,7 @@ const vector &Distinctness::GetUniqueSets(LogicalOperator return result; } -vector Distinctness::ComputeScanUniqueSets(LogicalGet &get) { +vector RelationProperties::ComputeScanUniqueSets(LogicalGet &get) { // the PRIMARY KEY / UNIQUE NOT NULL constraints of a scanned table, if all of their columns are scanned vector result; // Table-in/out functions need not preserve the multiplicity of their input keys. @@ -269,7 +272,7 @@ vector Distinctness::ComputeScanUniqueSets(LogicalGet &get return result; } -vector Distinctness::ComputeAggregateUniqueSets(LogicalAggregate &aggr) { +vector RelationProperties::ComputeAggregateUniqueSets(LogicalAggregate &aggr) { // the groups of the grouping set of an aggregate with a single grouping set // TODO: use child FDs to simplify groupings. vector result; @@ -295,7 +298,7 @@ vector Distinctness::ComputeAggregateUniqueSets(LogicalAgg return result; } -vector Distinctness::ComputeProjectionUniqueSets(LogicalProjection &projection) { +vector RelationProperties::ComputeProjectionUniqueSets(LogicalProjection &projection) { // cache one representative output binding per input binding vector result; auto &child_sets = GetUniqueSets(*projection.children[0]); @@ -312,8 +315,8 @@ vector Distinctness::ComputeProjectionUniqueSets(LogicalPr return RemapUniqueSets(child_sets, forwarded); } -vector Distinctness::RemapUniqueSets(const vector &sets, - const column_binding_map_t &bindings) { +vector RelationProperties::RemapUniqueSets(const vector &sets, + const column_binding_map_t &bindings) { vector result; for (auto &child_set : sets) { column_binding_set_t key; @@ -333,7 +336,7 @@ vector Distinctness::RemapUniqueSets(const vector Distinctness::ComputeCTEUniqueSets(LogicalCTERef &cte_ref) { +vector RelationProperties::ComputeCTEUniqueSets(LogicalCTERef &cte_ref) { if (!cte_scope || cte_ref.is_recurring) { return {}; } @@ -345,7 +348,8 @@ vector Distinctness::ComputeCTEUniqueSets(LogicalCTERef &c if (sets.empty()) { return {}; } - auto bindings = definition->GetColumnBindings(); + auto layout = layouts.Get(*definition); + const auto &bindings = layout->bindings; if (bindings.size() != cte_ref.chunk_types.size()) { return {}; } @@ -356,7 +360,7 @@ vector Distinctness::ComputeCTEUniqueSets(LogicalCTERef &c return RemapUniqueSets(sets, forwarded); } -vector Distinctness::ComputeUniqueSets(LogicalOperator &op) { +vector RelationProperties::ComputeUniqueSets(LogicalOperator &op) { if (ForwardsChildUniqueSets(op.type, propagation)) { return GetUniqueSets(*op.children[0]); } diff --git a/src/duckdb/src/optimizer/relation_properties_aliases.cpp b/src/duckdb/src/optimizer/relation_properties_aliases.cpp new file mode 100644 index 000000000..5a67cf7f9 --- /dev/null +++ b/src/duckdb/src/optimizer/relation_properties_aliases.cpp @@ -0,0 +1,184 @@ +#include "duckdb/optimizer/relation_properties.hpp" + +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" +#include "duckdb/planner/operator/logical_order.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +class ColumnAliasResolver { +public: + ColumnAliasResolver(ColumnBindingLayoutCache &layouts, optional_ptr outer_scope) + : layouts(layouts), outer_scope(outer_scope) { + } + +public: + vector Resolve(LogicalOperator &input, const vector &columns) { + vector equivalences; + vector aliases; + equivalences.reserve(columns.size()); + aliases.reserve(columns.size()); + for (idx_t i = 0; i < columns.size(); i++) { + aliases.push_back({i, optional_idx(columns[i])}); + } + MergeColumnAliases(aliases, equivalences); + vector pending; + pending.push_back({input, std::move(aliases)}); + auto active_scope = outer_scope; + ScopedCTEDefinitions definitions(active_scope, outer_scope); + static constexpr idx_t MAX_VISITED_OPERATORS = 1024; + idx_t visited = 0; + while (!pending.empty() && visited < MAX_VISITED_OPERATORS) { + auto request = std::move(pending.back()); + pending.pop_back(); + auto &op = request.op.get(); + if (request.type == AliasRequestType::RESTORE_SCOPE) { + definitions.Pop(op, request.previous_definition); + continue; + } + visited++; + auto &aliases = request.aliases; + MergeColumnAliases(aliases, equivalences); + idx_t mapped_count = 0; + for (auto &alias : aliases) { + mapped_count += alias.position.IsValid(); + } + if (mapped_count < 2) { + continue; + } + if (TryMapUnaryAliases(op, aliases, equivalences)) { + pending.push_back({*op.children[0], std::move(aliases)}); + continue; + } + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + auto definition = ref.is_recurring ? nullptr : active_scope->Find(ref.cte_index); + if (definition && layouts.Get(*definition)->bindings.size() == ref.chunk_types.size()) { + pending.push_back({*definition, std::move(aliases)}); + continue; + } + } + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && op.children.size() == 2) { + auto previous = definitions.Push(op); + pending.push_back({op, {}, AliasRequestType::RESTORE_SCOPE, previous}); + pending.push_back({*op.children[1], std::move(aliases)}); + continue; + } + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN || + op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + AddJoinAliasRequests(op, aliases, pending); + } + } + return equivalences; + } + +private: + struct MappedAlias { + idx_t representative; + optional_idx position; + }; + + enum class AliasRequestType { TRACE, RESTORE_SCOPE }; + + struct AliasRequest { + reference op; + vector aliases; + AliasRequestType type = AliasRequestType::TRACE; + optional_ptr previous_definition; + }; + + static void MergeColumnAliases(vector &aliases, vector &equivalences) { + unordered_map positions; + positions.reserve(aliases.size()); + idx_t count = 0; + for (auto &alias : aliases) { + if (!alias.position.IsValid()) { + aliases[count++] = alias; + continue; + } + auto entry = positions.emplace(alias.position.GetIndex(), alias.representative); + if (entry.second) { + aliases[count++] = alias; + } else { + D_ASSERT(entry.first->second < alias.representative); + equivalences.push_back({entry.first->second, alias.representative}); + } + } + aliases.resize(count); + } + + bool TryMapUnaryAliases(LogicalOperator &op, vector &aliases, vector &equivalences) { + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION && op.children.size() == 1) { + auto layout = layouts.Get(*op.children[0]); + for (auto &alias : aliases) { + if (alias.position.IsValid()) { + auto index = alias.position.GetIndex(); + alias.position = index < op.expressions.size() + ? layout->GetDirectColumnPosition(*op.expressions[index]) + : optional_idx(); + } + } + // Unsupported expressions stop independently; already-proven aliases remain equal. + MergeColumnAliases(aliases, equivalences); + return true; + } + if ((op.type == LogicalOperatorType::LOGICAL_FILTER || op.type == LogicalOperatorType::LOGICAL_ORDER_BY) && + op.children.size() == 1) { + const auto &projection_map = op.type == LogicalOperatorType::LOGICAL_FILTER + ? op.Cast().projection_map + : op.Cast().projection_map; + if (!projection_map.empty()) { + for (auto &alias : aliases) { + if (alias.position.IsValid()) { + auto index = alias.position.GetIndex(); + alias.position = index < projection_map.size() ? optional_idx(projection_map[index].GetIndex()) + : optional_idx(); + } + } + MergeColumnAliases(aliases, equivalences); + } + return true; + } + if (op.type == LogicalOperatorType::LOGICAL_LIMIT && op.children.size() == 1) { + return true; + } + return false; + } + + void AddJoinAliasRequests(LogicalOperator &join, const vector &aliases, + vector &pending) { + auto output = layouts.Get(join); + // Each input is a separate row stream. Visit the left one first to preserve discovery order. + for (idx_t child_index = join.children.size(); child_index-- > 0;) { + auto &child = *join.children[child_index]; + auto layout = layouts.Get(child); + vector mapped; + for (auto alias : aliases) { + if (!alias.position.IsValid() || alias.position.GetIndex() >= output->bindings.size()) { + continue; + } + alias.position = layout->TryGetPosition(output->bindings[alias.position.GetIndex()]); + if (alias.position.IsValid()) { + mapped.push_back(alias); + } + } + if (mapped.size() > 1) { + pending.push_back({child, std::move(mapped)}); + } + } + } + +private: + ColumnBindingLayoutCache &layouts; + const optional_ptr outer_scope; +}; + +vector RelationProperties::GetColumnAliases(LogicalOperator &input, const vector &columns) { + ColumnAliasResolver resolver(layouts, cte_scope); + return resolver.Resolve(input, columns); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_aggregate.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_aggregate.cpp index 10c1d48f7..19b0af192 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_aggregate.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_aggregate.cpp @@ -3,51 +3,13 @@ #include "duckdb/common/unordered_map.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" -#include "duckdb/optimizer/distinctness.hpp" +#include "duckdb/optimizer/relation_properties.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/list.hpp" #include "duckdb/planner/operator/list.hpp" namespace duckdb { -class GroupingColumnMapper { -public: - explicit GroupingColumnMapper(LogicalOperator &child) { - auto child_bindings = child.GetColumnBindings(); - child_indexes.reserve(child_bindings.size()); - for (idx_t i = 0; i < child_bindings.size(); i++) { - child_indexes.emplace(child_bindings[i], i); - } - } - -public: - optional_idx GetChildIndex(LogicalOperator &projection, idx_t index) const { - if (index >= projection.expressions.size()) { - return {}; - } - auto &expr = *projection.expressions[index]; - if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return {}; - } - auto &column = expr.Cast(); - if (column.Depth() != 0) { - return {}; - } - return GetChildIndex(column.Binding()); - } - - optional_idx GetChildIndex(const ColumnBinding &binding) const { - auto match = child_indexes.find(binding); - if (match == child_indexes.end()) { - return {}; - } - return match->second; - } - -private: - column_binding_map_t child_indexes; -}; - CardinalityValue RelationStatisticsHelper::EstimateGroupCardinality(LogicalOperator &input, const RelationStats &input_stats, vector groups, @@ -69,149 +31,31 @@ CardinalityValue RelationStatisticsHelper::EstimateGroupCardinality(LogicalOpera return estimate; } -struct GroupingAlias { - idx_t group_index; - optional_idx mapped_index; -}; - -static optional_ptr TryMapJoinAliases(LogicalOperator &join, vector &aliases) { - auto bindings = join.GetColumnBindings(); - for (auto &child : join.children) { - GroupingColumnMapper mapper(*child); - vector mapped; - mapped.reserve(aliases.size()); - for (auto alias : aliases) { - if (alias.mapped_index.IsValid()) { - if (alias.mapped_index.GetIndex() >= bindings.size()) { - return nullptr; - } - alias.mapped_index = mapper.GetChildIndex(bindings[alias.mapped_index.GetIndex()]); - if (!alias.mapped_index.IsValid()) { - break; - } - } - mapped.push_back(alias); - } - if (mapped.size() == aliases.size()) { - // Stay on one input: separate references to the same CTE are separate row streams. - aliases = std::move(mapped); - return child.get(); - } +static void DeduplicateGroupingAliases(LogicalOperator &input, const RelationStats &input_stats, vector &groups, + RelationProperties &properties) { + if (groups.size() < 2) { + return; } - return nullptr; -} - -static void MergeGroupingAliases(vector &aliases, const RelationStats &input_stats) { - unordered_map factors; - factors.reserve(aliases.size()); + auto aliases = properties.GetColumnAliases(input, groups); + vector redundant(groups.size(), false); auto domain = [&](idx_t index) { auto count = input_stats.columns[index].current_domain.distinct_count; return count.IsZero() ? CardinalityValue(1) : count; }; - idx_t distinct_count = 0; for (auto &alias : aliases) { - if (!alias.mapped_index.IsValid()) { - aliases[distinct_count++] = alias; - continue; - } - auto entry = factors.emplace(alias.mapped_index.GetIndex(), distinct_count); - if (entry.second) { - aliases[distinct_count++] = alias; - } else { - auto &existing = aliases[entry.first->second].group_index; - if (domain(existing) > domain(alias.group_index)) { - existing = alias.group_index; - } + auto &representative = groups[alias.representative]; + if (domain(representative) > domain(groups[alias.alias])) { + representative = groups[alias.alias]; } + redundant[alias.alias] = true; } - aliases.resize(distinct_count); -} - -static void DeduplicateGroupingAliases(LogicalOperator &input, const RelationStats &input_stats, vector &groups, - RelationStatsExtractor &extractor) { - if (groups.size() < 2) { - return; - } - // Keep aliases proved along this row stream, even if traversal stops; retain the filtered input's domains. - vector aliases; - aliases.reserve(groups.size()); - for (auto index : groups) { - aliases.push_back({index, optional_idx(index)}); - } - MergeGroupingAliases(aliases, input_stats); - optional_ptr current = input; - unordered_map> local_definitions; - static constexpr idx_t MAX_VISITED_OPERATORS = 1024; - for (idx_t visited = 0; visited < MAX_VISITED_OPERATORS; visited++) { - auto &op = *current; - idx_t mapped_count = 0; - for (auto &alias : aliases) { - mapped_count += alias.mapped_index.IsValid(); - } - if (mapped_count < 2) { - break; + idx_t count = 0; + for (idx_t i = 0; i < groups.size(); i++) { + if (!redundant[i]) { + groups[count++] = groups[i]; } - if (op.type == LogicalOperatorType::LOGICAL_PROJECTION && op.children.size() == 1) { - GroupingColumnMapper mapper(*op.children[0]); - for (auto &alias : aliases) { - if (alias.mapped_index.IsValid()) { - alias.mapped_index = mapper.GetChildIndex(op, alias.mapped_index.GetIndex()); - } - } - // Unresolved expressions remain independent; keep aliases proved before they became unresolved. - MergeGroupingAliases(aliases, input_stats); - current = *op.children[0]; - continue; - } - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &ref = op.Cast(); - auto local = local_definitions.find(ref.cte_index); - auto definition = local == local_definitions.end() ? extractor.GetCTEDefinition(ref) : local->second.get(); - if (definition && definition->GetColumnBindings().size() == ref.chunk_types.size()) { - current = definition; - continue; - } - } - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && op.children.size() == 2) { - local_definitions.emplace(op.Cast().table_index, *op.children[0]); - current = *op.children[1]; - continue; - } - if ((op.type == LogicalOperatorType::LOGICAL_FILTER || op.type == LogicalOperatorType::LOGICAL_ORDER_BY) && - op.children.size() == 1) { - const auto &projection_map = op.type == LogicalOperatorType::LOGICAL_FILTER - ? op.Cast().projection_map - : op.Cast().projection_map; - if (!projection_map.empty()) { - for (auto &alias : aliases) { - if (alias.mapped_index.IsValid()) { - alias.mapped_index = projection_map[alias.mapped_index.GetIndex()].GetIndex(); - } - } - MergeGroupingAliases(aliases, input_stats); - } - current = *op.children[0]; - continue; - } - if (op.type == LogicalOperatorType::LOGICAL_LIMIT && op.children.size() == 1) { - current = *op.children[0]; - continue; - } - if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN || - op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { - auto child = TryMapJoinAliases(op, aliases); - if (child) { - MergeGroupingAliases(aliases, input_stats); - current = child; - continue; - } - } - break; - } - groups.clear(); - for (auto &alias : aliases) { - groups.push_back(alias.group_index); } + groups.resize(count); } static optional_ptr GetSelectedValueStats(const Expression &expression, @@ -237,8 +81,8 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate const RelationStats &child_stats, RelationStatsExtractor &extractor) { RelationColumnStatsLookup child_columns(child_stats); - Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, extractor.GetContext(), - &extractor.GetCTEScope()); + RelationProperties properties(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, extractor.GetContext(), + &extractor.GetCTEScope()); vector cardinality_counts; const auto has_multiple_grouping_sets = aggregate.grouping_sets.size() > 1; CardinalityValue grouping_sets_cardinality(0); @@ -280,7 +124,7 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate if (has_multiple_grouping_sets) { if (grouping_set.empty()) { grouping_sets_cardinality += CardinalityValue(1); - } else if (aggregate.children.size() == 1 && distinctness.IsDistinctOn(*aggregate.children[0], set_keys)) { + } else if (aggregate.children.size() == 1 && properties.IsDistinctOn(*aggregate.children[0], set_keys)) { grouping_sets_cardinality += child_stats.cardinality; } else { grouping_sets_cardinality += @@ -319,7 +163,7 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate for (auto &group : aggregate.groups) { groups.push_back(positions.at(group->Cast().Binding())); } - DeduplicateGroupingAliases(*aggregate.children[0], child_stats, groups, extractor); + DeduplicateGroupingAliases(*aggregate.children[0], child_stats, groups, properties); result.cardinality = RelationStatisticsHelper::EstimateGroupCardinality(*aggregate.children[0], child_stats, std::move(groups), extractor); } else { @@ -330,7 +174,7 @@ static optional ExtractAggregationStatsInternal(LogicalAggregate } bool has_unique_groups = false; if (preserves_group_evidence && !aggregate.groups.empty() && aggregate.children.size() == 1) { - has_unique_groups = distinctness.IsDistinctOn(*aggregate.children[0], aggregate.groups); + has_unique_groups = properties.IsDistinctOn(*aggregate.children[0], aggregate.groups); if (has_unique_groups) { result.cardinality = child_stats.cardinality; } diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp index 559f2436f..b45910df5 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp @@ -15,54 +15,6 @@ namespace duckdb { -class GroupingCTEScope { -public: - GroupingCTEScope(optional_ptr &active_scope, const CTEDefinitionScope &outer) - : active_scope(active_scope), previous_scope(active_scope), outer(outer), scope([this](TableIndex index) { - auto entry = definitions.find(index); - return entry == definitions.end() ? this->outer.Find(index) - : optional_ptr(entry->second); - }) { - active_scope = scope; - } - ~GroupingCTEScope() { - active_scope = previous_scope; - } - -public: - optional_ptr Push(LogicalOperator &op) { - if (op.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || op.children.size() != 2) { - return nullptr; - } - auto index = op.Cast().table_index; - auto entry = definitions.find(index); - optional_ptr previous = entry == definitions.end() ? nullptr : &entry->second.get(); - definitions.insert_or_assign(index, *op.children[0]); - return previous; - } - void Pop(LogicalOperator &op, optional_ptr previous) { - if (op.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || op.children.size() != 2) { - return; - } - auto index = op.Cast().table_index; - if (previous) { - definitions.insert_or_assign(index, *previous); - } else { - definitions.erase(index); - } - } - -private: - //! Restore the caller's scope after this grouping walk, including on failure. - optional_ptr &active_scope; - optional_ptr previous_scope; - const CTEDefinitionScope &outer; - CTEDefinitionScope scope; - - //! A flat map keeps local lookups independent of materialized CTE nesting depth. - unordered_map> definitions; -}; - RelationStatsExtractor::RelationStatsExtractor(ClientContext &context) : context(context) { } @@ -78,28 +30,20 @@ RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, relation_stats_lookup_t lookup_p, CTEDefinitionScope::lookup_t cte_lookup, - optional_ptr distinctness_p) - : context(context), cte_scope(std::move(cte_lookup)), lookup(std::move(lookup_p)), distinctness(distinctness_p) { + optional_ptr properties_p) + : context(context), cte_scope(std::move(cte_lookup)), lookup(std::move(lookup_p)), properties(properties_p) { D_ASSERT(lookup); } -Distinctness &RelationStatsExtractor::GetDistinctness() { - if (!distinctness) { - owned_distinctness = make_uniq(DistinctnessPropagation::UNARY_OPERATORS, context); - distinctness = owned_distinctness.get(); - } - return *distinctness; -} - void RelationStatsExtractor::Invalidate(LogicalOperator &op) { cache.erase(op); failed_operators.erase(op); group_estimates.erase(op); union_group_inputs.erase(op); - group_input_layouts.erase(op); + group_input_layouts.Invalidate(op); projection_groups.erase(op); - if (distinctness) { - distinctness->Invalidate(op); + if (properties) { + properties->Invalidate(op); } } @@ -112,7 +56,7 @@ uint64_t RelationStatsExtractor::GroupHash::operator()(const vector &grou } bool RelationStatsExtractor::CanRefineUnionGroups(LogicalOperator &op) { - GroupingCTEScope scope(local_cte_scope, GetCTEScope()); + ScopedCTEDefinitions scope(local_cte_scope, GetCTEScope()); vector> path; optional_ptr current = op; bool result = false; @@ -144,45 +88,13 @@ bool RelationStatsExtractor::CanRefineUnionGroups(LogicalOperator &op) { return result; } -const ColumnBindingLayout &RelationStatsExtractor::GetGroupInputLayout(LogicalOperator &op) { - vector> path; - reference current = op; - shared_ptr layout; - while (true) { - auto entry = group_input_layouts.find(current); - if (entry != group_input_layouts.end()) { - layout = entry->second; - break; - } - auto &node = current.get(); - path.push_back(node); - if (node.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || node.children.size() != 2) { - layout = make_shared_ptr(node.GetColumnBindings()); - break; - } - current = *node.children[1]; - } - for (auto &node : path) { - group_input_layouts.emplace(node, layout); - } - return *layout; -} - bool RelationStatsExtractor::MapProjectionGroups(LogicalOperator &op, vector &groups) { auto entry = projection_groups.find(op); if (entry == projection_groups.end()) { vector mapping(op.expressions.size()); - auto &columns = GetGroupInputLayout(*op.children[0]).positions; + auto layout = group_input_layouts.Get(*op.children[0]); for (idx_t index = 0; index < op.expressions.size(); index++) { - auto &expression = *op.expressions[index]; - if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - continue; - } - auto &column = expression.Cast(); - auto match = columns.find(column.Binding()); - if (column.Depth() == 0 && match != columns.end()) { - mapping[index] = match->second; - } + mapping[index] = layout->GetDirectColumnPosition(*op.expressions[index]); } entry = projection_groups.emplace(op, std::move(mapping)).first; } @@ -225,7 +137,7 @@ RelationStatsExtractor::PrepareGroupEstimate(LogicalOperator &op, vector } else if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { auto &ref = op.Cast(); auto definition = GetCTEDefinition(ref); - if (!definition || GetGroupInputLayout(*definition).bindings.size() != ref.chunk_types.size()) { + if (!definition || group_input_layouts.Get(*definition)->bindings.size() != ref.chunk_types.size()) { estimate.cardinality = {}; } else { inputs.emplace_back(*definition, std::move(groups)); @@ -235,7 +147,7 @@ RelationStatsExtractor::PrepareGroupEstimate(LogicalOperator &op, vector } else if (op.type == LogicalOperatorType::LOGICAL_UNION) { estimate.has_union = true; for (auto &child : op.children) { - if (GetGroupInputLayout(*child).bindings.size() != op.Cast().column_count) { + if (group_input_layouts.Get(*child)->bindings.size() != op.Cast().column_count) { estimate.cardinality = {}; inputs.clear(); break; @@ -289,7 +201,7 @@ optional RelationStatsExtractor::EstimateUnionGroups(LogicalOp return {}; } auto &root_estimate = *root.first; - GroupingCTEScope scope(local_cte_scope, GetCTEScope()); + ScopedCTEDefinitions scope(local_cte_scope, GetCTEScope()); vector stack; auto push_frame = [&](LogicalOperator &op, vector keys, GroupEstimate &estimate) { auto previous = scope.Push(op); diff --git a/src/duckdb/src/optimizer/remove_redundant_distinct.cpp b/src/duckdb/src/optimizer/remove_redundant_distinct.cpp index 5fb0eca5d..a083aade7 100644 --- a/src/duckdb/src/optimizer/remove_redundant_distinct.cpp +++ b/src/duckdb/src/optimizer/remove_redundant_distinct.cpp @@ -38,7 +38,7 @@ void ReplaceByProjection(unique_ptr &op) { } // namespace void RemoveRedundantDistinct::VisitOperator(unique_ptr &op) { - // bottom-up, so that the distinctness of an input is derived from its already reduced children + // bottom-up, so that the properties of an input is derived from its already reduced children for (auto &child : op->children) { VisitOperator(child); } @@ -53,7 +53,7 @@ void RemoveRedundantDistinct::VisitOperator(unique_ptr &op) { } keys.insert(group->Cast().Binding()); } - if (!distinctness.IsDistinctOn(*aggr.children[0], keys)) { + if (!properties.IsDistinctOn(*aggr.children[0], keys)) { return; } ReplaceByProjection(op); diff --git a/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp index 763c02457..871b44214 100644 --- a/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp @@ -157,8 +157,8 @@ static bool ApplyWindowToMacroAggregate(unique_ptr &expr, Func // One FILTER from the MACRO window_expr.FilterMutable() = std::move(agg_fn_expr.FilterMutable()); } - // Transfer argument ORDER BYs - if (agg_fn_expr.OrderBy()) { + // An explicit ORDER BY in the macro body takes precedence over the caller's. + if (agg_fn_expr.OrderBy() && !agg_fn_expr.OrderBy()->orders.empty()) { window_expr.ArgOrdersMutable() = std::move(agg_fn_expr.OrderByMutable()->orders); } diff --git a/src/duckdb/src/planner/sql_export/sql_export_sources.cpp b/src/duckdb/src/planner/sql_export/sql_export_sources.cpp index 6a92ee17c..5293070b8 100644 --- a/src/duckdb/src/planner/sql_export/sql_export_sources.cpp +++ b/src/duckdb/src/planner/sql_export/sql_export_sources.cpp @@ -2,16 +2,27 @@ #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/sql_export/logical_plan_sql_exporter_internal.hpp" #include "duckdb/planner/logical_plan_sql_exporter.hpp" +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" +#include "duckdb/common/exception/binder_exception.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/main/settings.hpp" #include "duckdb/parser/expression/conjunction_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/tableref/basetableref.hpp" #include "duckdb/parser/tableref/at_clause.hpp" #include "duckdb/parser/query_node/select_node.hpp" #include "duckdb/planner/bound_expression_sql_exporter.hpp" +#include "duckdb/planner/collation_binding.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression_binder.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_limit.hpp" #include "duckdb/planner/operator/logical_top_n.hpp" #include "duckdb/planner/operator/logical_extension_operator.hpp" @@ -28,6 +39,315 @@ static LogicalPlanVerificationIssue ExtensionIssue(LogicalPlanVerificationIssueC std::move(message)); } +//! How binding an expression again treats the collations its operands state +enum class OperandCollations : uint8_t { + //! they are not looked at + IGNORED, + //! those of the VARCHAR operands are combined into the collation of the result + PROPAGATED, + //! they are combined, and the key functions of the combinable ones are pushed into the operands + PUSHED_COMBINABLE, + //! they are combined, and their key functions are pushed into the operands + PUSHED +}; + +static OperandCollations GetOperandCollations(const Expression &expr) { + switch (expr.GetExpressionClass()) { + case ExpressionClass::BOUND_OPERATOR: + // the parser writes NOT IN as the negation of IN, a parsed expression built elsewhere can still hold it + return expr.GetExpressionType() == ExpressionType::COMPARE_IN || + expr.GetExpressionType() == ExpressionType::COMPARE_NOT_IN + ? OperandCollations::PUSHED + : OperandCollations::IGNORED; + case ExpressionClass::BOUND_FUNCTION: + break; + default: + return OperandCollations::IGNORED; + } + if (expr.GetExpressionType() != ExpressionType::BOUND_FUNCTION) { + return expr.GetExpressionType() == ExpressionType::COMPARE_BETWEEN || + BoundComparisonExpression::IsComparison(expr.GetExpressionType()) + ? OperandCollations::PUSHED + : OperandCollations::IGNORED; + } + switch (expr.Cast().Function().GetCollationHandling()) { + case FunctionCollationHandling::IGNORE_COLLATIONS: + return OperandCollations::IGNORED; + case FunctionCollationHandling::PROPAGATE_COLLATIONS: { + auto &type = expr.GetReturnType(); + return type.id() == LogicalTypeId::VARCHAR && !type.HasAlias() ? OperandCollations::PROPAGATED + : OperandCollations::IGNORED; + } + case FunctionCollationHandling::PUSH_COMBINABLE_COLLATIONS: + return OperandCollations::PUSHED_COMBINABLE; + case FunctionCollationHandling::PUSH_DISTINCT_COLLATIONS: + throw InternalException("PUSH_DISTINCT_COLLATIONS is only supported for aggregate functions"); + } + throw InternalException("Unrecognized collation handling"); +} + +//! The collations the VARCHAR leaves of the operands of an expression state. A leaf is what the binder combines and +//! pushes collations into (ExtractCollationFromType in function_binder.cpp): the VARCHARs of lists, arrays and +//! structs, not those of an aliased type. +struct StatedCollations { + //! The first collation stated, empty if no leaf states one + string collation; + //! Whether two leaves state different collations. The binder refuses that for leaves it combines. It combines + //! the leaves of each struct field apart from the others, which is not told apart here. + bool differ = false; + //! Whether a leaf states none: the default collation applies to it unless a leaf it is combined with states one + bool has_default = false; + //! Whether a leaf is in a struct field, so that not all leaves are combined with each other + bool has_fields = false; + + void Add(const LogicalType &type) { + if (type.HasAlias()) { + return; + } + switch (type.id()) { + case LogicalTypeId::VARCHAR: { + auto stated = StringType::GetCollation(type); + has_default |= stated.empty(); + if (collation.empty()) { + collation = std::move(stated); + } else if (!stated.empty() && stated != collation) { + differ = true; + } + break; + } + case LogicalTypeId::LIST: + Add(ListType::GetChildType(type)); + break; + case LogicalTypeId::ARRAY: + Add(ArrayType::GetChildType(type)); + break; + case LogicalTypeId::STRUCT: + case LogicalTypeId::TUPLE: + for (auto &child : StructType::GetChildTypes(type)) { + has_fields = true; + Add(child.second); + } + break; + default: + break; + } + } +}; + +//! The type with its VARCHAR leaves stated under the collation: those that name a collation, and with state_default +//! those that name none as well +static LogicalType StateCollation(const LogicalType &type, const string &collation, bool state_default) { + if (type.HasAlias()) { + return type; + } + switch (type.id()) { + case LogicalTypeId::VARCHAR: + if (!state_default && StringType::GetCollation(type).empty()) { + return type; + } + return LogicalType::VARCHAR_COLLATION(collation); + case LogicalTypeId::LIST: + return LogicalType::LIST(StateCollation(ListType::GetChildType(type), collation, state_default)); + case LogicalTypeId::ARRAY: + return LogicalType::ARRAY(StateCollation(ArrayType::GetChildType(type), collation, state_default), + ArrayType::GetSize(type)); + case LogicalTypeId::STRUCT: + case LogicalTypeId::TUPLE: { + auto children = StructType::GetChildTypes(type); + for (auto &child : children) { + child.second = StateCollation(child.second, collation, state_default); + } + // a struct without member names is a tuple again + return LogicalType::STRUCT(std::move(children)); + } + default: + return type; + } +} + +//! A pushed filter is evaluated on the stored values. The collation functions its predicate was bound with are part +//! of the expression, and nothing in it collates beyond them, whatever collations the types of its operands still +//! name. The reference to a VARCHAR column does not even carry the type it was bound with: the export writes it +//! under the collation the column declares. Bound again, an expression that pushes collations takes the one its +//! operands state, or the default collation where they state none, and one that propagates them refuses operands +//! that state different ones. +//! +//! An expression whose operands, as they are written, bind without a key function being pushed is left as it is. +//! The operands of any other are stated under one collation that pushes none, down to the VARCHAR leaves of a nested +//! constant. That collation is the one the column declares where the reference to the column is one of the operands +//! and its collation pushes none into the expression, and binary otherwise. Planning the generated statement types +//! the reference to the column from the column again, and a function that is bound once more after that (plan +//! deserialization) refuses a sibling that names another collation. +//! +//! A collation is only asked about where the text depends on the answer. One the session cannot resolve (its +//! extension is not loaded) is taken to push a key function, and so is one the binder refuses: the operands are then +//! stated as binary, which needs no knowledge of it. The export loads no extension, and it adds no collation to an +//! operand that the session cannot resolve. +class ScanFilterCollation { +public: + ScanFilterCollation(ClientContext &context_p, const LogicalType &column_type) : context(context_p) { + if (column_type.id() == LogicalTypeId::VARCHAR && !column_type.HasAlias()) { + column_collation = StringType::GetCollation(column_type); + } + } + + void Restate(Expression &expr) { + ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { Restate(child); }); + const auto combination = GetOperandCollations(expr); + if (combination == OperandCollations::IGNORED) { + return; + } + const bool propagates = combination == OperandCollations::PROPAGATED; + const auto pushed = combination == OperandCollations::PUSHED_COMBINABLE ? CollationType::COMBINABLE_COLLATIONS + : CollationType::ALL_COLLATIONS; + StatedCollations stated; + bool combines_column = false; + ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { + if (Combines(child, propagates)) { + stated.Add(child.GetReturnType()); + combines_column |= child.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF; + } + }); + if (stated.collation.empty() && !stated.has_default) { + // no strings are combined + return; + } + // The default collation is pushed, and never propagated. It is asked about once, and not before the text + // depends on it. + bool state_default = false; + bool default_is_known = propagates || !stated.has_default; + auto pushes_default = [&]() { + if (!default_is_known) { + state_default = PushesKeyFunctions(string(), pushed); + default_is_known = true; + } + return state_default; + }; + if (!stated.differ) { + // A leaf that states no collation takes the one a leaf it is combined with states. Only the leaves of a + // struct field are combined apart from the others: there a leaf can take the default collation beside a + // stated one. + const bool takes_default = (stated.collation.empty() || stated.has_fields) && pushes_default(); + const bool pushes_key_functions = takes_default || (!propagates && !stated.collation.empty() && + PushesKeyFunctions(stated.collation, pushed)); + if (!pushes_key_functions) { + // binds to the expression it is + return; + } + } + // The collation of the column matters where the reference to the column is an operand itself: that reference + // is what planning the generated statement types from the column again. A collation that is propagated pushes + // nothing, and the generated statement still has to resolve it. + const bool keeps_column_collation = + combines_column && !column_collation.empty() && + (propagates ? IsResolvable(column_collation) : !PushesKeyFunctions(column_collation, pushed)); + const string collation = keeps_column_collation ? column_collation : "binary"; + StatedCollations nested; + if (StateOperands(expr, propagates, collation, pushes_default(), nested)) { + return; + } + // Only a VARCHAR expression or a constant can be stated under another type than its own. A nested column and + // a nested function result are written under the type they were bound with. The other operands can still be + // stated under the collation such an operand states, if that pushes nothing. If not, the expression is left + // as it is: its nested operands state what it combined them under. + if (nested.differ || nested.collation.empty() || PushesKeyFunctions(nested.collation, pushed)) { + return; + } + StatedCollations unused; + StateOperands(expr, propagates, nested.collation, pushes_default(), unused); + } + +private: + //! Whether the collation of the operand is combined: only those of VARCHAR arguments are propagated + static bool Combines(const Expression &operand, bool propagates) { + auto &type = operand.GetReturnType(); + return !propagates || (type.id() == LogicalTypeId::VARCHAR && !type.HasAlias()); + } + + //! Whether the session has the functions of the collation, or of the default collation if it is empty. The binder + //! resolves the names as GetVarcharCollationFunctions in collation_binding.cpp does, and loads the extension of + //! one that is missing. A default collation set when the database was opened has not been resolved yet. + bool IsResolvable(const string &collation) { + auto name = StringUtil::Lower(collation.empty() ? Settings::Get(context) : collation); + if (name.empty() || name == "binary" || name == "c" || name == "posix") { + // no function is looked up + return true; + } + // The functions are looked up in their schema. A lookup through the catalog loads the extension that registers + // a function of a missing name in any schema, and collations share names with functions (chr, ln). + auto &catalog = Catalog::GetSystemCatalog(context); + auto schema = catalog.GetSchema(context, CollationFunctions::GetSchema(), OnEntryNotFound::RETURN_NULL); + if (!schema) { + return false; + } + auto transaction = catalog.GetCatalogTransaction(context); + for (auto &part : StringUtil::Split(name, ".")) { + if (!schema->GetEntry(transaction, CatalogType::SCALAR_FUNCTION_ENTRY, Identifier(part))) { + return false; + } + } + return true; + } + + //! Whether the binder pushes a key function into an operand that states the collation, or none if it is empty. + //! A collation the session cannot resolve is taken to push one, and so is one the binder refuses: the names of + //! a default collation set when the database was opened can resolve and not combine. + bool PushesKeyFunctions(const string &collation, CollationType pushed) { + if (!IsResolvable(collation)) { + return true; + } + auto type = collation.empty() ? LogicalType::VARCHAR : LogicalType::VARCHAR_COLLATION(collation); + unique_ptr operand = make_uniq(Value(type)); + try { + return ExpressionBinder::PushCollation(context, operand, type, pushed); + } catch (const BinderException &) { + return true; + } + } + + //! States the operands of the expression under the collation. States none and returns false if that takes + //! another type for a nested operand that is not a constant: nested then holds what those operands state. + static bool StateOperands(Expression &expr, bool propagates, const string &collation, bool state_default, + StatedCollations &nested) { + vector> operands; + vector types; + bool keeps_nested_operand = false; + ExpressionIterator::EnumerateChildren(expr, [&](Expression &child) { + if (!Combines(child, propagates)) { + return; + } + auto &type = child.GetReturnType(); + const bool is_restatable = + type.id() == LogicalTypeId::VARCHAR || child.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT; + if (!is_restatable) { + nested.Add(type); + } + auto restated = StateCollation(type, collation, state_default); + if (type.EqualsIncludingCollation(restated)) { + return; + } + if (!is_restatable) { + keeps_nested_operand = true; + return; + } + operands.push_back(child); + types.push_back(std::move(restated)); + }); + if (keeps_nested_operand) { + return false; + } + for (idx_t i = 0; i < operands.size(); i++) { + // the setter of a constant states the type of its value as well, which is what a constant is exported under + operands[i].get().SetReturnType(std::move(types[i])); + } + return true; + } + + ClientContext &context; + //! The collation the column of the filter declares + string column_collation; +}; + LogicalPlanSQLExportResult LogicalGet::ExportSQLSource(LogicalPlanSQLExportContext &export_context, const LogicalPlanVerificationPath &path, optional_ptr ordinality) { @@ -134,6 +454,7 @@ LogicalPlanSQLExportResult LogicalGet::ExportSQLSource(LogicalPlanSQLExportConte auto &field = source.relation.fields[entry.GetIndex().GetIndex()]; BoundColumnRefExpression column(field.type, field.source_binding); predicates.push_back(entry.Filter().ToExpression(column)); + ScanFilterCollation(export_context.GetClientContext(), field.type).Restate(*predicates.back()); } auto conjunction = make_uniq(ExpressionType::CONJUNCTION_AND); auto ordinal = LogicalPlanSQLExportHelpers::CollectExpressions(get).size(); diff --git a/src/duckdb/src/planner/subquery/column_binding_layout.cpp b/src/duckdb/src/planner/subquery/column_binding_layout.cpp new file mode 100644 index 000000000..8f8950805 --- /dev/null +++ b/src/duckdb/src/planner/subquery/column_binding_layout.cpp @@ -0,0 +1,78 @@ +#include "duckdb/planner/subquery/column_binding_layout.hpp" + +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/logical_operator.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_order.hpp" + +namespace duckdb { + +optional_idx ColumnBindingLayout::GetDirectColumnPosition(const Expression &expression) const { + if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return {}; + } + auto &column = expression.Cast(); + return column.Depth() == 0 ? TryGetPosition(column.Binding()) : optional_idx(); +} + +static bool HasLocalColumnLayout(LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_GET: + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + case LogicalOperatorType::LOGICAL_CTE_REF: + return true; + default: + return false; + } +} + +static optional_ptr GetLayoutInput(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && op.children.size() == 2) { + return *op.children[1]; + } + if (op.children.size() != 1) { + return nullptr; + } + if (op.type == LogicalOperatorType::LOGICAL_LIMIT || + (op.type == LogicalOperatorType::LOGICAL_FILTER && op.Cast().projection_map.empty()) || + (op.type == LogicalOperatorType::LOGICAL_ORDER_BY && op.Cast().projection_map.empty())) { + return *op.children[0]; + } + return nullptr; +} + +shared_ptr ColumnBindingLayoutCache::Get(LogicalOperator &op) { + vector> path; + reference current = op; + shared_ptr layout; + while (true) { + auto entry = layouts.find(current); + if (entry != layouts.end()) { + layout = entry->second; + break; + } + auto &node = current.get(); + path.push_back(node); + auto child = GetLayoutInput(node); + if (!child) { + layout = + make_shared_ptr(node.GetColumnBindings(), "output layout", duplicate_position); + if (!HasLocalColumnLayout(node)) { + return layout; + } + break; + } + current = *child; + } + for (auto &node : path) { + layouts.emplace(node, layout); + } + return layout; +} + +void ColumnBindingLayoutCache::Invalidate(LogicalOperator &op) { + layouts.erase(op); +} + +} // namespace duckdb diff --git a/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp b/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp index 48e5b1d10..bffc7c3b4 100644 --- a/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp +++ b/src/duckdb/src/planner/subquery/delim_join_cte_rewriter.cpp @@ -8,6 +8,7 @@ #include "duckdb/planner/subquery/delim_join_cte_rewriter.hpp" +#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/common/enums/optimizer_type.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/query_profiler.hpp" @@ -1290,11 +1291,13 @@ struct GeneratedDomainReplacement { } }; +enum class EvidenceDomainPreservation { NONE, PRESERVE, SIMPLE_NEGATED_FILTER }; + class GeneratedDedupRefEliminator { public: GeneratedDedupRefEliminator(Binder &binder, unique_ptr &delim_join_op, TableIndex dedup_cte_index, - idx_t dedup_ref_count, LogicalOperator &rewrite_root, bool preserve_evidence_side, - bool preserve_nested_evidence_side); + idx_t dedup_ref_count, LogicalOperator &rewrite_root, + EvidenceDomainPreservation evidence_preservation, bool preserve_nested_evidence_side); idx_t Remove(); @@ -1309,6 +1312,8 @@ class GeneratedDedupRefEliminator { idx_t dedup_idx); bool RewriteJoin(unique_ptr &join, BindingReplacementGraph &replacements, GeneratedDomainAction action); + bool CanRemoveNegatedMembership(LogicalOperator &input, const GeneratedDomainRef &domain, + const vector &conditions) const; private: Binder &binder; @@ -1317,18 +1322,19 @@ class GeneratedDedupRefEliminator { TableIndex dedup_cte_index; idx_t dedup_ref_count; LogicalOperator &rewrite_root; - bool preserve_evidence_side; + EvidenceDomainPreservation evidence_preservation; bool preserve_nested_evidence_side; vector, idx_t>> consumer_path; }; GeneratedDedupRefEliminator::GeneratedDedupRefEliminator(Binder &binder, unique_ptr &delim_join_op, TableIndex dedup_cte_index, idx_t dedup_ref_count, - LogicalOperator &rewrite_root, bool preserve_evidence_side, + LogicalOperator &rewrite_root, + EvidenceDomainPreservation evidence_preservation, bool preserve_nested_evidence_side) : binder(binder), delim_join_op(delim_join_op), delim_join(delim_join_op->Cast()), dedup_cte_index(dedup_cte_index), dedup_ref_count(dedup_ref_count), rewrite_root(rewrite_root), - preserve_evidence_side(preserve_evidence_side), preserve_nested_evidence_side(preserve_nested_evidence_side) { + evidence_preservation(evidence_preservation), preserve_nested_evidence_side(preserve_nested_evidence_side) { consumer_path.emplace_back(delim_join, 1); } @@ -1601,6 +1607,44 @@ bool GeneratedDedupRefEliminator::RemoveInequalityJoinConditions(LogicalOperator return true; } +bool GeneratedDedupRefEliminator::CanRemoveNegatedMembership(LogicalOperator &input, const GeneratedDomainRef &domain, + const vector &conditions) const { + if (evidence_preservation != EvidenceDomainPreservation::SIMPLE_NEGATED_FILTER || dedup_ref_count != 1 || + domain.has_projection || !domain.filters.empty() || input.type != LogicalOperatorType::LOGICAL_GET) { + return false; + } + auto &get = input.Cast(); + auto table = get.GetTable(); + // Bare native scans are a conservative scope restriction. Broader inputs may have + // evaluation effects or benefit from keeping the domain restriction. + if (!table || !table->TryGetDuckTableEntry() || !get.children.empty() || !get.expressions.empty() || + get.table_filters.HasFilters() || get.dynamic_filters || get.has_pushed_projection || + get.extra_info.sample_options) { + return false; + } + for (auto &condition : conditions) { + if (!IsEqualityJoinCondition(condition)) { + return false; + } + } + // Direct projections are safe on newly exposed rows. Keep domain pruning for other + // operators, where it can protect evaluation semantics and reduce work. + for (idx_t index = 1; index < consumer_path.size(); index++) { + auto &consumer = consumer_path[index].first.get(); + if (consumer.type != LogicalOperatorType::LOGICAL_PROJECTION || consumer.children.size() != 1 || + consumer_path[index].second != 0) { + return false; + } + for (auto &expression : consumer.expressions) { + if (expression->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF && + expression->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + return false; + } + } + } + return true; +} + bool GeneratedDedupRefEliminator::RewriteJoin(unique_ptr &op, BindingReplacementGraph &replacements, GeneratedDomainAction action) { optional_ptr filter; @@ -1671,6 +1715,13 @@ bool GeneratedDedupRefEliminator::RewriteJoin(unique_ptr &op, B conditions.push_back(condition.Copy()); } } + if (action == GeneratedDomainAction::PRESERVE && join_op->expressions.empty() && + std::all_of(consumed.begin(), consumed.end(), [](bool value) { return value; }) && + CanRemoveNegatedMembership(*join_op->children[1 - domain_side], *domain, conditions)) { + // The outer NOT EXISTS does not need this membership test. Analyze below still checks + // key coverage, NULL handling and representation safety. + action = GeneratedDomainAction::REMOVE; + } GeneratedDomainReplacement replacement; const auto floating_keys_unobserved = CanSubstituteFloatingKeys(*domain, conditions, *op, consumer_path) && @@ -1716,7 +1767,8 @@ idx_t GeneratedDedupRefEliminator::Remove() { set marker_indexes; auto preserve_selected_domain = HasDelimiterDomainSelection(*delim_join.children[0], marker_indexes, false, delim_join.duplicate_eliminated_columns); - auto selected_evidence_side = preserve_selected_domain && preserve_evidence_side && + auto selected_evidence_side = preserve_selected_domain && + evidence_preservation != EvidenceDomainPreservation::NONE && HasEvidenceSide(delim_join.join_type) && (!ContainsSubqueryJoin(*delim_join.children[0]) || (preserve_nested_evidence_side && HasSingleEqualityJoinCondition(delim_join))); @@ -2173,8 +2225,17 @@ BindingReplacementGraph DelimJoinCTERewriter::MaterializeDelimJoinAsCTE(unique_p if (cte_deliminator_enabled) { auto cte_deliminator_timer = QueryProfiler::Get(binder.context).StartTimerInternal(CTE_DELIMINATOR_PROFILER_KEY); + auto preservation = + preserve_evidence_side ? EvidenceDomainPreservation::PRESERVE : EvidenceDomainPreservation::NONE; + auto &delim_join = plan->Cast(); + // Keep multi-key cases outside this exception; projected and nested marker uses stay protected. + if (preserve_evidence_side && delim_join.join_type == JoinType::MARK && + HasSingleEqualityJoinCondition(delim_join) && !preserve_nested_evidence_side && + preserve_marker_indexes.find(delim_join.mark_index) == preserve_marker_indexes.end()) { + preservation = EvidenceDomainPreservation::SIMPLE_NEGATED_FILTER; + } GeneratedDedupRefEliminator eliminator(binder, plan, dedup_cte_index, dedup_ref_count, rewrite_root, - preserve_evidence_side, preserve_nested_evidence_side); + preservation, preserve_nested_evidence_side); dedup_ref_count = eliminator.Remove(); auto &join = plan->Cast(); if (SingleJoinRHSIsDeduplicated(join)) { diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index 28adc96ac..fc2731431 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -288,7 +288,13 @@ bool CachingFileHandle::StripForceFullDownloadIfPresent() { } shared_ptr CachingFileHandle::EnsureCachedFileCurrent() { - annotated_lock_guard guard(file_handle_mutex); + { + const annotated_shared_lock guard(file_handle_mutex); + if (cached_file && cached_file->generation == external_file_cache.GetGeneration()) { + return cached_file; + } + } + annotated_lock_guard guard(file_handle_mutex); if (cached_file && cached_file->generation == external_file_cache.GetGeneration()) { return cached_file; } @@ -301,8 +307,8 @@ shared_ptr CachingFileHandle::EnsureCachedFileCur bool CachingFileHandle::CanUseCache() { auto current_cached_file = EnsureCachedFileCurrent(); - const annotated_lock_guard handle_guard(file_handle_mutex); - annotated_lock_guard guard(current_cached_file->meta_lock); + const annotated_shared_lock handle_guard(file_handle_mutex); + annotated_shared_lock guard(current_cached_file->meta_lock); return CanUseCache(current_cached_file->validation_info); } @@ -316,11 +322,11 @@ bool CachingFileHandle::CanUseCache(const CacheValidationInfo &cached) const { void CachingFileHandle::ReconcileCacheAfterRead(CachedFile &cached_file) { CacheValidationInfo current; { - const annotated_lock_guard guard(file_handle_mutex); + const annotated_shared_lock guard(file_handle_mutex); current = validation_info; } - const annotated_lock_guard guard(cached_file.meta_lock); + const annotated_lock_guard guard(cached_file.meta_lock); auto &cached = cached_file.validation_info; switch (GetCacheReconciliation(Validate(), cached, current)) { case CacheReconciliation::NONE: @@ -350,7 +356,7 @@ bool CachingFileHandle::Initialize() { return TryGetFileHandle() != nullptr; } { - annotated_lock_guard guard(file_handle_mutex); + annotated_lock_guard guard(file_handle_mutex); if (!TryAdoptCachedFile(cached_file) && !TryOpenFileHandle(cached_file)) { return false; } @@ -374,7 +380,13 @@ shared_ptr CachingFileHandle::GetFileHandle() { } shared_ptr CachingFileHandle::TryGetFileHandle() { - annotated_lock_guard guard(file_handle_mutex); + { + const annotated_shared_lock guard(file_handle_mutex); + if (file_handle) { + return file_handle; + } + } + annotated_lock_guard guard(file_handle_mutex); if (file_handle) { return file_handle; } @@ -386,8 +398,8 @@ bool CachingFileHandle::TryAdoptCachedFile(shared_ptr target) { if (file_handle || !external_file_cache.IsEnabled() || Validate()) { return false; } - annotated_lock_guard meta_guard(target->meta_lock); - annotated_lock_guard map_guard(target->map_lock); + annotated_shared_lock meta_guard(target->meta_lock); + annotated_shared_lock map_guard(target->map_lock); if (target->validation_info.file_size == 0 || target->blocks.empty() || target->validation_info.IsExpired()) { return false; } @@ -410,7 +422,7 @@ shared_ptr CachingFileHandle::TryOpenFileHandle(shared_ptr meta_guard(target->meta_lock); + annotated_lock_guard meta_guard(target->meta_lock); const bool first_access = (target->validation_info.file_size == 0); const bool refresh_expired_cache = !Validate() && target->validation_info.IsExpired(); if (first_access || Validate() || refresh_expired_cache) { @@ -509,7 +521,7 @@ optional CachingFileHandle::ReadInternal(const idx_t nr_b if (!external_file_cache.IsEnabled() || !external_file_cache.ShouldCacheFile(path.path)) { return nullopt; } - annotated_unique_lock handle_guard(file_handle_mutex, std::defer_lock); + annotated_shared_lock handle_guard(file_handle_mutex, std::defer_lock); if (!handle_guard.try_lock() || !cached_file || cached_file->generation != external_file_cache.GetGeneration()) { return nullopt; @@ -517,7 +529,7 @@ optional CachingFileHandle::ReadInternal(const idx_t nr_b current_cached_file = cached_file; // Validate policy and acquire block references in one metadata snapshot. An ordinary read may // tighten the deadline or drop these blocks after returning data; a resident probe must defer to it. - annotated_unique_lock meta_guard(current_cached_file->meta_lock, std::defer_lock); + annotated_shared_lock meta_guard(current_cached_file->meta_lock, std::defer_lock); if (!meta_guard.try_lock() || !CanUseCache(current_cached_file->validation_info) || GetCacheReconciliation(Validate(), current_cached_file->validation_info, validation_info) != CacheReconciliation::NONE) { @@ -688,33 +700,33 @@ string CachingFileHandle::GetPath() const { idx_t CachingFileHandle::GetFileSize() { if (!Validate()) { auto current_cached_file = EnsureCachedFileCurrent(); - annotated_lock_guard guard(current_cached_file->meta_lock); + annotated_shared_lock guard(current_cached_file->meta_lock); return current_cached_file->validation_info.file_size; } auto file_handle = GetFileHandle(); - annotated_lock_guard guard(file_handle_mutex); + annotated_shared_lock guard(file_handle_mutex); return validation_info.file_size; } timestamp_t CachingFileHandle::GetLastModifiedTime() { if (!Validate()) { auto current_cached_file = EnsureCachedFileCurrent(); - annotated_lock_guard guard(current_cached_file->meta_lock); + annotated_shared_lock guard(current_cached_file->meta_lock); return current_cached_file->validation_info.last_modified; } auto file_handle = GetFileHandle(); - annotated_lock_guard guard(file_handle_mutex); + annotated_shared_lock guard(file_handle_mutex); return validation_info.last_modified; } string CachingFileHandle::GetVersionTag() { if (!Validate()) { auto current_cached_file = EnsureCachedFileCurrent(); - annotated_lock_guard guard(current_cached_file->meta_lock); + annotated_shared_lock guard(current_cached_file->meta_lock); return current_cached_file->validation_info.version_tag; } auto file_handle = GetFileHandle(); - annotated_lock_guard guard(file_handle_mutex); + annotated_shared_lock guard(file_handle_mutex); return validation_info.version_tag; } @@ -738,7 +750,7 @@ bool CachingFileHandle::Validate() const { bool CachingFileHandle::CanSeek() { if (!Validate()) { auto current_cached_file = EnsureCachedFileCurrent(); - annotated_lock_guard guard(current_cached_file->meta_lock); + annotated_shared_lock guard(current_cached_file->meta_lock); return current_cached_file->can_seek; } return GetFileHandle()->CanSeek(); @@ -751,7 +763,7 @@ bool CachingFileHandle::IsRemoteFile() const { bool CachingFileHandle::OnDiskFile() { if (!Validate()) { auto current_cached_file = EnsureCachedFileCurrent(); - annotated_lock_guard guard(current_cached_file->meta_lock); + annotated_shared_lock guard(current_cached_file->meta_lock); return current_cached_file->on_disk_file; } return GetFileHandle()->OnDiskFile(); @@ -835,7 +847,7 @@ void CachingFileHandle::ReadAndRecord(Context &context, data_ptr_t buffer, idx_t handle->Read(context, buffer, nr_bytes, location); auto cache_valid_until = handle->file_system.GetCacheValidUntil(*handle); if (cache_valid_until) { - const annotated_lock_guard guard(file_handle_mutex); + const annotated_lock_guard guard(file_handle_mutex); if (file_handle == handle) { TightenCacheDeadline(validation_info.cache_valid_until, cache_valid_until); } @@ -844,7 +856,7 @@ void CachingFileHandle::ReadAndRecord(Context &context, data_ptr_t buffer, idx_t } bool CachingFileHandle::IsCacheReuseProhibited() { - const annotated_lock_guard guard(file_handle_mutex); + const annotated_shared_lock guard(file_handle_mutex); return validation_info.IsCacheReuseProhibited(); } @@ -861,8 +873,13 @@ idx_t CachingFileHandle::SeekPosition() { void CachingFileHandle::Seek(idx_t location) { position = location; - if (file_handle != nullptr) { - file_handle->Seek(location); + shared_ptr handle; + { + const annotated_shared_lock guard(file_handle_mutex); + handle = file_handle; + } + if (handle) { + handle->Seek(location); } } diff --git a/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp b/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp index e1baf4c9c..ded7f382a 100644 --- a/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp +++ b/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp @@ -132,7 +132,7 @@ static idx_t CountSmallAvailableBlocksLocked(const map map_guard(cached_file.map_lock); + const annotated_shared_lock map_guard(cached_file.map_lock); return CountSmallAvailableBlocksLocked(cached_file.blocks, location, location + nr_bytes, max_block_size); } @@ -158,7 +158,7 @@ static bool IsRangeAvailableLocked(const map> &blo } bool ExternalFileCache::IsRangeAvailable(CachedFile &cached_file, idx_t location, idx_t nr_bytes) { - const annotated_lock_guard map_guard(cached_file.map_lock); + const annotated_shared_lock map_guard(cached_file.map_lock); return IsRangeAvailableLocked(cached_file.blocks, location, location + nr_bytes); } @@ -183,14 +183,33 @@ vector> ExternalFileCache::AcquireBlocks(CachedFile &cach D_ASSERT(max_block_size > 0); const idx_t end = location + nr_bytes; - annotated_unique_lock map_guard(cached_file.map_lock, std::defer_lock); if (lookup == BlockLookup::EXISTING_ONLY) { + const auto &file = cached_file; + annotated_shared_lock map_guard(file.map_lock, std::defer_lock); if (!map_guard.try_lock()) { return {}; } - } else { - map_guard.lock(); + auto it = file.blocks.upper_bound(location); + if (it != file.blocks.begin()) { + --it; + } + vector> result; + idx_t pos = location; + for (; it != file.blocks.end() && pos < end; ++it) { + const auto block_end = it->first + it->second->size; + if (block_end <= pos) { + continue; + } + if (it->first > pos) { + return {}; + } + result.push_back(it->second); + pos = block_end; + } + return pos >= end ? std::move(result) : vector> {}; } + + const annotated_lock_guard map_guard(cached_file.map_lock); auto &blocks = cached_file.blocks; // smaller cached blocks between two gaps are re-fetched with them when that saves a request; within the ranges a // read asks for (a column chunk read whole after point lookups left pages of it in the cache) that holds for @@ -214,7 +233,7 @@ vector> ExternalFileCache::AcquireBlocks(CachedFile &cach idx_t pos = location; while (pos < end) { if (it != blocks.end() && it->first <= pos) { - if (lookup == BlockLookup::EXISTING_ONLY || !IsDroppedBlock(*it->second) || it->second.use_count() > 1) { + if (!IsDroppedBlock(*it->second) || it->second.use_count() > 1) { result.push_back(it->second); pos = it->first + it->second->size; ++it; @@ -223,9 +242,6 @@ vector> ExternalFileCache::AcquireBlocks(CachedFile &cach // re-fetch a dropped block only as far as this read needs it it = blocks.erase(it); } - if (lookup == BlockLookup::EXISTING_ONLY) { - return {}; - } // create blocks for the missing bytes up to the next cached block idx_t gap_end = it == blocks.end() ? end : MinValue(end, it->first); while (it != blocks.end() && it->first < end && absorbable(it->first, *it->second) && @@ -253,21 +269,19 @@ vector> ExternalFileCache::AcquireBlocks(CachedFile &cach pos += size; } } - if (lookup == BlockLookup::CREATE_MISSING) { - cached_file.UpdateBlockReservation(); - } + cached_file.UpdateBlockReservation(); return result; } void ExternalFileCache::DropBlocks(CachedFile &cached_file) { - const annotated_lock_guard map_guard(cached_file.map_lock); + const annotated_lock_guard map_guard(cached_file.map_lock); cached_file.blocks.clear(); cached_file.content_generation++; cached_file.UpdateBlockReservation(); } idx_t ExternalFileCache::GetContentGeneration(CachedFile &cached_file) { - const annotated_lock_guard map_guard(cached_file.map_lock); + const annotated_shared_lock map_guard(cached_file.map_lock); return cached_file.content_generation; } @@ -389,7 +403,7 @@ vector ExternalFileCache::GetCachedFileInformation() cons continue; } auto file = entry->GetCachedFile(); - const annotated_lock_guard map_guard(file->map_lock); + const annotated_shared_lock map_guard(file->map_lock); for (const auto &block_entry : file->blocks) { const auto &block = *block_entry.second; diff --git a/src/duckdb/ub_src_optimizer.cpp b/src/duckdb/ub_src_optimizer.cpp index 0d84b16bf..e469be75b 100644 --- a/src/duckdb/ub_src_optimizer.cpp +++ b/src/duckdb/ub_src_optimizer.cpp @@ -30,6 +30,8 @@ #include "src/optimizer/cse_optimizer.cpp" +#include "src/optimizer/cte_definition_scope.cpp" + #include "src/optimizer/cte_filter_helpers.cpp" #include "src/optimizer/cte_inlining.cpp" @@ -44,8 +46,6 @@ #include "src/optimizer/disjunctive_join_rewriter.cpp" -#include "src/optimizer/distinctness.cpp" - #include "src/optimizer/empty_result_pullup.cpp" #include "src/optimizer/expression_heuristics.cpp" @@ -104,6 +104,10 @@ #include "src/optimizer/regex_range_filter.cpp" +#include "src/optimizer/relation_properties.cpp" + +#include "src/optimizer/relation_properties_aliases.cpp" + #include "src/optimizer/remote_pushdown_optimizer.cpp" #include "src/optimizer/remove_duplicate_groups.cpp" diff --git a/src/duckdb/ub_src_planner_subquery.cpp b/src/duckdb/ub_src_planner_subquery.cpp index 14f5739f9..52425849f 100644 --- a/src/duckdb/ub_src_planner_subquery.cpp +++ b/src/duckdb/ub_src_planner_subquery.cpp @@ -1,3 +1,5 @@ +#include "src/planner/subquery/column_binding_layout.cpp" + #include "src/planner/subquery/delim_join_cte_rewriter.cpp" #include "src/planner/subquery/flatten_dependent_join.cpp"