Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::ART Class Reference
Inheritance diagram for duckdb::ART:
Collaboration diagram for duckdb::ART:

Public Member Functions

 ART (const string &name, const IndexConstraintType index_constraint_type, const vector< column_t > &column_ids, TableIOManager &table_io_manager, const vector< unique_ptr< Expression > > &unbound_expressions, AttachedDatabase &db, const shared_ptr< array< unsafe_unique_ptr< FixedSizeAllocator >, ALLOCATOR_COUNT > > &allocators_ptr=nullptr, const IndexStorageInfo &info=IndexStorageInfo())
unique_ptr< IndexScanState > TryInitializeScan (const Expression &expr, const Expression &filter_expr)
 Try to initialize a scan on the ART with the given expression and filter.
unique_ptr< IndexScanState > InitializeFullScan ()
bool Scan (IndexScanState &state, idx_t max_count, set< row_t > &row_ids)
void RemovalMerge (IndexLock &state, BoundIndex &source_index)
 Simple merge: scan source ART and delete each (key, rowid) from this ART.
void RemovalMerge (BoundIndex &source_index)
 Obtains a lock and calls RemovalMerge while holding that lock.
ErrorData InsertMerge (IndexLock &state, BoundIndex &source_index, IndexAppendMode append_mode)
ErrorData InsertMerge (BoundIndex &source_index, IndexAppendMode append_mode)
 Obtains a lock and calls InsertMerge while holding that lock.
ErrorData Append (IndexLock &l, DataChunk &chunk, Vector &row_ids) override
 Appends data to the locked index.
ErrorData Append (IndexLock &l, DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info) override
 Appends data to the locked index and verifies constraint violations.
ErrorData Insert (IndexLock &l, DataChunk &chunk, Vector &row_ids) override
 Insert a chunk.
ErrorData Insert (IndexLock &l, DataChunk &data, Vector &row_ids, IndexAppendInfo &info) override
ErrorData InsertKeys (ArenaAllocator &arena, unsafe_vector< ARTKey > &keys, unsafe_vector< ARTKey > &row_id_keys, idx_t count, const DeleteIndexInfo &delete_info, IndexAppendMode append_mode, optional_ptr< DataChunk > chunk=nullptr)
 Insert keys and row_ids into ART and verify constraint violations.
void VerifyAppend (DataChunk &chunk, IndexAppendInfo &info, optional_ptr< ConflictManager > manager) override
 Verify that data can be appended to the index without a constraint violation.
idx_t TryDelete (IndexLock &state, DataChunk &entries, Vector &row_identifiers, optional_ptr< SelectionVector > deleted_sel, optional_ptr< SelectionVector > non_deleted_sel) override
 Delete a chunk from the ART.
idx_t DeleteKeys (unsafe_vector< ARTKey > &keys, unsafe_vector< ARTKey > &row_id_keys, idx_t count, optional_ptr< SelectionVector > deleted_sel=nullptr, optional_ptr< SelectionVector > non_deleted_sel=nullptr)
 Delete keys and row_ids from the ART.
void CommitDrop (IndexLock &index_lock) override
 Drop the ART.
ARTConflictType Build (unsafe_vector< ARTKey > &keys, unsafe_vector< ARTKey > &row_ids, const idx_t row_count)
 Build an ART from a vector of sorted keys and their row IDs.
bool MergeIndexes (IndexLock &state, BoundIndex &other_index) override
void Vacuum (IndexLock &state) override
 Vacuums the ART storage.
IndexStorageInfo SerializeToDisk (QueryContext context, const case_insensitive_map_t< Value > &options) override
 Serializes ART memory to disk and returns the ART storage information.
IndexStorageInfo SerializeToWAL (const case_insensitive_map_t< Value > &options) override
 Serializes ART memory to the WAL and returns the ART storage information.
idx_t GetInMemorySize (IndexLock &index_lock) override
 Returns the in-memory usage of the ART.
bool SupportsDeltaIndexes () const override
 Whether or not the index supports the creation of delta indexes.
unique_ptr< BoundIndex > CreateDeltaIndex (DeltaIndexType delta_index_type) const override
 Creates a delta index - an empty copy of the index with the same schema, etc This will only be called if SupportsDeltaIndexes returns true.
template<bool IS_NOT_NULL = false>
void GenerateKeys (ArenaAllocator &allocator, DataChunk &input, unsafe_vector< ARTKey > &keys)
 ART key generation.
void GenerateKeyVectors (ArenaAllocator &allocator, DataChunk &input, Vector &row_ids, unsafe_vector< ARTKey > &keys, unsafe_vector< ARTKey > &row_id_keys)
void Verify (IndexLock &l) override
 Verifies the nodes.
void VerifyAllocations (IndexLock &l) override
 Verifies that the node allocations match the node counts.
void VerifyBuffers (IndexLock &l) override
 Verifies the index buffers.
string ToString (IndexLock &l, bool display_ascii=false) override
 Returns string representation of the ART.
uint8_t PrefixCount () const
 Returns the configured prefix byte capacity.
template<>
void GenerateKeys (ArenaAllocator &allocator, DataChunk &input, unsafe_vector< ARTKey > &keys)
template<>
void GenerateKeys (ArenaAllocator &allocator, DataChunk &input, unsafe_vector< ARTKey > &keys)
template<>
void GenerateKeys (ArenaAllocator &allocator, DataChunk &input, unsafe_vector< ARTKey > &keys)
template<>
void GenerateKeys (ArenaAllocator &allocator, DataChunk &input, unsafe_vector< ARTKey > &keys)
Public Member Functions inherited from duckdb::BoundIndex
 BoundIndex (const string &name, const string &index_type, IndexConstraintType index_constraint_type, const vector< column_t > &column_ids, TableIOManager &table_io_manager, const vector< unique_ptr< Expression > > &unbound_expressions, AttachedDatabase &db)
bool IsBound () const override
 Returns true if the index is a bound index, and false otherwise.
const string & GetIndexType () const override
 The index type (ART, B+-tree, Skip-List, ...).
const string & GetIndexName () const override
 The name of the index.
IndexConstraintType GetConstraintType () const override
 The index constraint type.
void InitializeLock (IndexLock &state)
 Obtains a lock on the index.
ErrorData Append (DataChunk &chunk, Vector &row_ids)
 Obtains a lock and calls Append while holding that lock.
ErrorData Append (DataChunk &chunk, Vector &row_ids, IndexAppendInfo &info)
 Obtains a lock and calls Append while holding that lock.
void CommitDrop () override
 Deletes all data from the index.
idx_t TryDelete (DataChunk &entries, Vector &row_identifiers, optional_ptr< SelectionVector > deleted_sel=nullptr, optional_ptr< SelectionVector > non_deleted_sel=nullptr)
 Obtains a lock and calls TryDelete while holding that lock.
virtual void Delete (IndexLock &state, DataChunk &entries, Vector &row_identifiers)
 Delete a chunk of entries from the index. The lock obtained from InitializeLock must be held. Throws an error if not all rows are deleted.
void Delete (DataChunk &entries, Vector &row_identifiers)
 Obtains a lock and calls Delete while holding that lock.
bool MergeIndexes (BoundIndex &other_index)
 Obtains a lock and calls MergeIndexes while holding that lock.
void Vacuum ()
 Obtains a lock and calls Vacuum while holding that lock.
idx_t GetInMemorySize ()
 Returns the in-memory usage of the index.
void Verify ()
 Obtains a lock and calls VerifyAndToString.
string ToString (bool display_ascii=false)
 Obtains a lock and calls ToString.
void VerifyAllocations ()
 Obtains a lock and calls VerifyAllocations.
void VerifyBuffers ()
 Obtains a lock and calls VerifyBuffers.
bool IndexIsUpdated (const vector< PhysicalIndex > &column_ids) const
 Returns true if the index is affected by updates on the specified column IDs, and false otherwise.
void ExecuteExpressions (DataChunk &input, DataChunk &result)
 Execute the index expressions on an input chunk.
void ApplyBufferedReplays (const vector< LogicalType > &table_types, BufferedIndexReplays &buffered_replays, const vector< StorageIndex > &mapped_column_ids)
 Replay index insert and delete operations buffered during WAL replay. table_types has the physical types of the table in the order they appear, not logical (no generated columns). mapped_column_ids contains the sorted order of Indexed physical column ID's (see unbound_index.hpp comments).
Public Member Functions inherited from duckdb::Index
bool IsUnique () const
 Returns unique flag.
bool IsPrimary () const
 Returns primary key flag.
bool IsForeign () const
 Returns foreign key flag.
const vector< column_t > & GetColumnIds () const
const unordered_set< column_t > & GetColumnIdSet () const
template<class TARGET>
TARGET & Cast ()
template<class TARGET>
const TARGET & Cast () const

Static Public Member Functions

static unique_ptr< BoundIndex > Create (CreateIndexInput &input)
 Create a index instance of this type.
static IndexType GetARTIndexType ()
Static Public Member Functions inherited from duckdb::BoundIndex
static string AppendRowError (DataChunk &input, idx_t index)

Public Attributes

Node tree = Node()
 Root of the tree.
shared_ptr< array< unsafe_unique_ptr< FixedSizeAllocator >, ALLOCATOR_COUNT > > allocators
 Fixed-size allocators holding the ART nodes.
bool owns_data
 True, if the ART owns its data.
optional_idx storage_version
 Storage version that the ART was created in, used for backwards compatible key generation.
Public Attributes inherited from duckdb::BoundIndex
vector< PhysicalType > types
 The physical types stored in the index.
vector< LogicalType > logical_types
 The logical types of the expressions.
string name
 The name of the index.
string index_type
 The index type (ART, B+-tree, Skip-List, ...).
IndexConstraintType index_constraint_type
 The index constraint type.
vector< unique_ptr< Expression > > unbound_expressions
 The vector of unbound expressions, which are later turned into bound expressions. We need to store the unbound expressions, as we might not always have the context available to bind directly. The leaves of these unbound expressions are BoundColumnRefExpressions. These BoundColumnRefExpressions contain a binding (ColumnBinding), and that contains a table_index and a column_index. The table_index is a dummy placeholder. The column_index indexes the column_ids vector in the Index base class. Those column_ids store the physical table indexes of the Index, and we use them when binding the unbound expressions.
