Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions src/duckdb/extension/json/json_functions/json_normalize.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<yyjson_mut_val *, yyjson_mut_val *> &a,
const std::pair<yyjson_mut_val *, yyjson_mut_val *> &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<yyjson_mut_val *, yyjson_mut_val *> &a,
const std::pair<yyjson_mut_val *, yyjson_mut_val *> &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) {
Expand Down Expand Up @@ -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());

Expand Down
17 changes: 9 additions & 8 deletions src/duckdb/extension/parquet/include/thrift_tools.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -141,6 +142,7 @@ struct ReadAheadBuffer {
std::set<ReadHead *, ReadHeadComparator> merge_set;

CachingFileHandle &file_handle;
const idx_t file_size;

idx_t total_size = 0;

Expand Down Expand Up @@ -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));
}
}

Expand Down Expand Up @@ -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) {
}

Expand All @@ -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;
Expand Down Expand Up @@ -340,15 +342,14 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra
}

idx_t GetSize() const {
return size;
return ra_buffer.file_size;
}

private:
Context &context;

CachingFileHandle &file_handle;
idx_t location;
idx_t size;

// Multi-buffer prefetch
ReadAheadBuffer ra_buffer;
Expand Down
8 changes: 4 additions & 4 deletions src/duckdb/generated_extension_loader_package_build.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/duckdb/src/common/enum_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 3 additions & 3 deletions src/duckdb/src/function/table/version/pragma_version.cpp
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,24 @@

#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 {

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<column_binding_set_t> 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;
Expand All @@ -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<column_binding_set_t> result;
};
Expand Down
23 changes: 23 additions & 0 deletions src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <functional>

Expand Down Expand Up @@ -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<const CTEDefinitionScope> &active_scope,
optional_ptr<const CTEDefinitionScope> outer);
~ScopedCTEDefinitions();
ScopedCTEDefinitions(const ScopedCTEDefinitions &) = delete;
ScopedCTEDefinitions &operator=(const ScopedCTEDefinitions &) = delete;

public:
optional_ptr<LogicalOperator> Push(LogicalOperator &op);
void Pop(LogicalOperator &op, optional_ptr<LogicalOperator> previous);

private:
optional_ptr<const CTEDefinitionScope> &active_scope;
optional_ptr<const CTEDefinitionScope> previous_scope;
const optional_ptr<const CTEDefinitionScope> outer;
CTEDefinitionScope scope;
unordered_map<TableIndex, reference<LogicalOperator>> definitions;
};

} // namespace duckdb
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ class DomainAnalysis {
const vector<ColumnBinding> empty_bindings;

//! Shared estimators and lazy discovery caches use the same invalidation boundary.
Distinctness distinctness;
RelationProperties properties;
RelationStatsExtractor statistics;
unique_ptr<JoinFilterTargetCache> filter_targets;
unordered_map<TableIndex, unique_ptr<DomainScanSourceFinder>> scan_sources;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<LogicalOperator> Optimize(unique_ptr<LogicalOperator> op);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ namespace duckdb {
class JoinOrderOptimizer;
class FilterInfo;
class RelationStatsExtractor;
class Distinctness;
class RelationProperties;

struct JoinOrderExtraction {
vector<unique_ptr<FilterInfo>> filters;
Expand Down Expand Up @@ -105,7 +105,7 @@ class RelationManager {
vector<reference<LogicalOperator>> &filter_operators,
vector<PendingRelation> &pending_relations);
bool RegisterRelation(LogicalOperator &op, optional_ptr<LogicalOperator> parent, RelationStats stats,
optional_ptr<Distinctness> published_distinctness = nullptr);
optional_ptr<RelationProperties> published_properties = nullptr);
optional_ptr<JoinRelationSet> GetJoinRelations(column_binding_set_t &column_bindings,
JoinRelationSetManager &set_manager);
void GetColumnBindingsFromExpression(const Expression &expression, column_binding_set_t &column_bindings);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/optimizer/distinctness.hpp
// duckdb/optimizer/relation_properties.hpp
//
//
//===----------------------------------------------------------------------===//
Expand All @@ -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 {

Expand All @@ -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
Expand All @@ -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
Expand All @@ -45,25 +55,29 @@ 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;

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<ClientContext> context = nullptr,
optional_ptr<const CTEDefinitionScope> cte_scope = nullptr)
explicit RelationProperties(DistinctnessPropagation propagation, optional_ptr<ClientContext> context = nullptr,
optional_ptr<const CTEDefinitionScope> 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<unique_ptr<Expression>> &keys);
//! The sets of columns the output of the operator is distinct on (cached)
const vector<column_binding_set_t> &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<ColumnAlias> GetColumnAliases(LogicalOperator &op, const vector<idx_t> &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
Expand All @@ -87,6 +101,7 @@ class Distinctness {
const optional_ptr<ClientContext> context;
optional_ptr<const CTEDefinitionScope> cte_scope;
reference_map_t<LogicalOperator, vector<column_binding_set_t>> unique_sets;
ColumnBindingLayoutCache layouts {ColumnBindingLayout::DuplicatePosition::FIRST};
};

} // namespace duckdb
Original file line number Diff line number Diff line change
Expand Up @@ -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<vector<idx_t>> unique_keys;
bool stats_initialized = false;
Identifier table_name;
Expand Down
Loading
Loading