diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index f664dfafb..6a049df07 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-alpha57331"; + descriptor->api_version = "v2.1.0-alpha57387"; 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-alpha57331"; + descriptor->api_version = "v2.1.0-alpha57387"; 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-alpha57331"; + descriptor->api_version = "v2.1.0-alpha57387"; 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-alpha57331"; + descriptor->api_version = "v2.1.0-alpha57387"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/common/sort/partitioned_sort.cpp b/src/duckdb/src/common/sort/partitioned_sort.cpp index 711bc7e2b..8a564df78 100644 --- a/src/duckdb/src/common/sort/partitioned_sort.cpp +++ b/src/duckdb/src/common/sort/partitioned_sort.cpp @@ -82,14 +82,14 @@ class PartitionedSortLocalSinkState : public LocalSinkState { //===--------------------------------------------------------------------===// PartitionedSort::PartitionedSort(ClientContext &client, const vector &order_bys, const Types &payload_types, const OperatorPartitionInfo &partition_info, - bool require_payload) - : SortStrategy(payload_types), partition_info(partition_info) { + bool require_payload, optional_idx partition_limit) + : SortStrategy(payload_types, partition_limit), partition_info(partition_info) { // Pipeline does the partitioning for us, so leave them out vector> unpartitioned; vector> unpartitioned_stats; OperatorPartitionInfo unpartitioned_info; child_strategy = SortStrategy::Factory(client, unpartitioned, order_bys, payload_types, unpartitioned_stats, - unpartitioned_info, 0, require_payload); + unpartitioned_info, 0, require_payload, partition_limit); this->payload_types = child_strategy->payload_types; scan_ids = child_strategy->scan_ids; diff --git a/src/duckdb/src/common/sort/sort_strategy.cpp b/src/duckdb/src/common/sort/sort_strategy.cpp index 0366bab2f..198a3a347 100644 --- a/src/duckdb/src/common/sort/sort_strategy.cpp +++ b/src/duckdb/src/common/sort/sort_strategy.cpp @@ -40,7 +40,8 @@ unique_ptr SortStrategy::Factory(ClientContext &client, const OperatorPartitionInfo &partition_info, idx_t estimated_cardinality, bool require_payload, optional_idx partition_limit) { if (partition_info.RequiresPartitionColumns()) { - return make_uniq(client, order_bys, payload_types, partition_info, require_payload); + return make_uniq(client, order_bys, payload_types, partition_info, require_payload, + partition_limit); } else if (!partition_bys.empty()) { return make_uniq(client, partition_bys, order_bys, payload_types, partitions_stats, estimated_cardinality, require_payload); diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index e12c966a6..d67a25499 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-alpha57331" +#define DUCKDB_PATCH_VERSION "0-alpha57387" #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-alpha57331" +#define DUCKDB_VERSION "v2.1.0-alpha57387" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "94a1663a4d" +#define DUCKDB_SOURCE_ID "eb318174fa" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/window/window_segment_tree.cpp b/src/duckdb/src/function/window/window_segment_tree.cpp index e6b4eb98a..869dc2b92 100644 --- a/src/duckdb/src/function/window/window_segment_tree.cpp +++ b/src/duckdb/src/function/window/window_segment_tree.cpp @@ -73,6 +73,7 @@ class WindowSegmentTreePart { using RightEntry = std::pair; enum FramePart : uint8_t { FULL = 0, LEFT = 1, RIGHT = 2 }; + enum class LeafPart { LEFT, RIGHT }; WindowSegmentTreePart(ArenaAllocator &allocator, const AggregateObject &aggr, unique_ptr cursor, const ValidityArray &filter_mask); @@ -103,7 +104,7 @@ class WindowSegmentTreePart { void EvaluateUpperLevels(const WindowSegmentTreeGlobalState &tree, const idx_t *begins, const idx_t *ends, const idx_t *bounds, idx_t count, idx_t row_idx, FramePart frame_part); void EvaluateLeaves(const WindowSegmentTreeGlobalState &tree, const idx_t *begins, const idx_t *ends, - const idx_t *bounds, idx_t count, idx_t row_idx, FramePart frame_part, FramePart leaf_part); + const idx_t *bounds, idx_t count, idx_t row_idx, FramePart frame_part, LeafPart leaf_part); static inline const idx_t *FrameBegins(const idx_t *begins, const idx_t *ends, const idx_t *bounds, FramePart frame_part) { @@ -541,17 +542,15 @@ void WindowSegmentTreePart::Evaluate(const WindowSegmentTreeGlobalState &tree, c Initialize(count); if (order_insensitive) { - // First pass: aggregate the segment tree nodes with sharing + // Shared states must contain only tree nodes, before either set of leaves is added. EvaluateUpperLevels(tree, begins, ends, bounds, count, row_idx, frame_part); - - // Second pass: aggregate the ragged leaves - EvaluateLeaves(tree, begins, ends, bounds, count, row_idx, frame_part, FramePart::FULL); - } else { - // Evaluate leaves in order - EvaluateLeaves(tree, begins, ends, bounds, count, row_idx, frame_part, FramePart::LEFT); + } + // Process each side in a separate pass so the cursor does not seek between both frame ends for every row. + EvaluateLeaves(tree, begins, ends, bounds, count, row_idx, frame_part, LeafPart::LEFT); + if (!order_insensitive) { EvaluateUpperLevels(tree, begins, ends, bounds, count, row_idx, frame_part); - EvaluateLeaves(tree, begins, ends, bounds, count, row_idx, frame_part, FramePart::RIGHT); } + EvaluateLeaves(tree, begins, ends, bounds, count, row_idx, frame_part, LeafPart::RIGHT); } void WindowSegmentTreePart::Initialize(idx_t count) { @@ -663,19 +662,17 @@ void WindowSegmentTreePart::EvaluateUpperLevels(const WindowSegmentTreeGlobalSta void WindowSegmentTreePart::EvaluateLeaves(const WindowSegmentTreeGlobalState &tree, const idx_t *begins, const idx_t *ends, const idx_t *bounds, idx_t count, idx_t row_idx, - FramePart frame_part, FramePart leaf_part) { + FramePart frame_part, LeafPart leaf_part) { auto fdata = FlatVector::GetDataMutable(statef); - // For order-sensitive aggregates, we have to process the ragged leaves in two pieces. - // The left side have to be added before the main tree followed by the ragged right sides. - // The current row is the leftmost value of the right hand side. - const bool compute_left = leaf_part != FramePart::RIGHT; - const bool compute_right = leaf_part != FramePart::LEFT; + // Process the ragged leaves one side at a time. + // Order-sensitive aggregates add left leaves before the tree and right leaves after it. + const bool compute_left = leaf_part == LeafPart::LEFT; + const bool compute_right = leaf_part == LeafPart::RIGHT; const auto exclude_mode = tree.tree.exclude_mode; const bool begin_on_curr_row = frame_part == FramePart::RIGHT && exclude_mode == WindowExcludeMode::CURRENT_ROW; const bool end_on_curr_row = frame_part == FramePart::LEFT && exclude_mode == WindowExcludeMode::CURRENT_ROW; - // with EXCLUDE TIES, in addition to the frame part right of the peer group's end, we also need to consider the - // current row + // EXCLUDE TIES adds the current row before the right frame part's other leaves. const bool add_curr_row = compute_left && frame_part == FramePart::RIGHT && exclude_mode == WindowExcludeMode::TIES; // We need the full range of the frame to clamp diff --git a/src/duckdb/src/include/duckdb/common/sorting/partitioned_sort.hpp b/src/duckdb/src/include/duckdb/common/sorting/partitioned_sort.hpp index e645b31e7..80cf8274d 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/partitioned_sort.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/partitioned_sort.hpp @@ -15,7 +15,8 @@ namespace duckdb { class PartitionedSort : public SortStrategy { public: PartitionedSort(ClientContext &client, const vector &order_bys, const Types &payload_types, - const OperatorPartitionInfo &partition_info, bool require_payload = false); + const OperatorPartitionInfo &partition_info, bool require_payload = false, + optional_idx partition_limit = optional_idx()); public: //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/parser/parser_options.hpp b/src/duckdb/src/include/duckdb/parser/parser_options.hpp index 6b106ea9d..febc32159 100644 --- a/src/duckdb/src/include/duckdb/parser/parser_options.hpp +++ b/src/duckdb/src/include/duckdb/parser/parser_options.hpp @@ -39,6 +39,9 @@ struct ParserOptions { optional_ptr extensions; AllowParserOverride parser_override_setting = AllowParserOverride::DEFAULT_OVERRIDE; shared_ptr compiled_grammar; + //! Only check that the statements match the grammar: each yields a PassthroughStatement holding its text, and + //! nothing is transformed. For a client that sends the text on to an engine that knows the grammar's rules. + bool match_only = false; //! The services the statement is parsed for (not set when parsing without a context) optional_ptr context; }; diff --git a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp index 49090ad84..169541687 100644 --- a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp @@ -325,6 +325,8 @@ class CollectionScanState { //! Optional state for custom row group ordering unique_ptr reorderer; + //! Keeps the transaction-local row groups from being replaced while they are scanned + unique_ptr local_row_groups_lock; public: void Initialize(const QueryContext &context_p, const vector &types); diff --git a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp index efb065cb7..62b702b7c 100644 --- a/src/duckdb/src/include/duckdb/transaction/local_storage.hpp +++ b/src/duckdb/src/include/duckdb/transaction/local_storage.hpp @@ -78,10 +78,12 @@ class LocalTableStorage : public enable_shared_from_this { OptimisticDataWriter optimistic_writer; //! Whether or not the storage was dropped - bool is_dropped = false; + atomic is_dropped {false}; //! Serializes the appends and merges into the primary collection StorageLock append_lock; + //! Shared by the users of the primary collection, exclusive while its row groups are replaced by a flush + StorageLock flush_lock; public: //! Initialize a scan; the context of the scanning query is used for pushed down casts and zonemap checks diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp index c11174849..97a251697 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp @@ -12,6 +12,8 @@ #include "duckdb/parallel/pipeline.hpp" #include "duckdb/parser/parsed_data/create_table_function_info.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/operator/logical_get.hpp" diff --git a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp index 03ccbb216..0f6b65bc0 100644 --- a/src/duckdb/src/optimizer/apply_functional_dependencies.cpp +++ b/src/duckdb/src/optimizer/apply_functional_dependencies.cpp @@ -133,6 +133,13 @@ void ApplyFunctionalDependencies::VisitWindowExpression(BoundWindowExpression &w // so there is only one peer group, which is the same as having no ORDER BY clause. auto &partition_bys = wexpr.Partitions(); auto &order_bys = wexpr.OrderByMutable(); + // A RANGE frame with an offset is measured on the ORDER BY value, so it needs the key even then. + const auto range_offset = [](WindowBoundary boundary) { + return boundary == WindowBoundary::EXPR_PRECEDING_RANGE || boundary == WindowBoundary::EXPR_FOLLOWING_RANGE; + }; + if (range_offset(wexpr.WindowStart()) || range_offset(wexpr.WindowEnd())) { + return; + } if (!partition_bys.empty() && order_bys.size() == 1) { vector> refs; for (auto &arg : partition_bys) { diff --git a/src/duckdb/src/optimizer/window_fusion.cpp b/src/duckdb/src/optimizer/window_fusion.cpp index b225bf991..fcef82811 100644 --- a/src/duckdb/src/optimizer/window_fusion.cpp +++ b/src/duckdb/src/optimizer/window_fusion.cpp @@ -3,17 +3,74 @@ #include "duckdb/optimizer/topn_window_elimination.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" -#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_window.hpp" #include "duckdb/optimizer/remove_unused_columns.hpp" -#include "duckdb/execution/operator/aggregate/physical_streaming_window.hpp" +#include "duckdb/optimizer/apply_functional_dependencies.hpp" namespace duckdb { +namespace { + +using bindings_t = vector; + +ColumnBinding GetColumnBinding(const Expression &expr, const bindings_t &bindings) { + switch (expr.GetExpressionType()) { + case ExpressionType::BOUND_COLUMN_REF: + return expr.Cast().Binding(); + case ExpressionType::BOUND_REF: + return bindings.at(expr.Cast().Index()); + default: + break; + } + + // Return invalid binding, which will not be in the UCCs + return ColumnBinding(); +} + +bool CanRank(const BoundWindowExpression &wexpr, LogicalOperator &op) { + // Row Number is always rankable + switch (wexpr.GetExpressionType()) { + case ExpressionType::WINDOW_ROW_NUMBER: + return true; + case ExpressionType::WINDOW_RANK: + case ExpressionType::WINDOW_RANK_DENSE: + break; + default: + return false; + } + + // Natural orders can always rank + auto &order_bys = wexpr.OrderBy(); + if (order_bys.empty()) { + return true; + } + + // For the other rankers to apply, we must have a UCC in play + const auto uccs = ApplyFunctionalDependencies::GetUniqueColumnCombinations(op); + const auto bindings = op.GetColumnBindings(); + for (const auto &ucc : uccs) { + auto fds = ucc; + for (const auto &order : order_bys) { + fds.erase(GetColumnBinding(*order.expression, bindings)); + } + if (fds.empty()) { + return true; + } + } + + return false; +} + +}; // namespace + WindowFusion::WindowFusion(ClientContext &client, optional_ptr>> stats) : client(client), stats(stats) { D_ASSERT(stats); @@ -31,17 +88,23 @@ optional_idx WindowFusion::CanOptimize(LogicalOperator &op) { } const auto comparison = filter.expressions[0]->GetExpressionType(); + idx_t left_idx = 0; + idx_t right_idx = 1; switch (comparison) { case ExpressionType::COMPARE_LESSTHANOREQUALTO: case ExpressionType::COMPARE_LESSTHAN: case ExpressionType::COMPARE_EQUAL: break; + case ExpressionType::COMPARE_BETWEEN: + right_idx = 2; + break; default: return cant_optimize; } auto &filter_comparison = filter.expressions[0]->Cast(); - auto &right = BoundComparisonExpression::Right(filter_comparison); + auto &right = *filter_comparison.GetChildren()[right_idx]; + if (right.GetExpressionType() != ExpressionType::VALUE_CONSTANT) { return cant_optimize; } @@ -57,6 +120,7 @@ optional_idx WindowFusion::CanOptimize(LogicalOperator &op) { optional_idx can_optimize(0); switch (comparison) { case ExpressionType::COMPARE_LESSTHANOREQUALTO: + case ExpressionType::COMPARE_BETWEEN: if (bigint_value < 1) { break; } @@ -82,7 +146,7 @@ optional_idx WindowFusion::CanOptimize(LogicalOperator &op) { return cant_optimize; } - auto &left = BoundComparisonExpression::LeftMutable(filter_comparison); + auto &left = filter_comparison.GetChildrenMutable()[left_idx]; if (left->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { return cant_optimize; } @@ -121,9 +185,10 @@ optional_idx WindowFusion::CanOptimize(LogicalOperator &op) { return cant_optimize; } auto &window_expr = window.expressions[0]->Cast(); - if (window_expr.GetExpressionType() != ExpressionType::WINDOW_ROW_NUMBER) { + if (!CanRank(window_expr, *window.children[0])) { return cant_optimize; } + if (window.expressions.size() != 1) { for (idx_t i = 1; i < window.expressions.size(); ++i) { if (!window.expressions[i]->Equals(window_expr)) { @@ -166,12 +231,6 @@ unique_ptr WindowFusion::OptimizeInternal(unique_ptr(); - auto &wexpr = window.expressions[0]->Cast(); - - // Restrict to implemented cases - if (!wexpr.Partitions().empty()) { - return op; - } // Add the limit to the child Window window.partition_limit = partition_limit; diff --git a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp index 9415c9cda..11315df7d 100644 --- a/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp +++ b/src/duckdb/src/parser/peg/transformer/peg_transformer_factory.cpp @@ -7,6 +7,7 @@ #include "duckdb/parser/peg/matcher.hpp" #include "duckdb/common/to_string.hpp" #include "duckdb/parser/sql_statement.hpp" +#include "duckdb/parser/statement/passthrough_statement.hpp" #include "duckdb/parser/token_iterator.hpp" #include "duckdb/parser/tableref/showref.hpp" #include "duckdb/common/enums/date_part_specifier.hpp" @@ -102,6 +103,14 @@ unique_ptr PEGTransformerFactory::TransformTopLevelStatement(Token } } + if (options.match_only) { + auto start = stmt_opt.GetResult().GetOffset().GetIndex(); + idx_t end_index = terminator_offset.IsValid() ? terminator_offset.GetIndex() : token_iterator.EndOffset(); + auto statement = make_uniq(); + statement->stmt_location = QueryLocation(start, end_index - start); + return std::move(statement); + } + ArenaAllocator transformer_allocator(allocator, PARSER_ARENA_INITIAL_CAPACITY); PEGTransformer transformer(transformer_allocator, token_iterator, options, grammar); diff --git a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp index 757fece59..acd5af50d 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp @@ -276,6 +276,10 @@ unique_ptr Binder::BindConstraint(const Constraint &constraint, void Binder::BindGeneratedColumns(BoundCreateTableInfo &info) { auto &base = info.base->Cast(); + if (base.columns.LogicalColumnCount() == base.columns.PhysicalColumnCount()) { + // no generated columns + return; + } vector names; vector types; diff --git a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp index d6d1bc0b8..c04282de1 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_basetableref.cpp @@ -275,15 +275,19 @@ BoundStatement Binder::Bind(BaseTableRef &ref) { vector table_names; vector table_categories; - vector return_types; - vector return_names; - for (auto &col : table.GetColumns().Logical()) { + auto &columns = table.GetColumns(); + table_types.reserve(columns.LogicalColumnCount()); + table_names.reserve(columns.LogicalColumnCount()); + for (auto &col : columns.Logical()) { table_types.push_back(col.Type()); table_names.emplace_back(col.Name()); - return_types.push_back(col.Type()); - return_names.emplace_back(col.Name()); } - table_names = BindContext::AliasColumnNames(ref.Table(), table_names, ref.column_name_alias); + auto return_types = table_types; + auto return_names = table_names; + // the ColumnList of a table already deduplicates its column names + if (!ref.column_name_alias.empty()) { + table_names = BindContext::AliasColumnNames(ref.Table(), table_names, ref.column_name_alias); + } virtual_column_map_t virtual_columns; if (scan_function.get_virtual_columns) { diff --git a/src/duckdb/src/planner/binder/tableref/bind_showref.cpp b/src/duckdb/src/planner/binder/tableref/bind_showref.cpp index 60bffb812..154b3ccab 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_showref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_showref.cpp @@ -120,11 +120,6 @@ BaseTableColumnInfo FindBaseTableColumn(LogicalOperator &op, ColumnBinding bindi return result; } -BaseTableColumnInfo FindBaseTableColumn(LogicalOperator &op, idx_t column_index) { - auto bindings = op.GetColumnBindings(); - return FindBaseTableColumn(op, bindings[column_index]); -} - BoundStatement Binder::BindDescribeQuery(ShowRef &ref) { // bind the child plan of the DESCRIBE statement auto child_binder = Binder::CreateBinder(context, this); @@ -140,9 +135,10 @@ BoundStatement Binder::BindDescribeQuery(ShowRef &ref) { auto collection = make_uniq(context, return_types); ColumnDataAppendState append_state; collection->InitializeAppend(append_state); + auto bindings = plan.plan->GetColumnBindings(); for (idx_t column_idx = 0; column_idx < plan.types.size(); column_idx++) { // check if we can trace the column to a base table so that we can figure out constraint information - auto result = FindBaseTableColumn(*plan.plan, column_idx); + auto result = FindBaseTableColumn(*plan.plan, bindings[column_idx]); idx_t row_index = output.size(); auto &alias = plan.names[column_idx]; if (result.table) { diff --git a/src/duckdb/src/storage/local_storage.cpp b/src/duckdb/src/storage/local_storage.cpp index 95e5599aa..821ada7f4 100644 --- a/src/duckdb/src/storage/local_storage.cpp +++ b/src/duckdb/src/storage/local_storage.cpp @@ -126,6 +126,11 @@ idx_t LocalTableStorage::EstimatedSize() const { } void LocalTableStorage::WriteNewRowGroup(Context &context, idx_t flushed_row_group_idx) { + // a flush replaces row groups: skip it while they are in use, the row groups are written at the latest on commit + auto flush_key = flush_lock.TryGetExclusiveLock(); + if (!flush_key) { + return; + } if (deleted_rows != 0) { // we have deletes - we cannot merge row groups return; @@ -412,6 +417,7 @@ void LocalStorage::InitializeScan(const QueryContext &context, DataTable &table, if (storage == nullptr || storage->GetCollection().GetTotalRows() == 0) { return; } + state.local_row_groups_lock = storage->flush_lock.GetSharedLock(); storage->InitializeScan(context, state, table_filters); } @@ -445,6 +451,9 @@ optional_idx LocalStorage::NextParallelScan(ClientContext &context, DataTable &t if (!storage) { return optional_idx(); } + if (!scan_state.local_row_groups_lock) { + scan_state.local_row_groups_lock = storage->flush_lock.GetSharedLock(); + } return storage->GetCollection().NextParallelScan(context, state, scan_state, initialize_columns); } @@ -485,9 +494,13 @@ void LocalTableStorage::AppendToDeleteIndexes(Vector &row_ids, DataChunk &delete if (committed_count == 0) { return; } + if (committed_count == delete_chunk.size()) { + delete_indexes.AppendToDeleteIndexes(delete_chunk, row_ids); + return; + } DataChunk committed_chunk; - committed_chunk.Initialize(Allocator::DefaultAllocator(), delete_chunk.GetTypes()); + committed_chunk.InitializeEmpty(delete_chunk.GetTypes()); committed_chunk.Slice(delete_chunk, committed_sel, committed_count); Vector committed_row_ids(row_ids, committed_sel, committed_count); @@ -581,6 +594,7 @@ idx_t LocalStorage::Delete(Context &context, DataTable &table, DuckTableEntry &t auto storage = table_manager.GetStorage(table); D_ASSERT(storage); + auto flush_key = storage->flush_lock.GetSharedLock(); auto ids = FlatVector::GetDataMutable(row_ids); if (storage->append_indexes.Empty()) { idx_t delete_count = storage->GetCollection().Delete(TransactionData::Unversioned(), table_entry, ids, count); @@ -620,6 +634,7 @@ void LocalStorage::Update(DataTable &table, DuckTableEntry &table_entry, Vector auto storage = table_manager.GetStorage(table); D_ASSERT(storage); + auto flush_key = storage->flush_lock.GetSharedLock(); auto ids = FlatVector::GetDataMutable(row_ids); storage->GetCollection().Update(TransactionData::Unversioned(), table_entry, ids, column_ids, updates); } @@ -756,6 +771,7 @@ vector LocalStorage::GetPartitionStats(DataTable &table, Tr if (!storage) { return vector(); } + auto flush_key = storage->flush_lock.GetSharedLock(); return storage->GetCollection().GetPartitionStats(transaction); } @@ -818,6 +834,7 @@ void LocalStorage::FetchChunk(DataTable &table, const Vector &row_ids, idx_t cou if (!storage) { throw InternalException("LocalStorage::FetchChunk - local storage not found"); } + auto flush_key = storage->flush_lock.GetSharedLock(); storage->GetCollection().Fetch(transaction, chunk, col_ids, row_ids, count, fetch_state); } @@ -826,6 +843,7 @@ bool LocalStorage::CanFetch(DataTable &table, const row_t row_id) { if (!storage) { throw InternalException("LocalStorage::CanFetch - local storage not found"); } + auto flush_key = storage->flush_lock.GetSharedLock(); return storage->GetCollection().CanFetch(transaction, row_id); } @@ -843,6 +861,7 @@ void LocalStorage::VerifyNewConstraint(Context &context, DataTable &parent, cons if (!storage) { return; } + auto flush_key = storage->flush_lock.GetSharedLock(); storage->GetCollection().VerifyNewConstraint(context, transaction, parent, constraint); }