DeltaIndexType delta_index_type = DeltaIndexType::NONE
 Whether or not this is a delta index - and if it is, which type it is.
Public Attributes inherited from duckdb::Index
TableIOManager & table_io_manager
 Associated table io manager.
AttachedDatabase & db
 Attached database instance.

Static Public Attributes

static constexpr const char * TYPE_NAME = "ART"
 Index type name for the ART.
static constexpr uint8_t ALLOCATOR_COUNT = 9
 FixedSizeAllocator count of the ART.
static constexpr uint8_t DEPRECATED_ALLOCATOR_COUNT = ALLOCATOR_COUNT - 3
 FixedSizeAllocator count of deprecated ARTs.

Private Member Functions

bool FullScan (idx_t max_count, set< row_t > &row_ids)
bool SearchEqual (ARTKey &key, idx_t max_count, set< row_t > &row_ids)
bool SearchGreater (ARTKey &key, bool equal, idx_t max_count, set< row_t > &row_ids)
bool SearchLess (ARTKey &upper_bound, bool equal, idx_t max_count, set< row_t > &row_ids)
bool SearchCloseRange (ARTKey &lower_bound, ARTKey &upper_bound, bool left_equal, bool right_equal, idx_t max_count, set< row_t > &row_ids)
string GenerateErrorKeyName (DataChunk &input, idx_t row)
string GenerateConstraintErrorMessage (VerifyExistenceType verify_type, const string &key_name)
void VerifyLeaf (const Node &leaf, const ARTKey &key, DeleteIndexInfo delete_index_info, ConflictManager &manager, optional_idx &conflict_idx, idx_t i)
void VerifyConstraint (DataChunk &chunk, IndexAppendInfo &info, ConflictManager &manager) override
 Verifies the constraint for a chunk of data.
string GetConstraintViolationMessage (VerifyExistenceType verify_type, idx_t failed_index, DataChunk &input) override
 Throw a constraint violation exception.
void InitializeMergeUpperBounds (unsafe_vector< idx_t > &upper_bounds)
void InitializeMerge (Node &node, unsafe_vector< idx_t > &upper_bounds)
void InitializeVacuum (unordered_set< uint8_t > &indexes)
void FinalizeVacuum (const unordered_set< uint8_t > &indexes)
void InitAllocators (const IndexStorageInfo &info)
void TransformToDeprecated ()
IndexStorageInfo PrepareSerialize (const case_insensitive_map_t< Value > &options, const bool v1_0_0_storage)
void Deserialize (const BlockPointer &pointer)
void WritePartialBlocks (QueryContext context, const bool v1_0_0_storage)
void SetPrefixCount (const IndexStorageInfo &info)
string ToStringInternal (bool display_ascii)
void VerifyInternal ()
void VerifyAllocationsInternal ()

Private Attributes

uint8_t prefix_count
 The number of bytes fitting in the prefix.

Friends

class Leaf

Additional Inherited Members

Protected Member Functions inherited from duckdb::Index
 Index (const vector< column_t > &column_ids, TableIOManager &table_io_manager, AttachedDatabase &db)
Protected Attributes inherited from duckdb::BoundIndex
mutex lock
 Lock used for any changes to the index.
vector< unique_ptr< Expression > > bound_expressions
 The vector of bound expressions to generate the Index keys based on a data chunk. The leaves of the bound expressions are BoundReferenceExpressions. These BoundReferenceExpressions contain offsets into the DataChunk to retrieve the columns for the expression. With these offsets into the DataChunk, the expression executor can now evaluate the expression on incoming data chunks to generate the keys.
Protected Attributes inherited from duckdb::Index
vector< column_t > column_ids
 The physical column ids of the indexed columns. For example, given a table with the following columns: (a INT, gen AS (2 * a), b INT, c VARCHAR), an index on columns (a,c) would have physical column_ids [0,2] (since the virtual column is skipped in the physical representation). Also see comments in bound_index.hpp to see how these column IDs are used in the context of bound/unbound expressions. Note that these are the columns for this Index, not all Indexes on the table.
unordered_set< column_t > column_id_set
 Unordered set of column_ids used by the Index.

Constructor & Destructor Documentation

◆ ART()

duckdb::ART::ART ( const string & name,
const IndexConstraintType index_constraint_type,
const vector< column_t > & column_ids,
TableIOManager & table_io_manager,
const vector< unique_ptr< Expression > > & unbound_expressions,
AttachedDatabase & db,
const shared_ptr< array< unsafe_unique_ptr< FixedSizeAllocator >, ALLOCATOR_COUNT > > & allocators_ptr = nullptr,
const IndexStorageInfo & info = IndexStorageInfo() )
151249 allocators(allocators_ptr), owns_data(false) {
151250 // FIXME: Use the new byte representation function to support nested types.
151251 for (idx_t i = 0; i < types.size(); i++) {
151252 switch (types[i]) {
151253 case PhysicalType::BOOL:
151254 case PhysicalType::INT8:
151255 case PhysicalType::INT16:
151256 case PhysicalType::INT32:
151257 case PhysicalType::INT64:
151258 case PhysicalType::INT128:
151259 case PhysicalType::UINT8:
151263 case PhysicalType::UINT128:
151264 case PhysicalType::FLOAT:
151267 break;
151268 default:
151269 throw InvalidTypeException(logical_types[i], "Invalid type for index key.");
151270 }
151271 }
151272
151273 // Initialize the allocators.
151274 SetPrefixCount(info);
151275 if (!allocators) {
151276 owns_data = true;
151277 auto prefix_size = NumericCast<idx_t>(prefix_count) + NumericCast<idx_t>(Prefix::METADATA_SIZE);
151278 auto &block_manager = table_io_manager.GetIndexBlockManager();
151279
151280 array<unsafe_unique_ptr<FixedSizeAllocator>, ALLOCATOR_COUNT> allocator_array = {
151281 make_unsafe_uniq<FixedSizeAllocator>(prefix_size, block_manager),
151282 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Leaf), block_manager),
151283 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Node4), block_manager),
151284 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Node16), block_manager),
151285 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Node48), block_manager),
151286 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Node256), block_manager),
151287 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Node7Leaf), block_manager),
151288 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Node15Leaf), block_manager),
151289 make_unsafe_uniq<FixedSizeAllocator>(sizeof(Node256Leaf), block_manager),
151290 };
151291 allocators =
151292 make_shared_ptr<array<unsafe_unique_ptr<FixedSizeAllocator>, ALLOCATOR_COUNT>>(std::move(allocator_array));
151293 }
151294
151295 if (!info.IsValid()) {
151296 // We create a new ART.
151297 storage_version = db.GetStorageManager().GetStorageVersion();
151298 return;
151299 }
151300
151301 if (info.root_block_ptr.IsValid()) {
151302 // Backwards compatibility.
151303 Deserialize(info.root_block_ptr);
151304 return;
151305 }
151306
151307 // Set the root node and initialize the allocators.
151308 tree.Set(info.root);
151309 InitAllocators(info);
151310
151311 // Set the storage version of the ART
151312 auto it = info.options.find("storage_version");
151313 if (it != info.options.end()) {
151314 // If this is an existing index with a saved storage version, use it.
151315 storage_version = it->second.GetValue<idx_t>();
151316 } else {
151317 // Otherwise, this must be an existing index without a saved storage version.
151318 // We started saving the storage version in v1.5.0, so if it is not present,
151319 // we can not make any general assumptions about the exact storage version.
151320 storage_version = optional_idx::Invalid();
151321 }
151322}
uint8_t prefix_count
The number of bytes fitting in the prefix.
Definition duckdb.cpp:12262
optional_idx storage_version
Storage version that the ART was created in, used for backwards compatible key generation.
Definition duckdb.cpp:12165
static constexpr const char * TYPE_NAME
Index type name for the ART.
Definition duckdb.cpp:12136
bool owns_data
True, if the ART owns its data.
Definition duckdb.cpp:12163
Node tree
Root of the tree.
Definition duckdb.cpp:12159
static constexpr uint8_t ALLOCATOR_COUNT
FixedSizeAllocator count of the ART.
Definition duckdb.cpp:12138
shared_ptr< array< unsafe_unique_ptr< FixedSizeAllocator >, ALLOCATOR_COUNT > > allocators
Fixed-size allocators holding the ART nodes.
Definition duckdb.cpp:12161
vector< PhysicalType > types
The physical types stored in the index.
Definition duckdb.hpp:50020
vector< LogicalType > logical_types
The logical types of the expressions.
Definition duckdb.hpp:50022
string name
The name of the index.
Definition duckdb.hpp:50025
IndexConstraintType index_constraint_type
The index constraint type.
Definition duckdb.hpp:50029
vector< unique_ptr< Expression > > unbound_expressions
The vector of unbound expressions, which are later turned into bound expressions. We need to store th...
Definition duckdb.hpp:50041
TableIOManager & table_io_manager
Associated table io manager.
Definition duckdb.hpp:49684
vector< column_t > column_ids
The physical column ids of the indexed columns. For example, given a table with the following columns...
Definition duckdb.hpp:49678
AttachedDatabase & db
Attached database instance.
Definition duckdb.hpp:49686
@ UINT32
Unsigned 32-bit little-endian integer.
Definition duckdb.hpp:2758
@ UINT16
Unsigned 16-bit little-endian integer.
Definition duckdb.hpp:2752
@ INT64
Signed 64-bit little-endian integer.
Definition duckdb.hpp:2767
@ INT16
Signed 16-bit little-endian integer.
Definition duckdb.hpp:2755
@ INT32
Signed 32-bit little-endian integer.
Definition duckdb.hpp:2761
@ UINT64
Unsigned 64-bit little-endian integer.
Definition duckdb.hpp:2764
@ BOOL
Boolean as 8 bit "bool" value.
Definition duckdb.hpp:2743
@ VARCHAR
DuckDB Extensions.
Definition duckdb.hpp:2847
@ FLOAT
4-byte floating point value
Definition duckdb.hpp:2773
@ UINT8
Unsigned 8-bit little-endian integer.
Definition duckdb.hpp:2746
@ INT8
Signed 8-bit little-endian integer.
Definition duckdb.hpp:2749
@ DOUBLE
8-byte floating point value
Definition duckdb.hpp:2776
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

Member Function Documentation

◆ Create()

unique_ptr< BoundIndex > duckdb::ART::Create ( CreateIndexInput & input)
inlinestatic

Create a index instance of this type.

12150 {
12151 auto art = make_uniq<ART>(input.name, input.constraint_type, input.column_ids, input.table_io_manager,
12152 input.unbound_expressions, input.db, nullptr, input.storage_info);
12153 return std::move(art);
12154 }

◆ GetARTIndexType()

IndexType duckdb::ART::GetARTIndexType ( )
static
152913 {
152914 IndexType art_index_type;
152915 art_index_type.name = ART::TYPE_NAME;
152916 art_index_type.create_instance = ART::Create;
152917 art_index_type.build_bind = ARTBuildBind;
152918 art_index_type.build_sort = ARTBuildSort;
152919 art_index_type.build_global_init = ARTBuildGlobalInit;
152920 art_index_type.build_local_init = ARTBuildLocalInit;
152921 art_index_type.build_sink = ARTBuildSink;
152922 art_index_type.build_combine = ARTBuildCombine;
152923 art_index_type.build_finalize = ARTBuildFinalize;
152924 return art_index_type;
152925}
static unique_ptr< BoundIndex > Create(CreateIndexInput &input)
Create a index instance of this type.
Definition duckdb.cpp:12150

◆ TryInitializeScan()

unique_ptr< IndexScanState > duckdb::ART::TryInitializeScan ( const Expression & expr,
const Expression & filter_expr )

Try to initialize a scan on the ART with the given expression and filter.

151348 {
151349 Value low_value, high_value, equal_value;
151350 ExpressionType low_comparison_type = ExpressionType::INVALID, high_comparison_type = ExpressionType::INVALID;
151351
151352 // Try to find a matching index for any of the filter expressions.
151353 ComparisonExpressionMatcher matcher;
151354
151355 // Match on a comparison type.
151356 matcher.expr_type = make_uniq<ComparisonExpressionTypeMatcher>();
151357
151358 // Match on a constant comparison with the indexed expression.
151359 matcher.matchers.push_back(make_uniq<ExpressionEqualityMatcher>(expr));
151360 matcher.matchers.push_back(make_uniq<ConstantExpressionMatcher>());
151361 matcher.policy = SetMatcher::Policy::UNORDERED;
151362
151363 vector<reference<Expression>> bindings;
151364 auto filter_match =
151365 matcher.Match(const_cast<Expression &>(filter_expr), bindings); // NOLINT: Match does not alter the expr.
151366 if (filter_match) {
151367 // This is a range or equality comparison with a constant value, so we can use the index.
151368 // bindings[0] = the expression
151369 // bindings[1] = the index expression
151370 // bindings[2] = the constant
151371 auto &comparison = bindings[0].get().Cast<BoundComparisonExpression>();
151372 auto constant_value = bindings[2].get().Cast<BoundConstantExpression>().value;
151373 auto comparison_type = comparison.GetExpressionType();
151374
151375 if (comparison.left->GetExpressionType() == ExpressionType::VALUE_CONSTANT) {
151376 // The expression is on the right side, we flip the comparison expression.
151377 comparison_type = FlipComparisonExpression(comparison_type);
151378 }
151379
151380 if (comparison_type == ExpressionType::COMPARE_EQUAL) {
151381 // An equality value overrides any other bounds.
151382 equal_value = constant_value;
151383 } else if (comparison_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO ||
151384 comparison_type == ExpressionType::COMPARE_GREATERTHAN) {
151385 // This is a lower bound.
151386 low_value = constant_value;
151387 low_comparison_type = comparison_type;
151388 } else {
151389 // This is an upper bound.
151390 high_value = constant_value;
151391 high_comparison_type = comparison_type;
151392 }
151393 } else if (filter_expr.GetExpressionType() == ExpressionType::COMPARE_BETWEEN) {
151394 auto &between = filter_expr.Cast<BoundBetweenExpression>();
151395 if (!between.input->Equals(expr)) {
151396 // The expression does not match the index expression.
151397 return nullptr;
151398 }
151399
151400 if (between.lower->GetExpressionType() != ExpressionType::VALUE_CONSTANT ||
151401 between.upper->GetExpressionType() != ExpressionType::VALUE_CONSTANT) {
151402 // Not a constant expression.
151403 return nullptr;
151404 }
151405
151406 low_value = between.lower->Cast<BoundConstantExpression>().value;
151407 low_comparison_type = between.lower_inclusive ? ExpressionType::COMPARE_GREATERTHANOREQUALTO
151408 : ExpressionType::COMPARE_GREATERTHAN;
151409 high_value = (between.upper->Cast<BoundConstantExpression>()).value;
151410 high_comparison_type =
151411 between.upper_inclusive ? ExpressionType::COMPARE_LESSTHANOREQUALTO : ExpressionType::COMPARE_LESSTHAN;
151412 }
151413 // FIXME: add another if...else... to match rewritten BETWEEN,
151414 // i.e., WHERE i BETWEEN 50 AND 1502 is rewritten to CONJUNCTION_AND.
151415
151416 // We cannot use an index scan.
151417 if (equal_value.IsNull() && low_value.IsNull() && high_value.IsNull()) {
151418 return nullptr;
151419 }
151420
151421 // Initialize the index scan state and return it.
151422 if (!equal_value.IsNull()) {
151423 // Equality predicate.
151424 return InitializeScanSinglePredicate(equal_value, ExpressionType::COMPARE_EQUAL);
151425 }
151426 if (!low_value.IsNull() && !high_value.IsNull()) {
151427 // Two-sided predicate.
151428 return InitializeScanTwoPredicates(low_value, low_comparison_type, high_value, high_comparison_type);
151429 }
151430 if (!low_value.IsNull()) {
151431 // Less-than predicate.
151432 return InitializeScanSinglePredicate(low_value, low_comparison_type);
151433 }
151434 // Greater-than predicate.
151435 return InitializeScanSinglePredicate(high_value, high_comparison_type);
151436}
@ UNORDERED
All entries have to be matched, but the order of the matches does not matter.
Definition duckdb.cpp:69123
ExpressionType FlipComparisonExpression(ExpressionType type)
Flip a comparison expression, turning e.g. < into >, or = into =.
Definition duckdb.cpp:68052
Here is the call graph for this function:

◆ InitializeFullScan()

unique_ptr< IndexScanState > duckdb::ART::InitializeFullScan ( )
151438 {
151439 return make_uniq<ARTIndexScanState>();
151440}

◆ Scan()

bool duckdb::ART::Scan ( IndexScanState & state,
idx_t max_count,
set< row_t > & row_ids )

Perform a lookup on the ART, fetching up to max_count row IDs. If all row IDs were fetched, it return true, else false.

151959 {
151960 auto &scan_state = state.Cast<ARTIndexScanState>();
151961 if (scan_state.values[0].IsNull()) {
151962 // full scan
151963 lock_guard<mutex> l(lock);
151964 return FullScan(max_count, row_ids);
151965 }
151966 D_ASSERT(scan_state.values[0].type().InternalType() == types[0]);
151967 ArenaAllocator arena_allocator(Allocator::Get(db));
151968
151969 auto key = ARTKey::CreateKey(arena_allocator, scan_state.values[0], storage_version);
151970
151971 lock_guard<mutex> l(lock);
151972 if (scan_state.values[1].IsNull()) {
151973 // Single predicate.
151974 switch (scan_state.expressions[0]) {
151975 case ExpressionType::COMPARE_EQUAL:
151976 return SearchEqual(key, max_count, row_ids);
151977 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
151978 return SearchGreater(key, true, max_count, row_ids);
151979 case ExpressionType::COMPARE_GREATERTHAN:
151980 return SearchGreater(key, false, max_count, row_ids);
151981 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
151982 return SearchLess(key, true, max_count, row_ids);
151983 case ExpressionType::COMPARE_LESSTHAN:
151984 return SearchLess(key, false, max_count, row_ids);
151985 default:
151986 throw InternalException("Index scan type not implemented");
151987 }
151988 }
151989
151990 // Two predicates.
151991 D_ASSERT(scan_state.values[1].type().InternalType() == types[0]);
151992
151993 auto upper_bound = ARTKey::CreateKey(arena_allocator, scan_state.values[1], storage_version);
151994
151995 bool left_equal = scan_state.expressions[0] == ExpressionType ::COMPARE_GREATERTHANOREQUALTO;
151996 bool right_equal = scan_state.expressions[1] == ExpressionType ::COMPARE_LESSTHANOREQUALTO;
151997 return SearchCloseRange(key, upper_bound, left_equal, right_equal, max_count, row_ids);
151998}
mutex lock
Lock used for any changes to the index.
Definition duckdb.hpp:50170

◆ RemovalMerge() [1/2]

void duckdb::ART::RemovalMerge ( IndexLock & state,
BoundIndex & source_index )

Simple merge: scan source ART and delete each (key, rowid) from this ART.

152515 {
152516 auto &source = source_index.Cast<ART>();
152517 if (!source.tree.HasMetadata()) {
152518 return;
152519 }
152520
152521 ArenaAllocator arena(BufferAllocator::Get(db));
152522 idx_t scan_count = 0;
152523 idx_t delete_count = 0;
152524
152525 Iterator it(source);
152526 it.FindMinimum(source.tree);
152527
152528 unsafe_vector<ARTKey> keys(STANDARD_VECTOR_SIZE);
152529 unsafe_vector<ARTKey> row_id_keys(STANDARD_VECTOR_SIZE);
152530 ARTKey empty_key = ARTKey();
152531
152532 KeyRowIdOutput output(arena, keys, row_id_keys, STANDARD_VECTOR_SIZE);
152533 ARTScanResult result;
152534 do {
152535 output.Reset();
152536 result = it.Scan(empty_key, output, false);
152537 if (output.Count() > 0) {
152538 scan_count += output.Count();
152539 delete_count += DeleteKeys(keys, row_id_keys, output.Count());
152540 }
152541 } while (result == ARTScanResult::PAUSED);
152542
152543 if (delete_count != scan_count) {
152544 throw InternalException("Failed to remove all rows while merging checkpoint deltas - "
152545 "this signifies a bug or broken index");
152546 }
152547}
idx_t DeleteKeys(unsafe_vector< ARTKey > &keys, unsafe_vector< ARTKey > &row_id_keys, idx_t count, optional_ptr< SelectionVector > deleted_sel=nullptr, optional_ptr< SelectionVector > non_deleted_sel=nullptr)
Delete keys and row_ids from the ART.
Definition duckdb.cpp:151839
ARTScanResult
Definition duckdb.cpp:59088
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RemovalMerge() [2/2]

void duckdb::ART::RemovalMerge ( BoundIndex & source_index)

Obtains a lock and calls RemovalMerge while holding that lock.

152549 {
152550 IndexLock state;
152551 InitializeLock(state);
152552 RemovalMerge(state, source_index);
152553}
void RemovalMerge(IndexLock &state, BoundIndex &source_index)
Simple merge: scan source ART and delete each (key, rowid) from this ART.
Definition duckdb.cpp:152515
void InitializeLock(IndexLock &state)
Obtains a lock on the index.
Definition duckdb.cpp:155906
Here is the call graph for this function:

◆ InsertMerge() [1/2]

ErrorData duckdb::ART::InsertMerge ( IndexLock & state,
BoundIndex & source_index,
IndexAppendMode append_mode )

Simple merge: scan source ART and insert each (key, rowid) into this ART. Returns error data if constraint violation.

152558 {
152559 auto &source = source_index.Cast<ART>();
152560 if (!source.tree.HasMetadata()) {
152561 return ErrorData();
152562 }
152563
152564 ArenaAllocator arena(BufferAllocator::Get(db));
152565
152566 Iterator it(source);
152567 it.FindMinimum(source.tree);
152568
152569 unsafe_vector<ARTKey> keys(STANDARD_VECTOR_SIZE);
152570 unsafe_vector<ARTKey> row_id_keys(STANDARD_VECTOR_SIZE);
152571 ARTKey empty_key = ARTKey();
152572
152573 KeyRowIdOutput output(arena, keys, row_id_keys, STANDARD_VECTOR_SIZE);
152574 ARTScanResult result;
152575 do {
152576 output.Reset();
152577 result = it.Scan(empty_key, output, false);
152578 if (output.Count() > 0) {
152579 auto error = InsertKeys(arena, keys, row_id_keys, output.Count(), DeleteIndexInfo(), append_mode);
152580 if (error.HasError()) {
152581 return error;
152582 }
152583 }
152584 } while (result == ARTScanResult::PAUSED);
152585
152586 return ErrorData();
152587}
ErrorData InsertKeys(ArenaAllocator &arena, unsafe_vector< ARTKey > &keys, unsafe_vector< ARTKey > &row_id_keys, idx_t count, const DeleteIndexInfo &delete_info, IndexAppendMode append_mode, optional_ptr< DataChunk > chunk=nullptr)
Insert keys and row_ids into ART and verify constraint violations.
Definition duckdb.cpp:151718
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InsertMerge() [2/2]

ErrorData duckdb::ART::InsertMerge ( BoundIndex & source_index,
IndexAppendMode append_mode )

Obtains a lock and calls InsertMerge while holding that lock.

152589 {
152590 IndexLock state;
152591 InitializeLock(state);
152592 return InsertMerge(state, source_index, append_mode);
152593}
ErrorData InsertMerge(IndexLock &state, BoundIndex &source_index, IndexAppendMode append_mode)
Definition duckdb.cpp:152558
Here is the call graph for this function:

◆ Append() [1/2]

ErrorData duckdb::ART::Append ( IndexLock & l,
DataChunk & chunk,
Vector & row_ids )
overridevirtual

Appends data to the locked index.

Implements duckdb::BoundIndex.

151780 {
151781 // Execute all column expressions before inserting the data chunk.
151782 DataChunk expr_chunk;
151783 expr_chunk.Initialize(Allocator::DefaultAllocator(), logical_types);
151784 ExecuteExpressions(chunk, expr_chunk);
151785
151786 // Now insert the data chunk.
151787 IndexAppendInfo info;
151788 return Insert(l, expr_chunk, row_ids, info);
151789}
ErrorData Insert(IndexLock &l, DataChunk &chunk, Vector &row_ids) override
Insert a chunk.
Definition duckdb.cpp:151700
void ExecuteExpressions(DataChunk &input, DataChunk &result)
Execute the index expressions on an input chunk.
Definition duckdb.cpp:156017
DUCKDB_API void Initialize(ClientContext &context, const vector< LogicalType > &types, idx_t capacity=STANDARD_VECTOR_SIZE)
Definition duckdb.cpp:116791
Here is the call graph for this function:

◆ Append() [2/2]

ErrorData duckdb::ART::Append ( IndexLock & l,
DataChunk & chunk,
Vector & row_ids,
IndexAppendInfo & info )
overridevirtual

Appends data to the locked index and verifies constraint violations.

Reimplemented from duckdb::BoundIndex.

151791 {
151792 // Execute all column expressions before inserting the data chunk.
151793 DataChunk expr_chunk;
151794 expr_chunk.Initialize(Allocator::DefaultAllocator(), logical_types);
151795 ExecuteExpressions(chunk, expr_chunk);
151796
151797 // Now insert the data chunk.
151798 return Insert(l, expr_chunk, row_ids, info);
151799}
Here is the call graph for this function:

◆ Insert() [1/2]

ErrorData duckdb::ART::Insert ( IndexLock & l,
DataChunk & chunk,
Vector & row_ids )
overridevirtual

Insert a chunk.

Implements duckdb::BoundIndex.

151700 {
151701 IndexAppendInfo info;
151702 return Insert(l, chunk, row_ids, info);
151703}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Insert() [2/2]

ErrorData duckdb::ART::Insert ( IndexLock & l,
DataChunk & data,
Vector & row_ids,
IndexAppendInfo & info )
overridevirtual

Insert a chunk and verify constraint violations (generates keys and calls InsertKeys which does the verification).

Reimplemented from duckdb::BoundIndex.

151705 {
151706 D_ASSERT(row_ids.GetType().InternalType() == ROW_TYPE);
151707 auto row_count = chunk.size();
151708
151709 ArenaAllocator arena(BufferAllocator::Get(db));
151710 unsafe_vector<ARTKey> keys(row_count);
151711 unsafe_vector<ARTKey> row_id_keys(row_count);
151712 GenerateKeyVectors(arena, chunk, row_ids, keys, row_id_keys);
151713
151714 return InsertKeys(arena, keys, row_id_keys, row_count, DeleteIndexInfo(info.delete_indexes), info.append_mode,
151715 &chunk);
151716}
const PhysicalType ROW_TYPE
The PhysicalType used by the row identifiers column.
Definition duckdb.cpp:139304
Here is the call graph for this function:

◆ InsertKeys()

ErrorData duckdb::ART::InsertKeys ( ArenaAllocator & arena,
unsafe_vector< ARTKey > & keys,
unsafe_vector< ARTKey > & row_id_keys,
idx_t count,
const DeleteIndexInfo & delete_info,
IndexAppendMode append_mode,
optional_ptr< DataChunk > chunk = nullptr )

Insert keys and row_ids into ART and verify constraint violations.

151720 {
151721 auto conflict_type = ARTConflictType::NO_CONFLICT;
151722 optional_idx conflict_idx;
151723 auto was_empty = !tree.HasMetadata();
151724
151725 // Insert the entries into the index.
151726 for (idx_t i = 0; i < row_count; i++) {
151727 if (keys[i].Empty()) {
151728 continue;
151729 }
151730 conflict_type = ARTOperator::Insert(arena, *this, tree, keys[i], 0, row_id_keys[i], GateStatus::GATE_NOT_SET,
151731 delete_info, append_mode);
151732 if (conflict_type != ARTConflictType::NO_CONFLICT) {
151733 conflict_idx = i;
151734 break;
151735 }
151736 }
151737
151738 // Remove any previously inserted entries.
151739 if (conflict_type != ARTConflictType::NO_CONFLICT) {
151740 D_ASSERT(conflict_idx.IsValid());
151741 for (idx_t i = 0; i < conflict_idx.GetIndex(); i++) {
151742 if (keys[i].Empty()) {
151743 continue;
151744 }
151745 D_ASSERT(tree.GetGateStatus() == GateStatus::GATE_NOT_SET);
151746 ARTOperator::Delete(*this, tree, keys[i], row_id_keys[i]);
151747 }
151748 }
151749
151750 if (was_empty) {
151751 // All nodes are in-memory.
151752 VerifyAllocationsInternal();
151753 }
151754
151755 if (conflict_type == ARTConflictType::TRANSACTION) {
151756 // chunk is only null when called from MergeCheckpointDeltas.
151757 auto msg = chunk ? AppendRowError(*chunk, conflict_idx.GetIndex()) : string("???");
151758 return ErrorData(TransactionException("write-write conflict on key: \"%s\"", msg));
151759 }
151760
151761 if (conflict_type == ARTConflictType::CONSTRAINT) {
151762 // chunk is only null when called from MergeCheckpointDeltas.
151763 auto msg = chunk ? AppendRowError(*chunk, conflict_idx.GetIndex()) : string("???");
151764 return ErrorData(ConstraintException("PRIMARY KEY or UNIQUE constraint violation: duplicate key \"%s\"", msg));
151765 }
151766
151767#ifdef DEBUG
151768 for (idx_t i = 0; i < row_count; i++) {
151769 if (keys[i].Empty()) {
151770 continue;
151771 }
151772 auto leaf = ARTOperator::Lookup(*this, tree, keys[i], 0);
151773 D_ASSERT(leaf);
151774 D_ASSERT(ARTOperator::LookupInLeaf(*this, *leaf, row_id_keys[i]));
151775 }
151776#endif
151777 return ErrorData();
151778}
static bool Delete(ART &art, Node &node, const ARTKey &key, const ARTKey &row_id)
Definition duckdb.cpp:150672
static bool LookupInLeaf(ART &art, const Node &node, const ARTKey &rowid)
Definition duckdb.cpp:150519
static ARTConflictType Insert(ArenaAllocator &arena, ART &art, Node &node, const ARTKey &key, idx_t depth, const ARTKey &row_id, GateStatus status, DeleteIndexInfo delete_index_info, const IndexAppendMode append_mode)
Definition duckdb.cpp:150573
static unsafe_optional_ptr< const Node > Lookup(ART &art, const Node &node, const ARTKey &key, idx_t depth)
Definition duckdb.cpp:150475
Here is the call graph for this function:
Here is the caller graph for this function:

◆ VerifyAppend()

void duckdb::ART::VerifyAppend ( DataChunk & chunk,
IndexAppendInfo & info,
optional_ptr< ConflictManager > manager )
overridevirtual

Verify that data can be appended to the index without a constraint violation.

Reimplemented from duckdb::BoundIndex.

151801 {
151802 if (manager) {
151803 D_ASSERT(manager->GetVerifyExistenceType() == VerifyExistenceType::APPEND);
151804 return VerifyConstraint(chunk, info, *manager);
151805 }
151806 ConflictManager local_manager(VerifyExistenceType::APPEND, chunk.size());
151807 VerifyConstraint(chunk, info, local_manager);
151808}
void VerifyConstraint(DataChunk &chunk, IndexAppendInfo &info, ConflictManager &manager) override
Verifies the constraint for a chunk of data.
Definition duckdb.cpp:152123
Here is the call graph for this function:

◆ TryDelete()

idx_t duckdb::ART::TryDelete ( IndexLock & state,
DataChunk & entries,
Vector & row_identifiers,
optional_ptr< SelectionVector > deleted_sel,
optional_ptr< SelectionVector > non_deleted_sel )
overridevirtual

Delete a chunk from the ART.

Reimplemented from duckdb::BoundIndex.

151822 {
151823 // FIXME: We could pass a row_count in here, as we sometimes don't have to delete all row IDs in the chunk,
151824 // FIXME: but rather all row IDs up to the conflicting row.
151825 auto row_count = entries.size();
151826
151827 DataChunk expr_chunk;
151828 expr_chunk.Initialize(Allocator::DefaultAllocator(), logical_types);
151829 ExecuteExpressions(entries, expr_chunk);
151830
151831 ArenaAllocator allocator(BufferAllocator::Get(db));
151832 unsafe_vector<ARTKey> keys(row_count);
151833 unsafe_vector<ARTKey> row_id_keys(row_count);
151834 GenerateKeyVectors(allocator, expr_chunk, row_ids, keys, row_id_keys);
151835
151836 return DeleteKeys(keys, row_id_keys, row_count, deleted_sel, non_deleted_sel);
151837}
Here is the call graph for this function:

◆ DeleteKeys()

idx_t duckdb::ART::DeleteKeys ( unsafe_vector< ARTKey > & keys,
unsafe_vector< ARTKey > & row_id_keys,
idx_t count,
optional_ptr< SelectionVector > deleted_sel = nullptr,
optional_ptr< SelectionVector > non_deleted_sel = nullptr )

Delete keys and row_ids from the ART.

151840 {
151841 idx_t delete_count = 0;
151842 for (idx_t i = 0; i < row_count; i++) {
151843 bool deleted = true;
151844 if (!keys[i].Empty()) {
151845 D_ASSERT(tree.GetGateStatus() == GateStatus::GATE_NOT_SET);
151846 deleted = ARTOperator::Delete(*this, tree, keys[i], row_id_keys[i]);
151847 }
151848 if (deleted) {
151849 if (deleted_sel) {
151850 deleted_sel->set_index(delete_count, i);
151851 }
151852 delete_count++;
151853 } else if (non_deleted_sel) {
151854 idx_t non_delete_count = i - delete_count;
151855 non_deleted_sel->set_index(non_delete_count, i);
151856 }
151857 }
151858
151859 if (!tree.HasMetadata()) {
151860 // No more allocations.
151861 VerifyAllocationsInternal();
151862 }
151863
151864#ifdef DEBUG
151865 for (idx_t i = 0; i < row_count; i++) {
151866 if (keys[i].Empty()) {
151867 continue;
151868 }
151869 auto leaf = ARTOperator::Lookup(*this, tree, keys[i], 0);
151870 if (leaf) {
151871 auto contains_row_id = ARTOperator::LookupInLeaf(*this, *leaf, row_id_keys[i]);
151872 D_ASSERT(!contains_row_id);
151873 }
151874 }
151875#endif
151876 return delete_count;
151877}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CommitDrop()

void duckdb::ART::CommitDrop ( IndexLock & index_lock)
overridevirtual

Drop the ART.

Implements duckdb::BoundIndex.

151814 {
151815 for (auto &allocator : *allocators) {
151816 allocator->Reset();
151817 }
151818 tree.Clear();
151819}

◆ Build()

ARTConflictType duckdb::ART::Build ( unsafe_vector< ARTKey > & keys,
unsafe_vector< ARTKey > & row_ids,
const idx_t row_count )

Build an ART from a vector of sorted keys and their row IDs.

151673 {
151674 ArenaAllocator arena(BufferAllocator::Get(db));
151675 ARTBuilder builder(arena, *this, keys, row_ids);
151676 builder.Init(tree, row_count - 1);
151677
151678 auto result = builder.Build();
151679 if (result != ARTConflictType::NO_CONFLICT) {
151680 return result;
151681 }
151682
151683#ifdef DEBUG
151684 set<row_t> row_ids_debug;
151685 Iterator it(*this);
151686 it.FindMinimum(tree);
151687 ARTKey empty_key = ARTKey();
151688 RowIdSetOutput output(row_ids_debug, NumericLimits<idx_t>().Maximum());
151689 it.Scan(empty_key, output, false);
151690 D_ASSERT(row_count == row_ids_debug.size());
151691#endif
151692
151693 return ARTConflictType::NO_CONFLICT;
151694}
Here is the call graph for this function:

◆ MergeIndexes()

bool duckdb::ART::MergeIndexes ( IndexLock & state,
BoundIndex & other_index )
overridevirtual

Merge another ART into this ART. Both must be locked. FIXME: Return ARTConflictType instead of a boolean.

Implements duckdb::BoundIndex.

152476 {
152477 auto &other_art = source_index.Cast<ART>();
152478 if (!other_art.tree.HasMetadata()) {
152479 return true;
152480 }
152481
152482 if (other_art.owns_data) {
152483 if (prefix_count != other_art.prefix_count) {
152484 throw InternalException("Failed to merge ARTs - prefix count does not match");
152485 }
152486 if (tree.HasMetadata()) {
152487 // Fully deserialize other_index, and traverse it to increment its buffer IDs.
152488 unsafe_vector<idx_t> upper_bounds;
152489 InitializeMergeUpperBounds(upper_bounds);
152490 other_art.InitializeMerge(other_art.tree, upper_bounds);
152491 }
152492
152493 // Merge the node storage.
152494 for (idx_t i = 0; i < allocators->size(); i++) {
152495 (*allocators)[i]->Merge(*(*other_art.allocators)[i]);
152496 }
152497 }
152498
152499 // Merge the ARTs.
152500 D_ASSERT(tree.GetGateStatus() == other_art.tree.GetGateStatus());
152501 if (tree.HasMetadata()) {
152502 ArenaAllocator arena(Allocator::Get(db));
152503 ARTMerger merger(arena, *this);
152504 merger.Init(tree, other_art.tree);
152505 return merger.Merge() == ARTConflictType::NO_CONFLICT;
152506 }
152507
152508 tree = other_art.tree;
152509 other_art.tree.Clear();
152510 return true;
152511}
Here is the call graph for this function:

◆ Vacuum()

void duckdb::ART::Vacuum ( IndexLock & state)
overridevirtual

Vacuums the ART storage.

Implements duckdb::BoundIndex.

152374 {
152375 D_ASSERT(owns_data);
152376
152377 if (!tree.HasMetadata()) {
152378 for (auto &allocator : *allocators) {
152379 allocator->Reset();
152380 }
152381 return;
152382 }
152383
152384 // True, if an allocator needs a vacuum, false otherwise.
152385 unordered_set<uint8_t> indexes;
152386 InitializeVacuum(indexes);
152387
152388 // Skip vacuum, if no allocators require it.
152389 if (indexes.empty()) {
152390 return;
152391 }
152392
152393 // Traverse the allocated memory of the tree to perform a vacuum.
152394 auto &art = *this;
152395 auto handler = [&art, &indexes](Node &node) {
152396 ARTHandlingResult result;
152397 const auto type = node.GetType();
152398 switch (type) {
152399 case NType::LEAF_INLINED:
152400 return ARTHandlingResult::SKIP;
152401 case NType::LEAF: {
152402 if (indexes.find(Node::GetAllocatorIdx(type)) == indexes.end()) {
152403 return ARTHandlingResult::SKIP;
152404 }
152405 Leaf::DeprecatedVacuum(art, node);
152406 return ARTHandlingResult::SKIP;
152407 }
152408 case NType::NODE_7_LEAF:
152409 case NType::NODE_15_LEAF:
152410 case NType::NODE_256_LEAF: {
152411 result = ARTHandlingResult::SKIP;
152412 break;
152413 }
152414 case NType::PREFIX:
152415 case NType::NODE_4:
152416 case NType::NODE_16:
152417 case NType::NODE_48:
152418 case NType::NODE_256: {
152419 result = ARTHandlingResult::CONTINUE;
152420 break;
152421 }
152422 default:
152423 throw InternalException("invalid node type for Vacuum: %d", type);
152424 }
152425
152426 const auto idx = Node::GetAllocatorIdx(type);
152427 auto &allocator = Node::GetAllocator(art, type);
152428 const auto needs_vacuum = indexes.find(idx) != indexes.end() && allocator.NeedsVacuum(node);
152429 if (needs_vacuum) {
152430 const auto status = node.GetGateStatus();
152431 node = allocator.VacuumPointer(node);
152432 node.SetMetadata(static_cast<uint8_t>(type));
152433 node.SetGateStatus(status);
152434 }
152435 return result;
152436 };
152437
152438 ARTScanner<ARTScanHandling::EMPLACE, Node> scanner(*this, handler, tree);
152439 scanner.Scan(handler);
152440
152441 // Finalize the vacuum operation.
152442 FinalizeVacuum(indexes);
152443}
static void DeprecatedVacuum(ART &art, Node &node)
Vacuums the linked list of leaves.
Definition duckdb.cpp:154448
static FixedSizeAllocator & GetAllocator(const ART &art, const NType type)
Get a reference to the allocator.
Definition duckdb.cpp:154663
static uint8_t GetAllocatorIdx(const NType type)
Get the index of a node type's allocator.
Definition duckdb.cpp:154667
::uint8_t uint8_t
Here is the call graph for this function:

◆ SerializeToDisk()

IndexStorageInfo duckdb::ART::SerializeToDisk ( QueryContext context,
const case_insensitive_map_t< Value > & options )
overridevirtual

Serializes ART memory to disk and returns the ART storage information.

Reimplemented from duckdb::BoundIndex.

152231 {
152232 lock_guard<mutex> guard(lock);
152233
152234 // If the storage format uses deprecated leaf storage,
152235 // then we need to transform all nested leaves before serialization.
152236 auto v1_0_0_option = options.find("v1_0_0_storage");
152237 bool v1_0_0_storage = v1_0_0_option == options.end() || v1_0_0_option->second != Value(false);
152238 auto info = PrepareSerialize(options, v1_0_0_storage);
152239 auto allocator_count = v1_0_0_storage ? DEPRECATED_ALLOCATOR_COUNT : ALLOCATOR_COUNT;
152240
152241 // Store the data on disk as partial blocks and set the block ids.
152242 WritePartialBlocks(context, v1_0_0_storage);
152243
152244 for (idx_t i = 0; i < allocator_count; i++) {
152245 info.allocator_infos.push_back((*allocators)[i]->GetInfo());
152246 }
152247
152248 return info;
152249}
static constexpr uint8_t DEPRECATED_ALLOCATOR_COUNT
FixedSizeAllocator count of deprecated ARTs.
Definition duckdb.cpp:12140

◆ SerializeToWAL()

IndexStorageInfo duckdb::ART::SerializeToWAL ( const case_insensitive_map_t< Value > & options)
overridevirtual

Serializes ART memory to the WAL and returns the ART storage information.

Reimplemented from duckdb::BoundIndex.

152251 {
152252 // If the storage format uses deprecated leaf storage,
152253 // then we need to transform all nested leaves before serialization.
152254 auto v1_0_0_option = options.find("v1_0_0_storage");
152255 bool v1_0_0_storage = v1_0_0_option == options.end() || v1_0_0_option->second != Value(false);
152256 auto info = PrepareSerialize(options, v1_0_0_storage);
152257 auto allocator_count = v1_0_0_storage ? DEPRECATED_ALLOCATOR_COUNT : ALLOCATOR_COUNT;
152258
152259 // Set the correct allocation sizes and get the map containing all buffers.
152260 for (idx_t i = 0; i < allocator_count; i++) {
152261 info.buffers.push_back((*allocators)[i]->InitSerializationToWAL());
152262 }
152263
152264 for (idx_t i = 0; i < allocator_count; i++) {
152265 info.allocator_infos.push_back((*allocators)[i]->GetInfo());
152266 }
152267
152268 return info;
152269}

◆ GetInMemorySize()

idx_t duckdb::ART::GetInMemorySize ( IndexLock & index_lock)
overridevirtual

Returns the in-memory usage of the ART.

Implements duckdb::BoundIndex.

152331 {
152332 D_ASSERT(owns_data);
152333
152334 idx_t in_memory_size = 0;
152335 for (auto &allocator : *allocators) {
152336 in_memory_size += allocator->GetInMemorySize();
152337 }
152338 return in_memory_size;
152339}

◆ SupportsDeltaIndexes()

bool duckdb::ART::SupportsDeltaIndexes ( ) const
overridevirtual

Whether or not the index supports the creation of delta indexes.

Reimplemented from duckdb::BoundIndex.

152341 {
152342 return true;
152343}

◆ CreateDeltaIndex()

unique_ptr< BoundIndex > duckdb::ART::CreateDeltaIndex ( DeltaIndexType delta_index_type) const
overridevirtual

Creates a delta index - an empty copy of the index with the same schema, etc This will only be called if SupportsDeltaIndexes returns true.

Reimplemented from duckdb::BoundIndex.

152345 {
152346 auto constraint_type = index_constraint_type;
152347 if (target_delta_index == DeltaIndexType::DELETED_ROWS_IN_USE) {
152348 // deleted_rows_in_use allows duplicates regardless of whether or not the main index is a unique index or not
152349 constraint_type = IndexConstraintType::NONE;
152350 }
152351 auto result = make_uniq<ART>(name, constraint_type, GetColumnIds(), table_io_manager, unbound_expressions, db);
152352 result->delta_index_type = target_delta_index;
152353 return std::move(result);
152354}

◆ GenerateKeyVectors()

void duckdb::ART::GenerateKeyVectors ( ArenaAllocator & allocator,
DataChunk & input,
Vector & row_ids,
unsafe_vector< ARTKey > & keys,
unsafe_vector< ARTKey > & row_id_keys )
151649 {
151650 auto key_input = &input;
151651
151652 DataChunk converted_chunk;
151653 // Do we need to convert the input first before generating keys?
151654 if (KeyInputNeedConversion(input.GetTypes(), storage_version)) {
151655 ConvertKeyInput(input, converted_chunk);
151656 key_input = &converted_chunk;
151657 }
151658
151659 GenerateKeys<>(allocator, *key_input, keys);
151660
151661 DataChunk row_id_chunk;
151662 row_id_chunk.Initialize(Allocator::DefaultAllocator(), vector<LogicalType> {LogicalType::ROW_TYPE},
151663 key_input->size());
151664 row_id_chunk.data[0].Reference(row_ids);
151665 row_id_chunk.SetCardinality(key_input->size());
151666 GenerateKeys<>(allocator, row_id_chunk, row_id_keys);
151667}
void GenerateKeys(ArenaAllocator &allocator, DataChunk &input, unsafe_vector< ARTKey > &keys)
ART key generation.
DUCKDB_API vector< LogicalType > GetTypes() const
Returns a list of types of the vectors of this data chunk.
Definition duckdb.cpp:116995
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445

◆ Verify()

void duckdb::ART::Verify ( IndexLock & l)
overridevirtual

Verifies the nodes.

Implements duckdb::BoundIndex.

152610 {
152611 VerifyInternal();
152612}

◆ VerifyAllocations()

void duckdb::ART::VerifyAllocations ( IndexLock & l)
overridevirtual

Verifies that the node allocations match the node counts.

Implements duckdb::BoundIndex.

152620 {
152621 return VerifyAllocationsInternal();
152622}

◆ VerifyBuffers()

void duckdb::ART::VerifyBuffers ( IndexLock & l)
overridevirtual

Verifies the index buffers.

Reimplemented from duckdb::BoundIndex.

152642 {
152643 for (auto &allocator : *allocators) {
152644 allocator->VerifyBuffers();
152645 }
152646}

◆ ToString()

string duckdb::ART::ToString ( IndexLock & l,
bool display_ascii = false )
overridevirtual

Returns string representation of the ART.

Implements duckdb::BoundIndex.

152599 {
152600 return ToStringInternal(display_ascii);
152601}

◆ PrefixCount()

uint8_t duckdb::ART::PrefixCount ( ) const
inline

Returns the configured prefix byte capacity.

12256 {
12257 return prefix_count;
12258 }
Here is the caller graph for this function:

◆ FullScan()

bool duckdb::ART::FullScan ( idx_t max_count,
set< row_t > & row_ids )
private
151882 {
151883 if (!tree.HasMetadata()) {
151884 return true;
151885 }
151886 Iterator it(*this);
151887 it.FindMinimum(tree);
151888 ARTKey empty_key = ARTKey();
151889 RowIdSetOutput output(row_ids, max_count);
151890 return it.Scan(empty_key, output, false) == ARTScanResult::COMPLETED;
151891}

◆ SearchEqual()

bool duckdb::ART::SearchEqual ( ARTKey & key,
idx_t max_count,
set< row_t > & row_ids )
private
151893 {
151894 auto leaf = ARTOperator::Lookup(*this, tree, key, 0);
151895 if (!leaf) {
151896 return true;
151897 }
151898
151899 Iterator it(*this);
151900 it.FindMinimum(*leaf);
151901 ARTKey empty_key = ARTKey();
151902 RowIdSetOutput output(row_ids, max_count);
151903 return it.Scan(empty_key, output, false) == ARTScanResult::COMPLETED;
151904}

◆ SearchGreater()

bool duckdb::ART::SearchGreater ( ARTKey & key,
bool equal,
idx_t max_count,
set< row_t > & row_ids )
private
151906 {
151907 if (!tree.HasMetadata()) {
151908 return true;
151909 }
151910
151911 // Find the lowest value that satisfies the predicate.
151912 Iterator it(*this);
151913
151914 // Early-out, if the maximum value in the ART is lower than the lower bound.
151915 if (!it.LowerBound(tree, key, equal)) {
151916 return true;
151917 }
151918
151919 // We continue the scan. We do not check the bounds as any value following this value is
151920 // greater and satisfies our predicate.
151921 RowIdSetOutput output(row_ids, max_count);
151922 return it.Scan(ARTKey(), output, false) == ARTScanResult::COMPLETED;
151923}

◆ SearchLess()

bool duckdb::ART::SearchLess ( ARTKey & upper_bound,
bool equal,
idx_t max_count,
set< row_t > & row_ids )
private
151925 {
151926 if (!tree.HasMetadata()) {
151927 return true;
151928 }
151929
151930 // Find the minimum value in the ART: we start scanning from this value.
151931 Iterator it(*this);
151932 it.FindMinimum(tree);
151933
151934 // Early-out, if the minimum value is higher than the upper bound.
151935 if (it.current_key.GreaterThan(upper_bound, equal, it.GetNestedDepth())) {
151936 return true;
151937 }
151938
151939 // Continue the scan until we reach the upper bound.
151940 RowIdSetOutput output(row_ids, max_count);
151941 return it.Scan(upper_bound, output, equal) == ARTScanResult::COMPLETED;
151942}

◆ SearchCloseRange()

bool duckdb::ART::SearchCloseRange ( ARTKey & lower_bound,
ARTKey & upper_bound,
bool left_equal,
bool right_equal,
idx_t max_count,
set< row_t > & row_ids )
private
151945 {
151946 // Find the first node that satisfies the left predicate.
151947 Iterator it(*this);
151948
151949 // Early-out, if the maximum value in the ART is lower than the lower bound.
151950 if (!it.LowerBound(tree, lower_bound, left_equal)) {
151951 return true;
151952 }
151953
151954 // Continue the scan until we reach the upper bound.
151955 RowIdSetOutput output(row_ids, max_count);
151956 return it.Scan(upper_bound, output, right_equal) == ARTScanResult::COMPLETED;
151957}

◆ GenerateErrorKeyName()

string duckdb::ART::GenerateErrorKeyName ( DataChunk & input,
idx_t row )
private
152004 {
152005 DataChunk expr_chunk;
152006 expr_chunk.Initialize(Allocator::DefaultAllocator(), logical_types);
152007 ExecuteExpressions(input, expr_chunk);
152008
152009 string key_name;
152010 for (idx_t k = 0; k < expr_chunk.ColumnCount(); k++) {
152011 if (k > 0) {
152012 key_name += ", ";
152013 }
152014 key_name += unbound_expressions[k]->GetName() + ": " + expr_chunk.data[k].GetValue(row_idx).ToString();
152015 }
152016 return key_name;
152017}

◆ GenerateConstraintErrorMessage()

string duckdb::ART::GenerateConstraintErrorMessage ( VerifyExistenceType verify_type,
const string & key_name )
private
152019 {
152020 switch (verify_type) {
152021 case VerifyExistenceType::APPEND: {
152022 // APPEND to PK/UNIQUE table, but node/key already exists in PK/UNIQUE table.
152023 string type = IsPrimary() ? "primary key" : "unique";
152024 return StringUtil::Format("Duplicate key \"%s\" violates %s constraint.", key_name, type);
152025 }
152026 case VerifyExistenceType::APPEND_FK: {
152027 // APPEND_FK to FK table, node/key does not exist in PK/UNIQUE table.
152028 return StringUtil::Format(
152029 "Violates foreign key constraint because key \"%s\" does not exist in the referenced table", key_name);
152030 }
152031 case VerifyExistenceType::DELETE_FK: {
152032 // DELETE_FK that still exists in a FK table, i.e., not a valid delete.
152033 return StringUtil::Format(
152034 "Violates foreign key constraint because key \"%s\" is still referenced by a foreign "
152035 "key in a different table. If this is an unexpected constraint violation, please refer to our "
152036 "foreign key limitations in the documentation",
152037 key_name);
152038 }
152039 default:
152040 throw NotImplementedException("Type not implemented for VerifyExistenceType");
152041 }
152042}
bool IsPrimary() const
Returns primary key flag.
Definition duckdb.hpp:49710
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002

◆ VerifyLeaf()

void duckdb::ART::VerifyLeaf ( const Node & leaf,
const ARTKey & key,
DeleteIndexInfo delete_index_info,
ConflictManager & manager,
optional_idx & conflict_idx,
idx_t i )
private
152045 {
152046 // Get the set of deleted row ids for this value if we have any delete indexes
152047 vector<row_t> deleted_row_ids;
152048 if (delete_index_info.delete_indexes) {
152049 for (auto &index : *delete_index_info.delete_indexes) {
152050 auto &delete_art = index.get().Cast<ART>();
152051 auto deleted_leaf = ARTOperator::Lookup(delete_art, delete_art.tree, key, 0);
152052 if (!deleted_leaf) {
152053 continue;
152054 }
152055 // All leaves in the delete ART are inlined.
152056 if (deleted_leaf->GetType() != NType::LEAF_INLINED) {
152057 throw InternalException("Non-inlined leaf?");
152058 }
152059 auto deleted_row_id = deleted_leaf->GetRowId();
152060 deleted_row_ids.push_back(deleted_row_id);
152061 }
152062 }
152063
152064 if (leaf.GetType() == NType::LEAF_INLINED) {
152065 auto this_row_id = leaf.GetRowId();
152066 if (!deleted_row_ids.empty()) {
152067 // The leaf is inlined, and the same key exists in the delete ART.
152068 // check if the row-id matches - if it does there is no conflict
152069 for (auto &deleted_row_id : deleted_row_ids) {
152070 if (deleted_row_id == this_row_id) {
152071 return;
152072 }
152073 }
152074 }
152075
152076 if (manager.AddHit(i, this_row_id)) {
152077 conflict_idx = i;
152078 }
152079 return;
152080 }
152081
152082 // Fast path for FOREIGN KEY constraints.
152083 // Up to here, the above code paths work implicitly for FKs, as the leaf is inlined.
152084 // FIXME: proper foreign key + delete ART support.
152085 if (index_constraint_type == IndexConstraintType::FOREIGN) {
152086 D_ASSERT(deleted_row_ids.empty());
152087 // We don't handle FK conflicts in UPSERT, so the row ID should not matter.
152088 if (manager.AddHit(i, MAX_ROW_ID)) {
152089 conflict_idx = i;
152090 }
152091 return;
152092 }
152093
152094 // Scan the two row IDs in the leaf.
152095 Iterator it(*this);
152096 it.FindMinimum(leaf);
152097 ARTKey empty_key = ARTKey();
152098 set<row_t> row_ids;
152099 RowIdSetOutput output(row_ids, 2);
152100 auto result = it.Scan(empty_key, output, false);
152101 if (result != ARTScanResult::COMPLETED || row_ids.size() != 2) {
152102 throw InternalException("VerifyLeaf expects exactly two row IDs to be scanned");
152103 }
152104
152105 if (!deleted_row_ids.empty()) {
152106 for (const auto row_id : row_ids) {
152107 for (auto deleted_row_id : deleted_row_ids) {
152108 if (deleted_row_id == row_id) {
152109 return;
152110 }
152111 }
152112 }
152113 }
152114
152115 auto row_id_it = row_ids.begin();
152116 if (manager.AddHit(i, *row_id_it)) {
152117 conflict_idx = i;
152118 }
152119 row_id_it++;
152120 manager.AddSecondHit(i, *row_id_it);
152121}
index
const row_t MAX_ROW_ID
The maximum row identifier used in tables.
Definition duckdb.cpp:50301

◆ VerifyConstraint()

void duckdb::ART::VerifyConstraint ( DataChunk & chunk,
IndexAppendInfo & info,
ConflictManager & manager )
overrideprivatevirtual

Verifies the constraint for a chunk of data.

Reimplemented from duckdb::BoundIndex.

152123 {
152124 // Lock the index during constraint checking.
152125 lock_guard<mutex> l(lock);
152126
152127 DataChunk expr_chunk;
152128 expr_chunk.Initialize(Allocator::DefaultAllocator(), logical_types);
152129 ExecuteExpressions(chunk, expr_chunk);
152130
152131 ArenaAllocator arena_allocator(BufferAllocator::Get(db));
152132 unsafe_vector<ARTKey> keys(expr_chunk.size());
152133 GenerateKeys<>(arena_allocator, expr_chunk, keys);
152134
152135 optional_idx conflict_idx;
152136 for (idx_t i = 0; !conflict_idx.IsValid() && i < chunk.size(); i++) {
152137 if (keys[i].Empty()) {
152138 if (manager.AddNull(i)) {
152139 conflict_idx = i;
152140 }
152141 continue;
152142 }
152143
152144 auto leaf = ARTOperator::Lookup(*this, tree, keys[i], 0);
152145 if (!leaf) {
152146 continue;
152147 }
152148 VerifyLeaf(*leaf, keys[i], DeleteIndexInfo(info.delete_indexes), manager, conflict_idx, i);
152149 }
152150
152151 manager.FinishLookup();
152152 if (!conflict_idx.IsValid()) {
152153 return;
152154 }
152155
152156 auto key_name = GenerateErrorKeyName(chunk, conflict_idx.GetIndex());
152157 auto exception_msg = GenerateConstraintErrorMessage(manager.GetVerifyExistenceType(), key_name);
152158 throw ConstraintException(exception_msg);
152159}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetConstraintViolationMessage()

string duckdb::ART::GetConstraintViolationMessage ( VerifyExistenceType verify_type,
idx_t failed_index,
DataChunk & input )
overrideprivatevirtual

Throw a constraint violation exception.

Implements duckdb::BoundIndex.

152161 {
152162 lock_guard<mutex> l(lock);
152163 auto key_name = GenerateErrorKeyName(input, failed_index);
152164 auto exception_msg = GenerateConstraintErrorMessage(verify_type, key_name);
152165 return exception_msg;
152166}

◆ InitializeMergeUpperBounds()

void duckdb::ART::InitializeMergeUpperBounds ( unsafe_vector< idx_t > & upper_bounds)
private
152449 {
152450 D_ASSERT(owns_data);
152451 for (auto &allocator : *allocators) {
152452 upper_bounds.emplace_back(allocator->GetUpperBoundBufferId());
152453 }
152454}

◆ InitializeMerge()

void duckdb::ART::InitializeMerge ( Node & node,
unsafe_vector< idx_t > & upper_bounds )
private
152456 {
152457 D_ASSERT(node.HasMetadata());
152458
152459 auto handler = [&upper_bounds](Node &node) {
152460 const auto type = node.GetType();
152461 if (node.GetType() == NType::LEAF_INLINED) {
152462 return ARTHandlingResult::NONE;
152463 }
152464 if (type == NType::LEAF) {
152465 throw InternalException("deprecated ART storage in InitializeMerge");
152466 }
152467 const auto idx = Node::GetAllocatorIdx(type);
152468 node.IncreaseBufferId(upper_bounds[idx]);
152469 return ARTHandlingResult::NONE;
152470 };
152471
152472 ARTScanner<ARTScanHandling::POP, Node> scanner(*this, handler, node);
152473 scanner.Scan(handler);
152474}

◆ InitializeVacuum()

void duckdb::ART::InitializeVacuum ( unordered_set< uint8_t > & indexes)
private
152360 {
152361 for (idx_t i = 0; i < allocators->size(); i++) {
152362 if ((*allocators)[i]->InitializeVacuum()) {
152363 indexes.insert(NumericCast<uint8_t>(i));
152364 }
152365 }
152366}

◆ FinalizeVacuum()

void duckdb::ART::FinalizeVacuum ( const unordered_set< uint8_t > & indexes)
private
152368 {
152369 for (const auto &idx : indexes) {
152370 (*allocators)[idx]->FinalizeVacuum();
152371 }
152372}

◆ InitAllocators()

void duckdb::ART::InitAllocators ( const IndexStorageInfo & info)
private
152282 {
152283 for (idx_t i = 0; i < info.allocator_infos.size(); i++) {
152284 (*allocators)[i]->Init(info.allocator_infos[i]);
152285 }
152286}

◆ TransformToDeprecated()

void duckdb::ART::TransformToDeprecated ( )
private
152172 {
152173 auto idx = Node::GetAllocatorIdx(NType::PREFIX);
152174 auto &block_manager = (*allocators)[idx]->block_manager;
152175 unsafe_unique_ptr<FixedSizeAllocator> deprecated_allocator = nullptr;
152176 if (prefix_count != Prefix::DEPRECATED_COUNT) {
152177 auto prefix_size = NumericCast<idx_t>(Prefix::DEPRECATED_COUNT) + NumericCast<idx_t>(Prefix::METADATA_SIZE);
152178 deprecated_allocator = make_unsafe_uniq<FixedSizeAllocator>(prefix_size, block_manager);
152179 }
152180
152181 unique_ptr<TransformToDeprecatedState> state =
152182 make_uniq<TransformToDeprecatedState>(std::move(deprecated_allocator));
152183
152184 // Transform all leaves, and possibly the prefixes.
152185 if (tree.HasMetadata()) {
152186 Node::TransformToDeprecated(*this, tree, *state);
152187 }
152188
152189 // Replace the prefix allocator with the deprecated allocator.
152190 if (state->HasAllocator()) {
152191 deprecated_allocator = state->TakeAllocator();
152192 prefix_count = Prefix::DEPRECATED_COUNT;
152193
152194 D_ASSERT((*allocators)[idx]->Empty());
152195 (*allocators)[idx]->Reset();
152196 (*allocators)[idx] = std::move(deprecated_allocator);
152197 }
152198}
static void TransformToDeprecated(ART &art, Node &node, TransformToDeprecatedState &state)
Transform the node storage to deprecated storage.
Definition duckdb.cpp:154939

◆ PrepareSerialize()

IndexStorageInfo duckdb::ART::PrepareSerialize ( const case_insensitive_map_t< Value > & options,
const bool v1_0_0_storage )
private
152200 {
152201 if (v1_0_0_storage) {
152202 TransformToDeprecated();
152203 }
152204
152205 IndexStorageInfo info(name);
152206 info.root = tree.Get();
152207 info.options = options;
152208
152209 // It never hurts to serialize the storage version, even to older formats
152210 if (storage_version.IsValid()) {
152211 info.options["storage_version"] = Value::UBIGINT(storage_version.GetIndex());
152212 }
152213
152214 for (auto &allocator : *allocators) {
152215 allocator->RemoveEmptyBuffers();
152216 }
152217
152218#ifdef DEBUG
152219 if (v1_0_0_storage) {
152220 D_ASSERT((*allocators)[Node::GetAllocatorIdx(NType::NODE_7_LEAF)]->Empty());
152221 D_ASSERT((*allocators)[Node::GetAllocatorIdx(NType::NODE_15_LEAF)]->Empty());
152222 D_ASSERT((*allocators)[Node::GetAllocatorIdx(NType::NODE_256_LEAF)]->Empty());
152223 D_ASSERT((*allocators)[Node::GetAllocatorIdx(NType::PREFIX)]->GetSegmentSize() ==
152224 Prefix::DEPRECATED_COUNT + Prefix::METADATA_SIZE);
152225 }
152226#endif
152227
152228 return info;
152229}
static DUCKDB_API Value UBIGINT(uint64_t value)
Create an unsigned bigint Value from a specified value.
Definition duckdb.cpp:132202

◆ Deserialize()

void duckdb::ART::Deserialize ( const BlockPointer & pointer)
private
152288 {
152289 D_ASSERT(pointer.IsValid());
152290
152291 auto &metadata_manager = table_io_manager.GetMetadataManager();
152292 MetadataReader reader(metadata_manager, pointer);
152293 tree = reader.Read<Node>();
152294
152295 for (idx_t i = 0; i < DEPRECATED_ALLOCATOR_COUNT; i++) {
152296 (*allocators)[i]->Deserialize(metadata_manager, reader.Read<BlockPointer>());
152297 }
152298}

◆ WritePartialBlocks()

void duckdb::ART::WritePartialBlocks ( QueryContext context,
const bool v1_0_0_storage )
private
152271 {
152272 auto &block_manager = table_io_manager.GetIndexBlockManager();
152273 PartialBlockManager partial_block_manager(context, block_manager, PartialBlockType::FULL_CHECKPOINT);
152274
152275 idx_t allocator_count = v1_0_0_storage ? DEPRECATED_ALLOCATOR_COUNT : ALLOCATOR_COUNT;
152276 for (idx_t i = 0; i < allocator_count; i++) {
152277 (*allocators)[i]->SerializeBuffers(partial_block_manager);
152278 }
152279 partial_block_manager.FlushPartialBlocks();
152280}

◆ SetPrefixCount()

void duckdb::ART::SetPrefixCount ( const IndexStorageInfo & info)
private
152300 {
152301 if (info.IsValid() && info.root_block_ptr.IsValid()) {
152302 prefix_count = Prefix::DEPRECATED_COUNT;
152303 return;
152304 }
152305
152306 if (info.IsValid()) {
152307 auto serialized_count = info.allocator_infos[0].segment_size - Prefix::METADATA_SIZE;
152308 prefix_count = NumericCast<uint8_t>(serialized_count);
152309 return;
152310 }
152311
152312 idx_t compound_size = 0;
152313 for (const auto &type : types) {
152314 compound_size += GetTypeIdSize(type);
152315 }
152316
152317 // Get the maximum possible prefix size.
152318 // Minus one to index the prefix count (last byte).
152319 auto numeric_max = NumericLimits<uint8_t>().Maximum();
152320 uint8_t max_aligned = AlignValueFloor<uint8_t>(numeric_max - Prefix::METADATA_SIZE) - 1;
152321
152322 // Ceiling of compound size,
152323 // minus one to index the prefix count (last byte).
152324 idx_t key_aligned = AlignValue(compound_size) - 1;
152325
152326 // Set the prefix size to the maximum of the (compound) key size and the maximum prefix size.
152327 bool exceeds_max = key_aligned > NumericCast<idx_t>(max_aligned);
152328 prefix_count = exceeds_max ? max_aligned : NumericCast<uint8_t>(key_aligned);
152329}
static T AlignValue(T n)
Align value (ceiling) (not for pointer types).
Definition duckdb.hpp:2126

◆ ToStringInternal()

string duckdb::ART::ToStringInternal ( bool display_ascii)
private
152603 {
152604 if (tree.HasMetadata()) {
152605 return "\nART: \n" + tree.ToString(*this, ToStringOptions(0, false, display_ascii, nullptr, 0, 0, true, false));
152606 }
152607 return "[empty]";
152608}

◆ VerifyInternal()

void duckdb::ART::VerifyInternal ( )
private
152614 {
152615 if (tree.HasMetadata()) {
152616 tree.Verify(*this);
152617 }
152618}

◆ VerifyAllocationsInternal()

void duckdb::ART::VerifyAllocationsInternal ( )
private
152624 {
152625#ifdef DEBUG
152626 unordered_map<uint8_t, idx_t> node_counts;
152627 for (idx_t i = 0; i < allocators->size(); i++) {
152628 node_counts[NumericCast<uint8_t>(i)] = 0;
152629 }
152630
152631 if (tree.HasMetadata()) {
152632 tree.VerifyAllocations(*this, node_counts);
152633 }
152634
152635 for (idx_t i = 0; i < allocators->size(); i++) {
152636 auto segment_count = (*allocators)[i]->GetSegmentCount();
152637 D_ASSERT(segment_count == node_counts[NumericCast<uint8_t>(i)]);
152638 }
152639#endif
152640}

◆ GenerateKeys() [1/2]

template<>
void duckdb::ART::GenerateKeys ( ArenaAllocator & allocator,
DataChunk & input,
unsafe_vector< ARTKey > & keys )
151598 {
151599 GenerateKeysInternal<false>(allocator, input, keys);
151600}

◆ GenerateKeys() [2/2]

template<>
void duckdb::ART::GenerateKeys ( ArenaAllocator & allocator,
DataChunk & input,
unsafe_vector< ARTKey > & keys )
151603 {
151604 GenerateKeysInternal<true>(allocator, input, keys);
151605}

The documentation for this class was generated from the following file: