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::RowGroupCollection Class Reference
Collaboration diagram for duckdb::RowGroupCollection:

Public Member Functions

 RowGroupCollection (shared_ptr< DataTableInfo > info, TableIOManager &io_manager, vector< LogicalType > types, idx_t row_start, idx_t total_rows=0)
 RowGroupCollection (shared_ptr< DataTableInfo > info, BlockManager &block_manager, vector< LogicalType > types, idx_t row_start, idx_t total_rows, idx_t row_group_size)
idx_t GetTotalRows () const
idx_t GetRowGroupCount () const
Allocator & GetAllocator () const
void Initialize (PersistentCollectionData &data)
void Initialize (PersistentTableData &data)
void InitializeEmpty ()
void FinalizeCheckpoint (MetaBlockPointer pointer, const vector< MetaBlockPointer > &existing_pointers)
bool IsEmpty () const
void AppendRowGroup (SegmentLock &l, idx_t start_row)
optional_ptr< RowGroup > GetRowGroup (int64_t index)
 Get the nth row-group, negative numbers start from the back (so -1 is the last row group, etc).
void SetRowGroup (int64_t index, shared_ptr< RowGroup > new_row_group)
 Overrides a row group - should only be used if you know what you're doing (will likely be removed in the future).
void Verify ()
void Destroy ()
void InitializeScan (const QueryContext &context, CollectionScanState &state, const vector< StorageIndex > &column_ids, optional_ptr< TableFilterSet > table_filters)
void InitializeCreateIndexScan (CreateIndexScanState &state)
void InitializeScanWithOffset (const QueryContext &context, CollectionScanState &state, const vector< StorageIndex > &column_ids, idx_t start_row, idx_t end_row)
void InitializeParallelScan (ParallelCollectionScanState &state)
bool NextParallelScan (ClientContext &context, ParallelCollectionScanState &state, CollectionScanState &scan_state)
RowGroupIterationHelper Chunks (DuckTransaction &transaction)
RowGroupIterationHelper Chunks (DuckTransaction &transaction, const vector< StorageIndex > &column_ids)
void Fetch (TransactionData transaction, DataChunk &result, const vector< StorageIndex > &column_ids, const Vector &row_identifiers, idx_t fetch_count, ColumnFetchState &state)
bool CanFetch (TransactionData, const row_t row_id)
 Returns true, if the row group can fetch the row id for the transaction.
void InitializeAppend (TableAppendState &state)
 Initialize an append of a variable number of rows. FinalizeAppend must be called after appending is done.
void InitializeAppend (TransactionData transaction, TableAppendState &state)
 Initialize an append with a variable number of rows. FinalizeAppend should not be called after appending is done.
bool Append (DataChunk &chunk, TableAppendState &state)
 Appends to the row group collection. Returns true if a new row group has been created to append to.
void FinalizeAppend (TransactionData transaction, TableAppendState &state)
 FinalizeAppend flushes an append with a variable number of rows.
void CommitAppend (transaction_t commit_id, idx_t row_start, idx_t count)
void RevertAppendInternal (idx_t start_row)
void CleanupAppend (transaction_t lowest_transaction, idx_t start, idx_t count)
void MergeStorage (RowGroupCollection &data, optional_ptr< DataTable > table, optional_ptr< StorageCommitState > commit_state)
bool IsPersistent () const
void RemoveFromIndexes (const QueryContext &context, TableIndexList &indexes, Vector &row_identifiers, idx_t count, IndexRemovalType removal_type, optional_idx active_checkpoint=optional_idx())
idx_t Delete (TransactionData transaction, DataTable &table, row_t *ids, idx_t count)
void Update (TransactionData transaction, DataTable &table, row_t *ids, const vector< PhysicalIndex > &column_ids, DataChunk &updates)
void UpdateColumn (TransactionData transaction, DataTable &table, Vector &row_ids, const vector< column_t > &column_path, DataChunk &updates)
void Checkpoint (TableDataWriter &writer, TableStatistics &global_stats)
void InitializeVacuumState (CollectionCheckpointState &checkpoint_state, VacuumState &state, optional_idx checkpoint_row_group_count)
bool ScheduleVacuumTasks (CollectionCheckpointState &checkpoint_state, VacuumState &state, idx_t segment_idx, bool schedule_vacuum)
unique_ptr< CheckpointTask > GetCheckpointTask (CollectionCheckpointState &checkpoint_state, idx_t segment_idx)
void CommitDropColumn (const idx_t column_index)
void CommitDropTable ()
vector< PartitionStatistics > GetPartitionStats () const
vector< ColumnSegmentInfo > GetColumnSegmentInfo (const QueryContext &context)
const vector< LogicalType > & GetTypes () const
shared_ptr< RowGroupCollection > AddColumn (ClientContext &context, ColumnDefinition &new_column, ExpressionExecutor &default_executor)
shared_ptr< RowGroupCollection > RemoveColumn (idx_t col_idx)
shared_ptr< RowGroupCollection > AlterType (ClientContext &context, idx_t changed_idx, const LogicalType &target_type, vector< StorageIndex > bound_columns, Expression &cast_expr)
void VerifyNewConstraint (const QueryContext &context, DataTable &parent, const BoundConstraint &constraint)
void SetStats (TableStatistics &new_stats)
void CopyStats (TableStatistics &stats)
unique_ptr< BaseStatistics > CopyStats (const StorageIndex &column_id)
unique_ptr< BlockingSample > GetSample ()
void SetDistinct (column_t column_id, unique_ptr< DistinctStatistics > distinct_stats)
AttachedDatabase & GetAttached ()
BlockManager & GetBlockManager ()
MetadataManager & GetMetadataManager ()
DataTableInfo & GetTableInfo ()
idx_t GetAllocationSize () const
idx_t GetRowGroupSize () const
void SetAppendRequiresNewRowGroup ()
idx_t GetSegmentCount ()
 Returns the total amount of segments - use sparingly, as this forces all segments to be loaded.

Static Public Member Functions

static bool InitializeScanInRowGroup (ClientContext &context, CollectionScanState &state, RowGroupCollection &collection, SegmentNode< RowGroup > &row_group, idx_t vector_index, idx_t max_row)

Private Member Functions

optional_ptr< SegmentNode< RowGroup > > NextUpdateRowGroup (RowGroupSegmentTree &row_groups, row_t *ids, idx_t &pos, idx_t count) const
shared_ptr< RowGroupSegmentTree > GetRowGroups () const
void SetRowGroups (shared_ptr< RowGroupSegmentTree > row_groups)

Private Attributes

BlockManager & block_manager
 BlockManager.
const idx_t row_group_size
 The row group size of the row group collection.
atomic< idx_t > total_rows
 The number of rows in the table.
shared_ptr< DataTableInfo > info
 The data table info.
vector< LogicalType > types
 The column types of the row group collection.
mutex row_group_pointer_lock
 Lock held when accessing or modifying the owned_row_groups pointer.
shared_ptr< RowGroupSegmentTree > owned_row_groups
 The owning pointer of the segment tree.
TableStatistics stats
 Table statistics.
atomic< idx_t > allocation_size
 Allocation size, only tracked for appends.
MetaBlockPointer metadata_pointer
 Root metadata pointer, if the collection is loaded from disk.
vector< MetaBlockPointer > metadata_pointers
 Other metadata pointers.
bool requires_new_row_group
 Whether or not we need to append a new row group prior to appending.

Constructor & Destructor Documentation

◆ RowGroupCollection() [1/2]

duckdb::RowGroupCollection::RowGroupCollection ( shared_ptr< DataTableInfo > info,
TableIOManager & io_manager,
vector< LogicalType > types,
idx_t row_start,
idx_t total_rows = 0 )
434543 : RowGroupCollection(std::move(info_p), io_manager.GetBlockManagerForRowData(), std::move(types_p), row_start,
434544 total_rows, io_manager.GetRowGroupSize()) {
434545}
atomic< idx_t > total_rows
The number of rows in the table.
Definition duckdb.hpp:50620

◆ RowGroupCollection() [2/2]

duckdb::RowGroupCollection::RowGroupCollection ( shared_ptr< DataTableInfo > info,
BlockManager & block_manager,
vector< LogicalType > types,
idx_t row_start,
idx_t total_rows,
idx_t row_group_size )
434550 : block_manager(block_manager), row_group_size(row_group_size_p), total_rows(total_rows_p), info(std::move(info_p)),
434551 types(std::move(types_p)), owned_row_groups(make_shared_ptr<RowGroupSegmentTree>(*this, row_start)),
434553}
bool requires_new_row_group
Whether or not we need to append a new row group prior to appending.
Definition duckdb.hpp:50638
shared_ptr< DataTableInfo > info
The data table info.
Definition duckdb.hpp:50622
atomic< idx_t > allocation_size
Allocation size, only tracked for appends.
Definition duckdb.hpp:50632
vector< LogicalType > types
The column types of the row group collection.
Definition duckdb.hpp:50624
shared_ptr< RowGroupSegmentTree > owned_row_groups
The owning pointer of the segment tree.
Definition duckdb.hpp:50628
BlockManager & block_manager
BlockManager.
Definition duckdb.hpp:50616
const idx_t row_group_size
The row group size of the row group collection.
Definition duckdb.hpp:50618

Member Function Documentation

◆ GetTotalRows()

idx_t duckdb::RowGroupCollection::GetTotalRows ( ) const
434555 {
434556 return total_rows.load();
434557}

◆ GetRowGroupCount()

idx_t duckdb::RowGroupCollection::GetRowGroupCount ( ) const
434559 {
434560 auto row_groups = GetRowGroups();
434561 return row_groups->GetSegmentCount();
434562}

◆ GetAllocator()

Allocator & duckdb::RowGroupCollection::GetAllocator ( ) const
434568 {
434569 return Allocator::Get(info->GetDB());
434570}

◆ Initialize() [1/2]

void duckdb::RowGroupCollection::Initialize ( PersistentCollectionData & data)
434609 {
434610 stats.InitializeEmpty(types);
434611 auto l = owned_row_groups->Lock();
434612 for (auto &row_group_data : data.row_group_data) {
434613 auto row_group = make_uniq<RowGroup>(*this, row_group_data);
434614 row_group->MergeIntoStatistics(stats);
434615 total_rows += row_group->count;
434616 owned_row_groups->AppendSegment(l, std::move(row_group), row_group_data.start);
434617 }
434618}
TableStatistics stats
Table statistics.
Definition duckdb.hpp:50630

◆ Initialize() [2/2]

void duckdb::RowGroupCollection::Initialize ( PersistentTableData & data)
434593 {
434594 D_ASSERT(owned_row_groups->GetBaseRowId() == 0);
434595 auto l = owned_row_groups->Lock();
434596 this->total_rows = data.total_rows;
434597 metadata_pointer = data.base_table_pointer;
434598 metadata_pointers = data.read_metadata_pointers;
434599 owned_row_groups->Initialize(data, metadata_pointers);
434600 stats.Initialize(types, data);
434601}
vector< MetaBlockPointer > metadata_pointers
Other metadata pointers.
Definition duckdb.hpp:50636
MetaBlockPointer metadata_pointer
Root metadata pointer, if the collection is loaded from disk.
Definition duckdb.hpp:50634

◆ InitializeEmpty()

void duckdb::RowGroupCollection::InitializeEmpty ( )
434624 {
434625 stats.InitializeEmpty(types);
434626}

◆ FinalizeCheckpoint()

void duckdb::RowGroupCollection::FinalizeCheckpoint ( MetaBlockPointer pointer,
const vector< MetaBlockPointer > & existing_pointers )
434604 {
434605 metadata_pointer = pointer;
434606 metadata_pointers = existing_pointers;
434607}

◆ IsEmpty()

bool duckdb::RowGroupCollection::IsEmpty ( ) const
434941 {
434942 auto row_groups = GetRowGroups();
434943 auto l = row_groups->Lock();
434944 return row_groups->IsEmpty(l);
434945}

◆ AppendRowGroup()

void duckdb::RowGroupCollection::AppendRowGroup ( SegmentLock & l,
idx_t start_row )
434638 {
434639 auto new_row_group = make_uniq<RowGroup>(*this, 0U);
434640 new_row_group->InitializeEmpty(types, GetColumnDataType(start_row));
434641 owned_row_groups->AppendSegment(l, std::move(new_row_group), start_row);
434642 requires_new_row_group = false;
434643}

◆ GetRowGroup()

optional_ptr< RowGroup > duckdb::RowGroupCollection::GetRowGroup ( int64_t index)

Get the nth row-group, negative numbers start from the back (so -1 is the last row group, etc).

434645 {
434646 auto result = owned_row_groups->GetSegmentByIndex(index);
434647 if (!result) {
434648 return nullptr;
434649 }
434650 return result->GetNode();
434651}

◆ SetRowGroup()

void duckdb::RowGroupCollection::SetRowGroup ( int64_t index,
shared_ptr< RowGroup > new_row_group )

Overrides a row group - should only be used if you know what you're doing (will likely be removed in the future).

434658 {
434659 auto result = owned_row_groups->GetSegmentByIndex(index);
434660 if (!result) {
434661 throw InternalException("RowGroupCollection::SetRowGroup - Segment is out of range");
434662 }
434663 result->SetNode(std::move(new_row_group));
434664}

◆ Verify()

void duckdb::RowGroupCollection::Verify ( )
434666 {
434667#ifdef DEBUG
434668 idx_t current_total_rows = 0;
434669 auto row_groups = GetRowGroups();
434670 row_groups->Verify();
434671 for (auto &entry : row_groups->SegmentNodes()) {
434672 auto &row_group = entry.GetNode();
434673 row_group.Verify();
434674 D_ASSERT(&row_group.GetCollection() == this);
434675 D_ASSERT(entry.GetRowStart() == row_groups->GetBaseRowId() + current_total_rows);
434676 current_total_rows += row_group.count;
434677 }
434678 D_ASSERT(current_total_rows == total_rows.load());
434679#endif
434680}
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ Destroy()

void duckdb::RowGroupCollection::Destroy ( )
436281 {
436282 auto l = owned_row_groups->Lock();
436283 auto &segments = owned_row_groups->ReferenceLoadedSegmentsMutable(l);
436284
436285 TaskExecutor executor(TaskScheduler::GetScheduler(GetAttached().GetDatabase()));
436286 for (auto &segment : segments) {
436287 auto destroy_task = make_uniq<DestroyTask>(executor, segment->MoveNode());
436288 executor.ScheduleTask(std::move(destroy_task));
436289 }
436290 executor.WorkOnTasks();
436291}

◆ InitializeScan()

void duckdb::RowGroupCollection::InitializeScan ( const QueryContext & context,
CollectionScanState & state,
const vector< StorageIndex > & column_ids,
optional_ptr< TableFilterSet > table_filters )
434687 {
434688 state.row_groups = GetRowGroups();
434689 auto row_group = state.GetRootSegment();
434690 D_ASSERT(row_group);
434691 state.max_row = state.row_groups->GetBaseRowId() + total_rows;
434692 state.Initialize(context, GetTypes());
434693 while (row_group && !row_group->GetNode().InitializeScan(state, *row_group)) {
434694 row_group = state.GetNextRowGroup(*row_group);
434695 }
434696}

◆ InitializeCreateIndexScan()

void duckdb::RowGroupCollection::InitializeCreateIndexScan ( CreateIndexScanState & state)
434698 {
434699 state.row_groups = GetRowGroups();
434700 state.segment_lock = state.row_groups->Lock();
434701}

◆ InitializeScanWithOffset()

void duckdb::RowGroupCollection::InitializeScanWithOffset ( const QueryContext & context,
CollectionScanState & state,
const vector< StorageIndex > & column_ids,
idx_t start_row,
idx_t end_row )
434705 {
434706 state.row_groups = GetRowGroups();
434707 auto row_group = state.row_groups->GetSegment(start_row);
434708 D_ASSERT(row_group);
434709 state.max_row = end_row;
434710 state.Initialize(context, GetTypes());
434711 idx_t start_vector = (start_row - row_group->GetRowStart()) / STANDARD_VECTOR_SIZE;
434712 if (!row_group->GetNode().InitializeScanWithOffset(state, *row_group, start_vector)) {
434713 throw InternalException("Failed to initialize row group scan with offset");
434714 }
434715}

◆ InitializeScanInRowGroup()

bool duckdb::RowGroupCollection::InitializeScanInRowGroup ( ClientContext & context,
CollectionScanState & state,
RowGroupCollection & collection,
SegmentNode< RowGroup > & row_group,
idx_t vector_index,
idx_t max_row )
static
434719 {
434720 state.max_row = max_row;
434721 state.row_groups = collection.GetRowGroups();
434722 if (state.column_scans.empty()) {
434723 // initialize the scan state
434724 state.Initialize(context, collection.GetTypes());
434725 }
434726 return row_group.GetNode().InitializeScanWithOffset(state, row_group, vector_index);
434727}

◆ InitializeParallelScan()

void duckdb::RowGroupCollection::InitializeParallelScan ( ParallelCollectionScanState & state)
434729 {
434730 state.collection = this;
434731 state.row_groups = GetRowGroups();
434732 state.current_row_group = state.GetRootSegment(*state.row_groups);
434733 state.vector_index = 0;
434734 state.max_row = state.row_groups->GetBaseRowId() + total_rows;
434735 state.batch_index = 0;
434736 state.processed_rows = 0;
434737}

◆ NextParallelScan()

bool duckdb::RowGroupCollection::NextParallelScan ( ClientContext & context,
ParallelCollectionScanState & state,
CollectionScanState & scan_state )
434740 {
434741 AssignSharedPointer(scan_state.row_groups, state.row_groups);
434742 while (true) {
434743 idx_t vector_index;
434744 idx_t max_row;
434745 optional_ptr<RowGroupCollection> collection;
434746 optional_ptr<SegmentNode<RowGroup>> row_group;
434747 {
434748 // select the next row group to scan from the parallel state
434749 lock_guard<mutex> l(state.lock);
434750 if (!state.current_row_group) {
434751 // no more data left to scan
434752 break;
434753 }
434754 auto &current_row_group = state.current_row_group->GetNode();
434755 if (current_row_group.count == 0) {
434756 break;
434757 }
434758 auto row_start = state.current_row_group->GetRowStart();
434759 collection = state.collection;
434760 row_group = state.current_row_group;
434761 if (ClientConfig::GetConfig(context).verify_parallelism) {
434762 vector_index = state.vector_index;
434763 max_row = row_start + MinValue<idx_t>(current_row_group.count,
434764 STANDARD_VECTOR_SIZE * state.vector_index + STANDARD_VECTOR_SIZE);
434765 D_ASSERT(vector_index * STANDARD_VECTOR_SIZE < current_row_group.count);
434766 state.vector_index++;
434767 if (state.vector_index * STANDARD_VECTOR_SIZE >= current_row_group.count) {
434768 state.current_row_group = state.GetNextRowGroup(*state.row_groups, *row_group).get();
434769 state.vector_index = 0;
434770 }
434771 } else {
434772 state.processed_rows += current_row_group.count;
434773 vector_index = 0;
434774 max_row = row_start + current_row_group.count;
434775 state.current_row_group = state.GetNextRowGroup(*state.row_groups, *row_group).get();
434776 }
434777 max_row = MinValue<idx_t>(max_row, state.max_row);
434778 scan_state.batch_index = ++state.batch_index;
434779 }
434780 D_ASSERT(collection);
434781 D_ASSERT(row_group);
434782
434783 // initialize the scan for this row group
434784 bool need_to_scan =
434785 InitializeScanInRowGroup(context, scan_state, *collection, *row_group, vector_index, max_row);
434786 if (!need_to_scan) {
434787 // skip this row group
434788 continue;
434789 }
434790 return true;
434791 }
434792 lock_guard<mutex> l(state.lock);
434793 scan_state.batch_index = state.batch_index;
434794 return false;
434795}
void AssignSharedPointer(shared_ptr< T > &target, const shared_ptr< T > &source)
Definition duckdb.hpp:2180

◆ Chunks() [1/2]

RowGroupIterationHelper duckdb::RowGroupCollection::Chunks ( DuckTransaction & transaction)
434865 {
434866 vector<StorageIndex> column_ids;
434867 column_ids.reserve(types.size());
434868 for (idx_t i = 0; i < types.size(); i++) {
434869 column_ids.emplace_back(i);
434870 }
434871 return Chunks(transaction, column_ids);
434872}

◆ Chunks() [2/2]

RowGroupIterationHelper duckdb::RowGroupCollection::Chunks ( DuckTransaction & transaction,
const vector< StorageIndex > & column_ids )
434875 {
434876 return RowGroupIterationHelper(*this, transaction, column_ids);
434877}

◆ Fetch()

void duckdb::RowGroupCollection::Fetch ( TransactionData transaction,
DataChunk & result,
const vector< StorageIndex > & column_ids,
const Vector & row_identifiers,
idx_t fetch_count,
ColumnFetchState & state )
434883 {
434884 // figure out which row_group to fetch from
434885 auto row_ids = FlatVector::GetData<row_t>(row_identifiers);
434886 idx_t count = 0;
434887 auto row_groups = GetRowGroups();
434888 for (idx_t i = 0; i < fetch_count; i++) {
434889 auto row_id = row_ids[i];
434890 optional_ptr<SegmentNode<RowGroup>> row_group;
434891 {
434892 idx_t segment_index;
434893 auto l = row_groups->Lock();
434894 if (!row_groups->TryGetSegmentIndex(l, UnsafeNumericCast<idx_t>(row_id), segment_index)) {
434895 // in parallel append scenarios it is possible for the row_id
434896 continue;
434897 }
434898 row_group = row_groups->GetSegmentByIndex(l, UnsafeNumericCast<int64_t>(segment_index));
434899 }
434900 auto &current_row_group = row_group->GetNode();
434901 auto offset_in_row_group = UnsafeNumericCast<idx_t>(row_id) - row_group->GetRowStart();
434902 if (state.fetch_type == FetchType::TRANSACTIONAL_FETCH &&
434903 !current_row_group.Fetch(transaction, offset_in_row_group)) {
434904 continue;
434905 }
434906 state.row_group = row_group;
434907 current_row_group.FetchRow(transaction, state, column_ids, UnsafeNumericCast<row_t>(offset_in_row_group),
434908 result, count);
434909 count++;
434910 }
434911 result.SetCardinality(count);
434912}
@ TRANSACTIONAL_FETCH
Verify if each row is valid for the transaction prior to fetching.
Definition duckdb.cpp:74961

◆ CanFetch()

bool duckdb::RowGroupCollection::CanFetch ( TransactionData transaction,
const row_t row_id )

Returns true, if the row group can fetch the row id for the transaction.

434914 {
434915 auto row_groups = GetRowGroups();
434916 optional_ptr<SegmentNode<RowGroup>> row_group;
434917 {
434918 idx_t segment_index;
434919 auto l = row_groups->Lock();
434920 if (!row_groups->TryGetSegmentIndex(l, UnsafeNumericCast<idx_t>(row_id), segment_index)) {
434921 return false;
434922 }
434923 row_group = row_groups->GetSegmentByIndex(l, UnsafeNumericCast<int64_t>(segment_index));
434924 }
434925 auto &current_row_group = row_group->GetNode();
434926 auto offset_in_row_group = UnsafeNumericCast<idx_t>(row_id) - row_group->GetRowStart();
434927 return current_row_group.Fetch(transaction, offset_in_row_group);
434928}
Here is the caller graph for this function:

◆ InitializeAppend() [1/2]

void duckdb::RowGroupCollection::InitializeAppend ( TableAppendState & state)

Initialize an append of a variable number of rows. FinalizeAppend must be called after appending is done.

434971 {
434972 TransactionData tdata(0, 0);
434973 InitializeAppend(tdata, state);
434974}
void InitializeAppend(TableAppendState &state)
Initialize an append of a variable number of rows. FinalizeAppend must be called after appending is d...
Definition duckdb.cpp:434971
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializeAppend() [2/2]

void duckdb::RowGroupCollection::InitializeAppend ( TransactionData transaction,
TableAppendState & state )

Initialize an append with a variable number of rows. FinalizeAppend should not be called after appending is done.

434947 {
434948 state.row_start = UnsafeNumericCast<row_t>(total_rows.load());
434949 state.current_row = state.row_start;
434950 state.total_append_count = 0;
434951
434952 // start writing to the row_groups
434953 state.row_groups = GetRowGroups();
434954 auto l = state.row_groups->Lock();
434955 if (state.row_groups->IsEmpty(l) || requires_new_row_group) {
434956 // empty row group collection: empty first row group
434957 AppendRowGroup(l, state.row_groups->GetBaseRowId() + total_rows);
434958 }
434959 state.start_row_group = state.row_groups->GetLastSegment(l);
434960 D_ASSERT(state.row_groups->GetBaseRowId() + total_rows ==
434961 state.start_row_group->GetRowStart() + state.start_row_group->GetNode().count);
434962 state.start_row_group->GetNode().InitializeAppend(state.row_group_append_state);
434963 state.transaction = transaction;
434964 state.row_group_start = state.start_row_group->GetRowStart();
434965
434966 // initialize thread-local stats so we have less lock contention when updating distinct statistics
434967 state.stats = TableStatistics();
434968 state.stats.InitializeEmpty(types);
434969}

◆ Append()

bool duckdb::RowGroupCollection::Append ( DataChunk & chunk,
TableAppendState & state )

Appends to the row group collection. Returns true if a new row group has been created to append to.

434976 {
434977 const idx_t row_group_size = GetRowGroupSize();
434978 D_ASSERT(chunk.ColumnCount() == types.size());
434979 chunk.Verify();
434980
434981 bool new_row_group = false;
434982 idx_t total_append_count = chunk.size();
434983 idx_t remaining = chunk.size();
434984 state.total_append_count += total_append_count;
434985 while (true) {
434986 auto current_row_group = state.row_group_append_state.row_group;
434987 // check how much we can fit into the current row_group
434988 idx_t append_count =
434989 MinValue<idx_t>(remaining, row_group_size - state.row_group_append_state.offset_in_row_group);
434990 if (append_count > 0) {
434991 auto previous_allocation_size = current_row_group->GetAllocationSize();
434992 current_row_group->Append(state.row_group_append_state, chunk, append_count);
434993 allocation_size += current_row_group->GetAllocationSize() - previous_allocation_size;
434994 // merge the stats
434995 current_row_group->MergeIntoStatistics(stats);
434996 }
434997 remaining -= append_count;
434998 if (remaining == 0) {
434999 break;
435000 }
435001 // we expect max 1 iteration of this loop (i.e. a single chunk should never overflow more than one
435002 // row_group)
435003 D_ASSERT(chunk.size() == remaining + append_count);
435004 // slice the input chunk
435005 if (remaining < chunk.size()) {
435006 chunk.Slice(append_count, remaining);
435007 }
435008 // append a new row_group
435009 new_row_group = true;
435010 auto next_start = state.row_group_start + state.row_group_append_state.offset_in_row_group;
435011
435012 auto l = state.row_groups->Lock();
435013 AppendRowGroup(l, next_start);
435014 // set up the append state for this row_group
435015 auto last_row_group = state.row_groups->GetLastSegment(l);
435016 last_row_group->GetNode().InitializeAppend(state.row_group_append_state);
435017 state.row_group_start = next_start;
435018 }
435019 state.current_row += row_t(total_append_count);
435020
435021 auto local_stats_lock = state.stats.GetLock();
435022
435023 for (idx_t col_idx = 0; col_idx < types.size(); col_idx++) {
435024 auto &column_stats = state.stats.GetStats(*local_stats_lock, col_idx);
435025 column_stats.UpdateDistinctStatistics(chunk.data[col_idx], chunk.size(), state.hashes);
435026 }
435027
435028 return new_row_group;
435029}
DUCKDB_API void Verify()
Definition duckdb.cpp:117115
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
int64_t row_t
The type used for row identifiers.
Definition duckdb.hpp:240
Here is the call graph for this function:

◆ FinalizeAppend()

void duckdb::RowGroupCollection::FinalizeAppend ( TransactionData transaction,
TableAppendState & state )

FinalizeAppend flushes an append with a variable number of rows.

435031 {
435032 const idx_t row_group_size = GetRowGroupSize();
435033
435034 auto remaining = state.total_append_count;
435035 auto row_group = state.start_row_group;
435036 while (remaining > 0) {
435037 auto &current_row_group = row_group->GetNode();
435038 auto append_count = MinValue<idx_t>(remaining, row_group_size - current_row_group.count);
435039 current_row_group.AppendVersionInfo(transaction, append_count);
435040 remaining -= append_count;
435041 row_group = state.row_groups->GetNextSegment(*row_group);
435042 }
435043 total_rows += state.total_append_count;
435044
435045 state.total_append_count = 0;
435046 state.start_row_group = nullptr;
435047
435048 auto local_stats_lock = state.stats.GetLock();
435049 auto global_stats_lock = stats.GetLock();
435050 for (idx_t col_idx = 0; col_idx < types.size(); col_idx++) {
435051 auto &global_stats = stats.GetStats(*global_stats_lock, col_idx);
435052 if (!global_stats.HasDistinctStats()) {
435053 continue;
435054 }
435055 auto &local_stats = state.stats.GetStats(*local_stats_lock, col_idx);
435056 if (!local_stats.HasDistinctStats()) {
435057 continue;
435058 }
435059 global_stats.DistinctStats().Merge(local_stats.DistinctStats());
435060 }
435061
435062 Verify();
435063}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CommitAppend()

void duckdb::RowGroupCollection::CommitAppend ( transaction_t commit_id,
idx_t row_start,
idx_t count )
435065 {
435066 auto row_groups = GetRowGroups();
435067 auto row_group = row_groups->GetSegment(row_start);
435068 D_ASSERT(row_group);
435069 idx_t current_row = row_start;
435070 idx_t remaining = count;
435071 while (true) {
435072 auto &current_row_group = row_group->GetNode();
435073 idx_t start_in_row_group = current_row - row_group->GetRowStart();
435074 idx_t append_count = MinValue<idx_t>(current_row_group.count - start_in_row_group, remaining);
435075
435076 current_row_group.CommitAppend(commit_id, start_in_row_group, append_count);
435077
435078 current_row += append_count;
435079 remaining -= append_count;
435080 if (remaining == 0) {
435081 break;
435082 }
435083 row_group = row_groups->GetNextSegment(*row_group);
435084 }
435085}

◆ RevertAppendInternal()

void duckdb::RowGroupCollection::RevertAppendInternal ( idx_t start_row)
435087 {
435088 auto row_groups = GetRowGroups();
435089
435090 auto l = row_groups->Lock();
435091 idx_t segment_count = row_groups->GetSegmentCount(l);
435092 if (segment_count == 0) {
435093 // we have no segments to revert
435094 return;
435095 }
435096 auto last_segment = row_groups->GetLastSegment(l);
435097 if (last_segment->GetRowEnd() <= new_end_idx) {
435098 return;
435099 }
435100 auto reverted_row_groups = make_shared_ptr<RowGroupSegmentTree>(*this, row_groups->GetBaseRowId());
435101 auto rlock = reverted_row_groups->Lock();
435102 for (auto &entry : row_groups->SegmentNodes(l)) {
435103 idx_t row_start = entry.GetRowStart();
435104 idx_t row_end = row_start + entry.GetCount();
435105 if (row_start >= new_end_idx) {
435106 // this row group does not belong to the new row group set
435107 break;
435108 }
435109 // this row group - at least partially - belongs to the new set
435110 if (row_end > new_end_idx) {
435111 // this is the last row group - have to revert WITHIN it
435112 entry.GetNode().RevertAppend(new_end_idx - row_start);
435113 }
435114 reverted_row_groups->AppendSegment(rlock, entry.ReferenceNode());
435115 }
435116 SetRowGroups(std::move(reverted_row_groups));
435117 total_rows = new_end_idx;
435118}

◆ CleanupAppend()

void duckdb::RowGroupCollection::CleanupAppend ( transaction_t lowest_transaction,
idx_t start,
idx_t count )
435120 {
435121 auto row_groups = GetRowGroups();
435122 auto row_group = row_groups->GetSegment(start);
435123 D_ASSERT(row_group);
435124 idx_t current_row = start;
435125 idx_t remaining = count;
435126 while (true) {
435127 auto &current_row_group = row_group->GetNode();
435128 idx_t start_in_row_group = current_row - row_group->GetRowStart();
435129 idx_t append_count = MinValue<idx_t>(current_row_group.count - start_in_row_group, remaining);
435130
435131 current_row_group.CleanupAppend(lowest_transaction, start_in_row_group, append_count);
435132
435133 current_row += append_count;
435134 remaining -= append_count;
435135 if (remaining == 0) {
435136 break;
435137 }
435138 row_group = row_groups->GetNextSegment(*row_group);
435139 }
435140}

◆ MergeStorage()

void duckdb::RowGroupCollection::MergeStorage ( RowGroupCollection & data,
optional_ptr< DataTable > table,
optional_ptr< StorageCommitState > commit_state )
435153 {
435154 D_ASSERT(data.types == types);
435155 auto segments = data.GetRowGroups()->MoveSegments();
435156 auto row_groups = GetRowGroups();
435157 auto start_index = row_groups->GetBaseRowId() + total_rows.load();
435158 auto index = start_index;
435159
435160 // check if the row groups we are merging are optimistically written
435161 // if all row groups are optimistically written we keep around the block pointers
435162 unique_ptr<PersistentCollectionData> row_group_data;
435163 idx_t optimistically_written_count = 0;
435164 if (commit_state) {
435165 for (auto &entry : segments) {
435166 auto &row_group = entry->GetNode();
435167 if (!row_group.IsPersistent()) {
435168 if (optimistically_written_count > 0) {
435169#ifdef DEBUG
435170 throw InternalException("Partially optimistically written data at position %d (row start %d)",
435171 entry->GetIndex(), entry->GetRowStart());
435172#endif
435173 }
435174 break;
435175 }
435176 optimistically_written_count += row_group.count;
435177 }
435178 if (optimistically_written_count > 0) {
435179 row_group_data = make_uniq<PersistentCollectionData>();
435180 }
435181 }
435182 bool is_persistent = segments.back()->GetNode().IsPersistent();
435183 for (auto &entry : segments) {
435184 auto row_group = entry->MoveNode();
435185 row_group->MoveToCollection(*this);
435186
435187 if (commit_state && (index - start_index) < optimistically_written_count) {
435188 // serialize the block pointers of this row group
435189 auto persistent_data = row_group->SerializeRowGroupInfo(index);
435190 persistent_data.types = types;
435191 row_group_data->row_group_data.push_back(std::move(persistent_data));
435192 }
435193 index += row_group->count;
435194 row_groups->AppendSegment(std::move(row_group));
435195 }
435196 if (commit_state && optimistically_written_count > 0) {
435197 // if we have serialized the row groups - push the serialized block pointers into the commit state
435198 commit_state->AddRowGroupData(*table, start_index, optimistically_written_count, std::move(row_group_data));
435199 }
435200 stats.MergeStats(data.stats);
435201 total_rows += data.total_rows.load();
435202 if (is_persistent) {
435203 SetAppendRequiresNewRowGroup();
435204 }
435205}
index

◆ IsPersistent()

bool duckdb::RowGroupCollection::IsPersistent ( ) const
435142 {
435143 auto row_groups = GetRowGroups();
435144 for (auto &row_group : row_groups->Segments()) {
435145 if (!row_group.IsPersistent()) {
435146 return false;
435147 }
435148 }
435149 return true;
435150}

◆ RemoveFromIndexes()

void duckdb::RowGroupCollection::RemoveFromIndexes ( const QueryContext & context,
TableIndexList & indexes,
Vector & row_identifiers,
idx_t count,
IndexRemovalType removal_type,
optional_idx active_checkpoint = optional_idx() )
435409 {
435410 // Collect all Indexed columns on the table.
435411 unordered_set<column_t> indexed_column_id_set;
435412
435413 for (auto &index : indexes.Indexes()) {
435414 auto &set = index.GetColumnIdSet();
435415 indexed_column_id_set.insert(set.begin(), set.end());
435416 }
435417
435418 // If we are in WAL replay, delete data will be buffered, and so we sort the column_ids
435419 // since the sorted form will be the mapping used to get back physical IDs from the buffered index chunk.
435420 vector<StorageIndex> column_ids;
435421 for (auto &col : indexed_column_id_set) {
435422 column_ids.emplace_back(col);
435423 }
435424 sort(column_ids.begin(), column_ids.end());
435425
435426 vector<LogicalType> column_types;
435427 for (auto &col : column_ids) {
435428 column_types.push_back(types[col.GetPrimaryIndex()]);
435429 }
435430
435431 DataChunk fetch_chunk;
435432 fetch_chunk.Initialize(GetAllocator(), column_types);
435433
435434 ColumnFetchState state;
435435 state.fetch_type = FetchType::FORCE_FETCH;
435436 TransactionData commit_transaction(MAX_TRANSACTION_ID, TRANSACTION_ID_START - 1);
435437 Fetch(commit_transaction, fetch_chunk, column_ids, row_identifiers, count, state);
435438
435439 // Used for index value removal.
435440 // Contains all columns but only initializes indexed ones.
435441 DataChunk result_chunk;
435442 auto fetched_columns = vector<bool>(types.size(), false);
435443 result_chunk.Initialize(GetAllocator(), types, fetched_columns);
435444 // Now set all to-be-fetched columns.
435445 for (auto &col : indexed_column_id_set) {
435446 fetched_columns[col] = true;
435447 }
435448
435449 // Reference the necessary columns of the fetch_chunk.
435450 idx_t fetch_idx = 0;
435451 for (idx_t j = 0; j < types.size(); j++) {
435452 if (fetched_columns[j]) {
435453 result_chunk.data[j].Reference(fetch_chunk.data[fetch_idx++]);
435454 continue;
435455 }
435456 result_chunk.data[j].Reference(Value(types[j]));
435457 }
435458 result_chunk.SetCardinality(fetch_chunk);
435459
435460 DataChunk remaining_result_chunk;
435461 unique_ptr<Vector> remaining_row_ids;
435462
435463 for (auto &entry : indexes.IndexEntries()) {
435464 auto &index = *entry.index;
435465 if (index.IsBound()) {
435466 lock_guard<mutex> guard(entry.lock);
435467
435468 // check which indexes we should append to or remove from
435469 // note that this method might also involve appending to indexes
435470 // the reason for that is that we have "delta" indexes that we must fill with data we are removing
435471 // OR because we are actually reverting a previous removal
435472 IndexRemovalTargets targets;
435473 GetIndexRemovalTargets(entry, removal_type, targets, active_checkpoint);
435474
435475 bool removal_succeeded = false;
435476 if (targets.conditional_remove_target) {
435477 // if we have an conditional remove target, we first try to remove the chunk from there
435478 idx_t delete_count = targets.conditional_remove_target->TryDelete(result_chunk, row_identifiers);
435479 if (delete_count > 0) {
435480 if (delete_count != result_chunk.size()) {
435481 // it should not be possible to get here
435482 // what this means is that we removed SOME rows from the "initial_remove_target" - but not all
435483 // "initial_remove_target" contains rows that were INSERTED during the checkpoint
435484 // the regular remove target contains rows that were ALREADY THERE during the checkpoint
435485 // "RemoveFromIndexes" works on a per-row-group basis
435486 // when appending during a checkpoint, we always insert new row groups for new data
435487 // so the two groups of data should always be separate
435488 throw InternalException("RowGroupCollection::RemoveFromIndexes - partially deleted from the "
435489 "initial removal target");
435490 }
435491 removal_succeeded = true;
435492 }
435493 }
435494 if (targets.conditional_append_target && !removal_succeeded) {
435495 // for any rows that were not removed - append them to the conditional append target instead
435496 IndexAppendInfo append_info;
435497 auto error = targets.conditional_append_target->Append(result_chunk, row_identifiers, append_info);
435498 if (error.HasError()) {
435499 throw InternalException("Failed to append to %s: %s", targets.conditional_append_target->name,
435500 error.Message());
435501 }
435502 }
435503 // perform the targeted append / removal
435504 if (targets.append_target) {
435505 IndexAppendInfo append_info;
435506 auto error = targets.append_target->Append(result_chunk, row_identifiers, append_info);
435507 if (error.HasError()) {
435508 throw InternalException("Failed to append to %s: %s", targets.append_target->name, error.Message());
435509 }
435510 }
435511 if (targets.remove_target) {
435512 targets.remove_target->Delete(result_chunk, row_identifiers);
435513 }
435514 continue;
435515 }
435516 // Buffering takes only the indexed columns in ordering of the column_ids mapping.
435517 DataChunk index_column_chunk;
435518 index_column_chunk.InitializeEmpty(column_types);
435519 for (idx_t i = 0; i < column_types.size(); i++) {
435520 auto col_id = column_ids[i].GetPrimaryIndex();
435521 index_column_chunk.data[i].Reference(result_chunk.data[col_id]);
435522 }
435523 index_column_chunk.SetCardinality(result_chunk.size());
435524 auto &unbound_index = index.Cast<UnboundIndex>();
435525 unbound_index.BufferChunk(index_column_chunk, row_identifiers, column_ids, BufferedIndexReplay::DEL_ENTRY);
435526 }
435527}
DUCKDB_API void InitializeEmpty(const vector< LogicalType > &types)
Initializes a DataChunk with the given types and without any vector data allocation.
Definition duckdb.cpp:116783
DUCKDB_API void Initialize(ClientContext &context, const vector< LogicalType > &types, idx_t capacity=STANDARD_VECTOR_SIZE)
Definition duckdb.cpp:116791
void sort(InputArray src, OutputArray dst, int flags)

◆ Delete()

idx_t duckdb::RowGroupCollection::Delete ( TransactionData transaction,
DataTable & table,
row_t * ids,
idx_t count )
435210 {
435211 idx_t delete_count = 0;
435212 // delete is in the row groups
435213 // we need to figure out for each id to which row group it belongs
435214 // usually all (or many) ids belong to the same row group
435215 // we iterate over the ids and check for every id if it belongs to the same row group as their predecessor
435216 idx_t pos = 0;
435217 auto row_groups = GetRowGroups();
435218 do {
435219 idx_t start = pos;
435220 auto row_group = row_groups->GetSegment(UnsafeNumericCast<idx_t>(ids[start]));
435221
435222 auto &current_row_group = row_group->GetNode();
435223 auto row_start = row_group->GetRowStart();
435224 auto row_end = row_start + current_row_group.count;
435225 for (pos++; pos < count; pos++) {
435226 D_ASSERT(ids[pos] >= 0);
435227 // check if this id still belongs to this row group
435228 if (idx_t(ids[pos]) < row_start) {
435229 // id is before row_group start -> it does not
435230 break;
435231 }
435232 if (idx_t(ids[pos]) >= row_end) {
435233 // id is after row group end -> it does not
435234 break;
435235 }
435236 }
435237 delete_count += current_row_group.Delete(transaction, table, ids + start, pos - start, row_start);
435238 } while (pos < count);
435239
435240 return delete_count;
435241}

◆ Update()

void duckdb::RowGroupCollection::Update ( TransactionData transaction,
DataTable & table,
row_t * ids,
const vector< PhysicalIndex > & column_ids,
DataChunk & updates )
435272 {
435273 D_ASSERT(updates.size() >= 1);
435274 idx_t pos = 0;
435275 auto row_groups = GetRowGroups();
435276 do {
435277 idx_t start = pos;
435278 auto row_group = NextUpdateRowGroup(*row_groups, ids, pos, updates.size());
435279
435280 auto &current_row_group = row_group->GetNode();
435281 current_row_group.Update(transaction, data_table, updates, ids, start, pos - start, column_ids,
435282 row_group->GetRowStart());
435283
435284 auto l = stats.GetLock();
435285 for (idx_t i = 0; i < column_ids.size(); i++) {
435286 auto column_id = column_ids[i];
435287 stats.MergeStats(*l, column_id.index, *current_row_group.GetStatistics(column_id.index));
435288 }
435289 } while (pos < updates.size());
435290}

◆ UpdateColumn()

void duckdb::RowGroupCollection::UpdateColumn ( TransactionData transaction,
DataTable & table,
Vector & row_ids,
const vector< column_t > & column_path,
DataChunk & updates )
435530 {
435531 D_ASSERT(updates.size() >= 1);
435532 auto ids = FlatVector::GetData<row_t>(row_ids);
435533 idx_t pos = 0;
435534 auto row_groups = GetRowGroups();
435535 do {
435536 idx_t start = pos;
435537 auto row_group = NextUpdateRowGroup(*row_groups, ids, pos, updates.size());
435538 auto &current_row_group = row_group->GetNode();
435539 current_row_group.UpdateColumn(transaction, data_table, updates, row_ids, start, pos - start, column_path,
435540 row_group->GetRowStart());
435541
435542 auto lock = stats.GetLock();
435543 auto primary_column_idx = column_path[0];
435544 current_row_group.MergeIntoStatistics(primary_column_idx,
435545 stats.GetStats(*lock, primary_column_idx).Statistics());
435546 } while (pos < updates.size());
435547}

◆ Checkpoint()

void duckdb::RowGroupCollection::Checkpoint ( TableDataWriter & writer,
TableStatistics & global_stats )
435969 {
435970 auto row_groups = GetRowGroups();
435971
435972 CollectionCheckpointState checkpoint_state(*this, writer, global_stats, *row_groups);
435973
435974 VacuumState vacuum_state;
435975 InitializeVacuumState(checkpoint_state, vacuum_state, writer.GetRowGroupCount());
435976
435977 try {
435978 // schedule tasks
435979 idx_t total_vacuum_tasks = 0;
435980 auto max_vacuum_tasks = Settings::Get<MaxVacuumTasksSetting>(writer.GetDatabase());
435981 for (idx_t segment_idx = 0; segment_idx < checkpoint_state.SegmentCount(); segment_idx++) {
435982 auto vacuum_tasks =
435983 ScheduleVacuumTasks(checkpoint_state, vacuum_state, segment_idx, total_vacuum_tasks < max_vacuum_tasks);
435984 if (vacuum_tasks) {
435985 // vacuum tasks were scheduled - don't schedule a checkpoint task yet
435986 total_vacuum_tasks++;
435987 vacuum_state.row_ids_changed = true;
435988 continue;
435989 }
435990 if (checkpoint_state.SegmentIsDropped(segment_idx)) {
435991 // row group was vacuumed/dropped - skip
435992 continue;
435993 }
435994 // schedule a checkpoint task for this row group
435995 auto entry = checkpoint_state.GetSegment(segment_idx);
435996 auto &row_group = entry->GetNode();
435997 if (!RefersToSameObject(row_group.GetCollection(), *this)) {
435998 throw InternalException("RowGroup Vacuum - row group collection of row group changed");
435999 }
436000 if (writer.GetCheckpointOptions().type != CheckpointType::VACUUM_ONLY) {
436001 DUCKDB_LOG(checkpoint_state.writer.GetDatabase(), CheckpointLogType, GetAttached(), *info, segment_idx,
436002 row_group, vacuum_state.row_start);
436003 auto checkpoint_task = GetCheckpointTask(checkpoint_state, segment_idx);
436004 if (checkpoint_task) {
436005 checkpoint_state.executor->ScheduleTask(std::move(checkpoint_task));
436006 }
436007 }
436008 vacuum_state.row_start += row_group.count;
436009 }
436010 } catch (const std::exception &e) {
436011 ErrorData error(e);
436012 checkpoint_state.executor->PushError(std::move(error));
436013 checkpoint_state.executor->WorkOnTasks(); // ensure all tasks have completed first before rethrowing
436014 throw;
436015 }
436016 // all tasks have been successfully scheduled - execute tasks until we are done
436017 checkpoint_state.executor->WorkOnTasks();
436018
436019 // no errors - finalize the row groups
436020 // if the table already exists on disk - check if all row groups have stayed the same
436021 if (Settings::Get<ExperimentalMetadataReuseSetting>(writer.GetDatabase()) && metadata_pointer.IsValid()) {
436022 bool table_has_changes = false;
436023 for (idx_t segment_idx = 0; segment_idx < checkpoint_state.SegmentCount(); segment_idx++) {
436024 if (checkpoint_state.SegmentIsDropped(segment_idx)) {
436025 table_has_changes = true;
436026 break;
436027 }
436028 auto &write_state = checkpoint_state.write_data[segment_idx];
436029 if (!write_state.reuse_existing_metadata_blocks) {
436030 table_has_changes = true;
436031 break;
436032 }
436033 }
436034 if (!table_has_changes) {
436035 // table is unmodified and already exists on disk
436036 // we can directly re-use the metadata pointer
436037 // mark all blocks associated with row groups as still being in-use
436038 auto &metadata_manager = writer.GetMetadataManager();
436039 for (idx_t segment_idx = 0; segment_idx < checkpoint_state.SegmentCount(); segment_idx++) {
436040 auto entry = checkpoint_state.GetSegment(segment_idx);
436041 auto &row_group = entry->GetNode();
436042 auto &write_state = checkpoint_state.write_data[segment_idx];
436043 metadata_manager.ClearModifiedBlocks(row_group.GetColumnStartPointers());
436044 D_ASSERT(write_state.reuse_existing_metadata_blocks);
436045 vector<MetaBlockPointer> extra_metadata_block_pointers;
436046 extra_metadata_block_pointers.reserve(write_state.existing_extra_metadata_blocks.size());
436047 for (auto &block_pointer : write_state.existing_extra_metadata_blocks) {
436048 extra_metadata_block_pointers.emplace_back(block_pointer, 0);
436049 }
436050 metadata_manager.ClearModifiedBlocks(extra_metadata_block_pointers);
436051 auto row_group_writer = checkpoint_state.writer.GetRowGroupWriter(row_group);
436052 row_group.CheckpointDeletes(*row_group_writer);
436053 }
436054 writer.WriteUnchangedTable(metadata_pointer, metadata_pointers, total_rows.load());
436055 // copy over existing stats into the global stats
436056 CopyStats(global_stats);
436057 return;
436058 }
436059 }
436060
436061 // not all segments have stayed the same - we need to make a new segment tree with the new set of segments
436062 auto new_row_groups = make_shared_ptr<RowGroupSegmentTree>(*this, row_groups->GetBaseRowId());
436063 auto l = new_row_groups->Lock();
436064
436065 // initialize new empty stats
436066 global_stats.InitializeEmpty(stats);
436067
436068 idx_t new_total_rows = 0;
436069 unordered_set<idx_t> columns_with_incomplete_stats;
436070 for (idx_t segment_idx = 0; segment_idx < checkpoint_state.SegmentCount(); segment_idx++) {
436071 auto entry = checkpoint_state.GetSegment(segment_idx);
436072 if (!entry) {
436073 // row group was vacuumed/dropped - skip
436074 D_ASSERT(checkpoint_state.SegmentIsDropped(segment_idx));
436075 continue;
436076 }
436077 auto &row_group = entry->GetNode();
436078 auto &row_group_writer = checkpoint_state.writers[segment_idx];
436079 if (!row_group_writer) {
436080 // row group was not checkpointed - this can happen if compressing is disabled for in-memory tables
436081 new_row_groups->AppendSegment(l, entry->ReferenceNode());
436082 new_total_rows += row_group.count;
436083
436084 auto lock = global_stats.GetLock();
436085 for (idx_t column_idx = 0; column_idx < row_group.GetColumnCount(); column_idx++) {
436086 global_stats.GetStats(*lock, column_idx).Statistics().Merge(*row_group.GetStatistics(column_idx));
436087 }
436088 continue;
436089 }
436090 auto &row_group_write_data = checkpoint_state.write_data[segment_idx];
436091 idx_t row_start = new_total_rows;
436092 bool metadata_reuse = row_group_write_data.reuse_existing_metadata_blocks;
436093 auto new_row_group = std::move(row_group_write_data.result_row_group);
436094 if (!new_row_group) {
436095 // row group was unchanged - emit previous row group
436096 new_row_group = entry->ReferenceNode();
436097 }
436098 RowGroupPointer pointer_copy;
436099 auto debug_verify_blocks = Settings::Get<DebugVerifyBlocksSetting>(GetAttached().GetDatabase()) &&
436100 dynamic_cast<SingleFileTableDataWriter *>(&checkpoint_state.writer) != nullptr;
436101
436102 // check if we should write this row group to the persistent storage
436103 // don't write it if it only has uncommitted transaction-local changes made AFTER this checkpoint was started
436104 auto pointer =
436105 row_group.Checkpoint(std::move(row_group_write_data), *row_group_writer, global_stats, row_start);
436106 if (debug_verify_blocks) {
436107 pointer_copy = pointer;
436108 }
436109 // for any columns that are not yet loaded add them to the list of columns with incomplete stats
436110 auto unloaded_columns = row_group_writer->GetUnloadedColumns();
436111 for (auto &column_idx : unloaded_columns) {
436112 columns_with_incomplete_stats.insert(column_idx);
436113 }
436114
436115 writer.AddRowGroup(std::move(pointer), std::move(row_group_writer));
436116 new_row_groups->AppendSegment(l, std::move(new_row_group));
436117 new_total_rows += row_group.count;
436118
436119 if (debug_verify_blocks) {
436120 if (!pointer_copy.has_metadata_blocks) {
436121 throw InternalException("Checkpointing should always remember metadata blocks");
436122 }
436123 if (metadata_reuse && pointer_copy.data_pointers != row_group.GetColumnStartPointers()) {
436124 throw InternalException("Colum start pointers changed during metadata reuse");
436125 }
436126
436127 // Capture blocks that have been written
436128 vector<MetaBlockPointer> all_written_blocks = pointer_copy.data_pointers;
436129 vector<MetaBlockPointer> all_metadata_blocks;
436130 for (auto &block : pointer_copy.extra_metadata_blocks) {
436131 all_written_blocks.emplace_back(block, 0);
436132 all_metadata_blocks.emplace_back(block, 0);
436133 }
436134
436135 // Verify that we can load the metadata correctly again
436136 vector<MetaBlockPointer> all_quick_read_blocks;
436137 for (auto &ptr : row_group.GetColumnStartPointers()) {
436138 all_quick_read_blocks.emplace_back(ptr);
436139 if (metadata_reuse && !block_manager.GetMetadataManager().BlockHasBeenCleared(ptr)) {
436140 throw InternalException("Found column start block that was not cleared");
436141 }
436142 }
436143 auto extra_metadata_blocks = row_group.GetOrComputeExtraMetadataBlocks(/* force_compute: */ true);
436144 for (auto &ptr : extra_metadata_blocks) {
436145 auto block_pointer = MetaBlockPointer(ptr, 0);
436146 all_quick_read_blocks.emplace_back(block_pointer);
436147 if (metadata_reuse && !block_manager.GetMetadataManager().BlockHasBeenCleared(block_pointer)) {
436148 throw InternalException("Found extra metadata block that was not cleared");
436149 }
436150 }
436151
436152 // Deserialize all columns to check if the quick read via GetOrComputeExtraMetadataBlocks was correct
436153 vector<MetaBlockPointer> all_full_read_blocks;
436154 auto column_start_pointers = row_group.GetColumnStartPointers();
436155 auto &types = row_group.GetCollection().GetTypes();
436156 auto &metadata_manager = row_group.GetCollection().GetMetadataManager();
436157 for (idx_t i = 0; i < column_start_pointers.size(); i++) {
436158 MetadataReader reader(metadata_manager, column_start_pointers[i], &all_full_read_blocks);
436159 ColumnData::Deserialize(GetBlockManager(), GetTableInfo(), i, reader, types[i]);
436160 }
436161
436162 // Derive sets of blocks to compare
436163 set<idx_t> all_written_block_ids;
436164 for (auto &ptr : all_written_blocks) {
436165 all_written_block_ids.insert(ptr.block_pointer);
436166 }
436167 set<idx_t> all_quick_read_block_ids;
436168 for (auto &ptr : all_quick_read_blocks) {
436169 all_quick_read_block_ids.insert(ptr.block_pointer);
436170 }
436171 set<idx_t> all_full_read_block_ids;
436172 for (auto &ptr : all_full_read_blocks) {
436173 all_full_read_block_ids.insert(ptr.block_pointer);
436174 }
436175 if (all_written_block_ids != all_quick_read_block_ids ||
436176 all_quick_read_block_ids != all_full_read_block_ids) {
436177 std::stringstream oss;
436178 oss << "Written: ";
436179 for (auto &block : all_written_blocks) {
436180 oss << block << ", ";
436181 }
436182 oss << "\n";
436183 oss << "Quick read: ";
436184 for (auto &block : all_quick_read_blocks) {
436185 oss << block << ", ";
436186 }
436187 oss << "\n";
436188 oss << "Full read: ";
436189 for (auto &block : all_full_read_blocks) {
436190 oss << block << ", ";
436191 }
436192 oss << "\n";
436193
436194 throw InternalException("Reloading blocks just written does not yield same blocks: " + oss.str());
436195 }
436196
436197 vector<MetaBlockPointer> read_deletes_pointers;
436198 if (!pointer_copy.deletes_pointers.empty()) {
436199 auto root_delete = pointer_copy.deletes_pointers[0];
436200 auto vm = RowVersionManager::Deserialize(root_delete, GetBlockManager().GetMetadataManager());
436201 read_deletes_pointers = vm->GetStoragePointers();
436202 }
436203
436204 set<idx_t> all_written_deletes_block_ids;
436205 for (auto &ptr : pointer_copy.deletes_pointers) {
436206 all_written_deletes_block_ids.insert(ptr.block_pointer);
436207 }
436208 set<idx_t> all_read_deletes_block_ids;
436209 for (auto &ptr : read_deletes_pointers) {
436210 all_read_deletes_block_ids.insert(ptr.block_pointer);
436211 }
436212
436213 if (all_written_deletes_block_ids != all_read_deletes_block_ids) {
436214 std::stringstream oss;
436215 oss << "Written: ";
436216 for (auto &block : all_written_deletes_block_ids) {
436217 oss << block << ", ";
436218 }
436219 oss << "\n";
436220 oss << "Read: ";
436221 for (auto &block : all_read_deletes_block_ids) {
436222 oss << block << ", ";
436223 }
436224 oss << "\n";
436225
436226 throw InternalException("Reloading deletes blocks just written does not yield same blocks: " +
436227 oss.str());
436228 }
436229 }
436230 }
436231 if (!columns_with_incomplete_stats.empty()) {
436232 // for any columns that have incomplete stats we need to merge in the previous global stats to ensure the stats
436233 // are correct
436234 auto lock = global_stats.GetLock();
436235 for (auto &column_idx : columns_with_incomplete_stats) {
436236 auto stats_lock = stats.GetLock();
436237 auto &column_stats = stats.GetStats(*stats_lock, column_idx);
436238 global_stats.MergeStats(*lock, column_idx, column_stats.Statistics());
436239 }
436240 }
436241 l.Release();
436242
436243 // flush any partial blocks BEFORE updating the row group pointer
436244 // flushing partial blocks updates where data lives
436245 // this cannot be done after other threads start scanning the row groups
436246 // so this HAS to happen before we call "SetRowGroups" to update the row groups
436247 writer.FlushPartialBlocks();
436248 // override the row group segment tree
436249 total_rows = new_total_rows;
436250 SetRowGroups(std::move(new_row_groups));
436251 Verify();
436252 // Rebuild indexes if:
436253 // 1) can_rebuild_indexes is set (it is set when the vacuum_rebuild_indexes
436254 // threshold is set, the table's row count is within the threshold,
436255 // and all the indexes are bound ART's),
436256 // and
436257 // 2) we have changed rowids.
436258 if (vacuum_state.can_rebuild_indexes && vacuum_state.row_ids_changed) {
436259 writer.SetRebuildIndexes();
436260 }
436261}
@ VACUUM_ONLY
Only run vacuum - this can be triggered for in-memory tables.
Definition duckdb.hpp:23137
bool RefersToSameObject(const reference< T > &a, const reference< T > &b)
Returns whether or not two reference wrappers refer to the same object.
Definition duckdb.hpp:2191

◆ InitializeVacuumState()

void duckdb::RowGroupCollection::InitializeVacuumState ( CollectionCheckpointState & checkpoint_state,
VacuumState & state,
optional_idx checkpoint_row_group_count )
435778 {
435779 auto options = checkpoint_state.writer.GetCheckpointOptions();
435780 // currently we can only vacuum deletes if we are doing a full checkpoint
435781 state.can_vacuum_deletes = options.type != CheckpointType::CONCURRENT_CHECKPOINT;
435782 if (!state.can_vacuum_deletes) {
435783 return;
435784 }
435785
435786 // if there are indexes - we cannot change row-ids
435787 // this limits what kind of vacuuming we can do
435788 bool has_indexes = !info->GetIndexes().Empty();
435789
435790 // *unless* vacuum_rebuild_indexes threshold is set, the table's row count
435791 // is within the threshold, and all indexes are bound ART indexes,
435792 // in which case we allow vacuuming and rebuild the indexes afterward.
435793 auto vacuum_rebuild_threshold = Settings::Get<VacuumRebuildIndexesSetting>(checkpoint_state.writer.GetDatabase());
435794 auto index_types = info->GetIndexes().DistinctIndexTypes();
435795 state.can_rebuild_indexes = has_indexes && !info->GetIndexes().HasUnbound() && index_types.size() == 1 &&
435796 index_types.count(ART::TYPE_NAME) && vacuum_rebuild_threshold > 0 &&
435797 GetTotalRows() <= vacuum_rebuild_threshold;
435798
435799 // We can move around rowids if we either 1) don't have any indexes at all or 2) can_rebuild_indexes is true (in
435800 // which case indexes are entirely rebuilt after vacuuming).
435801 state.can_change_row_ids = !has_indexes || state.can_rebuild_indexes;
435802 // obtain the set of committed row counts for each row group
435803 auto row_group_count = checkpoint_state.SegmentCount();
435804 vector<optional_idx> committed_counts;
435805 state.row_group_counts.reserve(checkpoint_state.SegmentCount());
435806 if (checkpoint_row_group_count.IsValid() && checkpoint_row_group_count.GetIndex() > row_group_count) {
435807 // we have row groups that were concurrently appended to this collection
435808 // don't vacuum - otherwise we can move row groups which could cause committed row-ids to be moved around
435809 // while transactions are still processing / depending on them being stable (during e.g. commit)
435810 state.can_vacuum_deletes = false;
435811 return;
435812 }
435813 bool dropped_any_rowgroups = false;
435814 for (auto &entry : checkpoint_state.row_groups.SegmentNodes()) {
435815 auto &row_group = entry.GetNode();
435816 auto row_group_count = row_group.GetCommittedRowCount();
435817 if (!state.can_change_row_ids) {
435818 idx_t total_count = row_group.count;
435819 committed_counts.emplace_back(row_group_count);
435820 // we cannot change row ids, and this row group has deletes
435821 // vacuuming here would alter row ids - so skip it
435822 if (total_count != row_group_count) {
435823 state.row_group_counts.emplace_back();
435824 continue;
435825 }
435826 }
435827 if (row_group_count == 0) {
435828 // empty row group - we can drop it entirely.
435829 row_group.CommitDrop();
435830 checkpoint_state.DropSegment(entry.GetIndex());
435831 dropped_any_rowgroups = true;
435832 state.row_group_counts.push_back(row_group_count);
435833 continue;
435834 }
435835 if (dropped_any_rowgroups) {
435836 // if there are any dropped row groups before a live row group, all the row ids of the row groups following
435837 // the dropped row group will have their row ids shifted forward (to keep row ids contiguous).
435838 state.row_ids_changed = true;
435839 }
435840 state.row_group_counts.push_back(row_group_count);
435841 }
435842 if (!state.can_change_row_ids && options.type != CheckpointType::CONCURRENT_CHECKPOINT) {
435843 // if we cannot change row ids we might still be able to vacuum trailing deletions
435844 // since that would not change the row ids of any non-deleted rows
435845 auto segment_count = state.row_group_counts.size();
435846 for (idx_t i = segment_count; i > 0; i--) {
435847 auto segment_idx = i - 1;
435848 if (!committed_counts[segment_idx].IsValid()) {
435849 // cannot vacuum this row group
435850 break;
435851 }
435852 if (committed_counts[segment_idx].GetIndex() != 0) {
435853 // multiple rows found here - skip
435854 break;
435855 }
435856 auto &entry = *checkpoint_state.row_groups.GetSegmentByIndex(NumericCast<int64_t>(segment_idx));
435857 auto &row_group = entry.GetNode();
435858 D_ASSERT(entry.GetIndex() == segment_idx);
435859 row_group.CommitDrop();
435860 checkpoint_state.DropSegment(segment_idx);
435861 }
435862 }
435863}
static constexpr const char * TYPE_NAME
Index type name for the ART.
Definition duckdb.cpp:12136
@ CONCURRENT_CHECKPOINT
Definition duckdb.hpp:23135

◆ ScheduleVacuumTasks()

bool duckdb::RowGroupCollection::ScheduleVacuumTasks ( CollectionCheckpointState & checkpoint_state,
VacuumState & state,
idx_t segment_idx,
bool schedule_vacuum )
435866 {
435867 static constexpr const idx_t MAX_MERGE_COUNT = 3;
435868
435869 if (!state.can_vacuum_deletes) {
435870 // we cannot vacuum deletes - cannot vacuum
435871 return false;
435872 }
435873 if (segment_idx < state.next_vacuum_idx) {
435874 // this segment is being vacuumed by a previously scheduled task
435875 return true;
435876 }
435877 if (state.row_group_counts[segment_idx].IsValid() && state.row_group_counts[segment_idx].GetIndex() == 0) {
435878 // segment was already dropped - skip
435879 D_ASSERT(checkpoint_state.SegmentIsDropped(segment_idx));
435880 return false;
435881 }
435882 if (!schedule_vacuum) {
435883 return false;
435884 }
435885 idx_t merge_rows;
435886 idx_t next_idx = 0;
435887 idx_t merge_count = 0;
435888 idx_t target_count = 0;
435889 bool perform_merge = false;
435890 // check if we can merge row groups adjacent to the current segment_idx
435891 // we try merging row groups into batches of 1-3 row groups
435892 // our goal is to reduce the amount of row groups
435893 // hence we target_count should be less than merge_count for a merge to be worth it
435894 // we greedily prefer to merge to the lowest target_count
435895 // i.e. we prefer to merge 2 row groups into 1, than 3 row groups into 2
435896 const idx_t row_group_size = GetRowGroupSize();
435897 for (target_count = 1; target_count <= MAX_MERGE_COUNT; target_count++) {
435898 auto total_target_size = target_count * row_group_size;
435899 merge_count = 0;
435900 merge_rows = 0;
435901 for (next_idx = segment_idx; next_idx < checkpoint_state.SegmentCount(); next_idx++) {
435902 if (!state.row_group_counts[next_idx].IsValid()) {
435903 // cannot vacuum this row group - break
435904 break;
435905 }
435906 auto next_row_count = state.row_group_counts[next_idx].GetIndex();
435907 if (next_row_count == 0) {
435908 continue;
435909 }
435910 if (merge_rows + next_row_count > total_target_size) {
435911 // does not fit
435912 break;
435913 }
435914 // we can merge this row group together with the other row group
435915 merge_rows += next_row_count;
435916 merge_count++;
435917 }
435918 if (next_idx == checkpoint_state.SegmentCount()) {
435919 // in order to prevent poor performance when performing small appends, we only merge row groups at the end
435920 // if we can reach a "target" size of twice the current size, or the max row group size
435921 // this is to prevent repeated expensive checkpoints where:
435922 // we have a row group with 100K rows
435923 // merge it with a row group with 1 row, creating a row group with 100K+1 rows
435924 // merge it with a row group with 1 row, creating a row group with 100K+2 rows
435925 // etc. This leads to constant rewriting of the original 100K rows.
435926 idx_t minimum_target =
435927 MinValue<idx_t>(state.row_group_counts[segment_idx].GetIndex() * 2, row_group_size) * target_count;
435928 if (merge_rows >= STANDARD_VECTOR_SIZE && merge_rows < minimum_target) {
435929 // we haven't reached the minimum target - don't do this vacuum
435930 next_idx = segment_idx + 1;
435931 continue;
435932 }
435933 }
435934 if (target_count < merge_count) {
435935 // we can reduce "merge_count" row groups to "target_count"
435936 // perform the merge at this level
435937 perform_merge = true;
435938 break;
435939 }
435940 }
435941 if (!perform_merge) {
435942 return false;
435943 }
435944 // schedule the vacuum task
435945 DUCKDB_LOG(checkpoint_state.writer.GetDatabase(), CheckpointLogType, GetAttached(), *info, segment_idx, merge_count,
435946 target_count, merge_rows, state.row_start);
435947 auto vacuum_task =
435948 make_uniq<VacuumTask>(checkpoint_state, state, segment_idx, merge_count, target_count, merge_rows);
435949 checkpoint_state.executor->ScheduleTask(std::move(vacuum_task));
435950 // skip vacuuming by the row groups we have merged
435951 state.next_vacuum_idx = next_idx;
435952 state.row_start += merge_rows;
435953 return true;
435954}

◆ GetCheckpointTask()

unique_ptr< CheckpointTask > duckdb::RowGroupCollection::GetCheckpointTask ( CollectionCheckpointState & checkpoint_state,
idx_t segment_idx )
435960 {
435961 auto row_group_count = checkpoint_state.writer.GetRowGroupCount();
435962 if (row_group_count.IsValid() && segment_idx >= row_group_count.GetIndex()) {
435963 // this row group was appended AFTER the checkpoint was started - we should not be checkpointing it
435964 return nullptr;
435965 }
435966 return make_uniq<CheckpointTask>(checkpoint_state, segment_idx);
435967}

◆ CommitDropColumn()

void duckdb::RowGroupCollection::CommitDropColumn ( const idx_t column_index)
436296 {
436297 auto row_groups = GetRowGroups();
436298 for (auto &row_group : row_groups->Segments()) {
436299 row_group.CommitDropColumn(column_index);
436300 }
436301}

◆ CommitDropTable()

void duckdb::RowGroupCollection::CommitDropTable ( )
436303 {
436304 auto row_groups = GetRowGroups();
436305 for (auto &row_group : row_groups->Segments()) {
436306 row_group.CommitDrop();
436307 }
436308}

◆ GetPartitionStats()

vector< PartitionStatistics > duckdb::RowGroupCollection::GetPartitionStats ( ) const
436313 {
436314 vector<PartitionStatistics> result;
436315 auto row_groups = GetRowGroups();
436316 for (auto &entry : row_groups->SegmentNodes()) {
436317 result.push_back(RowGroup::GetPartitionStats(entry));
436318 }
436319 return result;
436320}

◆ GetColumnSegmentInfo()

vector< ColumnSegmentInfo > duckdb::RowGroupCollection::GetColumnSegmentInfo ( const QueryContext & context)
436325 {
436326 vector<ColumnSegmentInfo> result;
436327 auto row_groups = GetRowGroups();
436328 auto lock = row_groups->Lock();
436329 for (auto &node : row_groups->SegmentNodes(lock)) {
436330 auto &row_group = node.GetNode();
436331 row_group.GetColumnSegmentInfo(context, node.GetIndex(), result);
436332 }
436333 return result;
436334}

◆ GetTypes()

const vector< LogicalType > & duckdb::RowGroupCollection::GetTypes ( ) const
434564 {
434565 return types;
434566}

◆ AddColumn()

shared_ptr< RowGroupCollection > duckdb::RowGroupCollection::AddColumn ( ClientContext & context,
ColumnDefinition & new_column,
ExpressionExecutor & default_executor )
436340 {
436341 idx_t new_column_idx = types.size();
436342 auto new_types = types;
436343 auto row_groups = GetRowGroups();
436344 new_types.push_back(new_column.GetType());
436345 auto result = make_shared_ptr<RowGroupCollection>(info, block_manager, std::move(new_types),
436346 row_groups->GetBaseRowId(), total_rows.load(), row_group_size);
436347
436348 DataChunk dummy_chunk;
436349 Vector default_vector(new_column.GetType());
436350
436351 result->stats.InitializeAddColumn(stats, new_column.GetType());
436352 auto lock = result->stats.GetLock();
436353 auto &new_column_stats = result->stats.GetStats(*lock, new_column_idx);
436354
436355 // fill the column with its DEFAULT value, or NULL if none is specified
436356 auto new_stats = make_uniq<SegmentStatistics>(new_column.GetType());
436357 auto result_row_groups = result->GetRowGroups();
436358 for (auto &current_row_group : row_groups->Segments()) {
436359 auto new_row_group = current_row_group.AddColumn(*result, new_column, default_executor, default_vector);
436360 // merge in the statistics
436361 new_row_group->MergeIntoStatistics(new_column_idx, new_column_stats.Statistics());
436362
436363 result_row_groups->AppendSegment(std::move(new_row_group));
436364 }
436365
436366 return result;
436367}

◆ RemoveColumn()

shared_ptr< RowGroupCollection > duckdb::RowGroupCollection::RemoveColumn ( idx_t col_idx)
436369 {
436370 D_ASSERT(col_idx < types.size());
436371 auto new_types = types;
436372 auto row_groups = GetRowGroups();
436373 new_types.erase_at(col_idx);
436374
436375 auto result = make_shared_ptr<RowGroupCollection>(info, block_manager, std::move(new_types),
436376 row_groups->GetBaseRowId(), total_rows.load(), row_group_size);
436377 result->stats.InitializeRemoveColumn(stats, col_idx);
436378
436379 auto result_lock = result->stats.GetLock();
436380 result->stats.DestroyTableSample(*result_lock);
436381
436382 auto result_row_groups = result->GetRowGroups();
436383 for (auto &current_row_group : row_groups->Segments()) {
436384 auto new_row_group = current_row_group.RemoveColumn(*result, col_idx);
436385 result_row_groups->AppendSegment(std::move(new_row_group));
436386 }
436387 return result;
436388}

◆ AlterType()

shared_ptr< RowGroupCollection > duckdb::RowGroupCollection::AlterType ( ClientContext & context,
idx_t changed_idx,
const LogicalType & target_type,
vector< StorageIndex > bound_columns,
Expression & cast_expr )
436393 {
436394 D_ASSERT(changed_idx < types.size());
436395 auto new_types = types;
436396 auto row_groups = GetRowGroups();
436397 new_types[changed_idx] = target_type;
436398
436399 auto result = make_shared_ptr<RowGroupCollection>(info, block_manager, std::move(new_types),
436400 row_groups->GetBaseRowId(), total_rows.load(), row_group_size);
436401 result->stats.InitializeAlterType(stats, changed_idx, target_type);
436402
436403 vector<LogicalType> scan_types;
436404 for (idx_t i = 0; i < bound_columns.size(); i++) {
436405 if (bound_columns[i].IsRowIdColumn()) {
436406 scan_types.emplace_back(LogicalType::ROW_TYPE);
436407 } else {
436408 scan_types.push_back(types[bound_columns[i].GetPrimaryIndex()]);
436409 }
436410 }
436411 DataChunk scan_chunk;
436412 scan_chunk.Initialize(GetAllocator(), scan_types);
436413
436414 ExpressionExecutor executor(context);
436415 executor.AddExpression(cast_expr);
436416
436417 TableScanState scan_state;
436418 scan_state.Initialize(bound_columns);
436419 scan_state.table_state.Initialize(context, GetTypes());
436420 scan_state.table_state.max_row = row_groups->GetBaseRowId() + total_rows;
436421
436422 // now alter the type of the column within all of the row_groups individually
436423 auto lock = result->stats.GetLock();
436424 auto &changed_stats = result->stats.GetStats(*lock, changed_idx);
436425 auto result_row_groups = result->GetRowGroups();
436426
436427 for (auto &node : row_groups->SegmentNodes()) {
436428 auto &current_row_group = node.GetNode();
436429 auto new_row_group = current_row_group.AlterType(*result, target_type, changed_idx, executor,
436430 scan_state.table_state, node, scan_chunk);
436431 new_row_group->MergeIntoStatistics(changed_idx, changed_stats.Statistics());
436432 result_row_groups->AppendSegment(std::move(new_row_group));
436433 }
436434 return result;
436435}

◆ VerifyNewConstraint()

void duckdb::RowGroupCollection::VerifyNewConstraint ( const QueryContext & context,
DataTable & parent,
const BoundConstraint & constraint )
436438 {
436439 if (total_rows == 0) {
436440 return;
436441 }
436442
436443 // Scan the original table for NULL values.
436444 auto &not_null_constraint = constraint.Cast<BoundNotNullConstraint>();
436445 vector<LogicalType> scan_types;
436446 auto physical_index = not_null_constraint.index.index;
436447 D_ASSERT(physical_index < types.size());
436448
436449 scan_types.push_back(types[physical_index]);
436450 DataChunk scan_chunk;
436451 scan_chunk.Initialize(GetAllocator(), scan_types);
436452
436453 vector<StorageIndex> column_ids;
436454 column_ids.emplace_back(physical_index);
436455
436456 // Use SCAN_COMMITTED to scan the latest data.
436457 CreateIndexScanState state;
436459 state.Initialize(column_ids, nullptr);
436460 InitializeScan(context, state.table_state, column_ids, nullptr);
436461
436462 InitializeCreateIndexScan(state);
436463
436464 while (true) {
436465 scan_chunk.Reset();
436466 state.table_state.Scan(scan_chunk, scan_type, state.segment_lock);
436467 if (scan_chunk.size() == 0) {
436468 break;
436469 }
436470
436471 // Verify the NOT NULL constraint.
436472 if (VectorOperations::HasNull(scan_chunk.data[0], scan_chunk.size())) {
436473 auto name = parent.Columns()[physical_index].GetName();
436474 throw ConstraintException("NOT NULL constraint failed: %s.%s", info->GetTableName(), name);
436475 }
436476 }
436477}
DUCKDB_API void Reset()
Definition duckdb.cpp:116840
@ TABLE_SCAN_OMIT_PERMANENTLY_DELETED
Definition duckdb.hpp:22676

◆ SetStats()

void duckdb::RowGroupCollection::SetStats ( TableStatistics & new_stats)
436483 {
436484 stats.SetStats(new_stats);
436485}

◆ CopyStats() [1/2]

void duckdb::RowGroupCollection::CopyStats ( TableStatistics & stats)
436487 {
436488 stats.CopyStats(other_stats);
436489}

◆ CopyStats() [2/2]

unique_ptr< BaseStatistics > duckdb::RowGroupCollection::CopyStats ( const StorageIndex & column_id)
436491 {
436492 return stats.CopyStats(column_id);
436493}

◆ GetSample()

unique_ptr< BlockingSample > duckdb::RowGroupCollection::GetSample ( )
436495 {
436496 return nullptr;
436497}

◆ SetDistinct()

void duckdb::RowGroupCollection::SetDistinct ( column_t column_id,
unique_ptr< DistinctStatistics > distinct_stats )
436499 {
436500 D_ASSERT(column_id != COLUMN_IDENTIFIER_ROW_ID);
436501 auto stats_lock = stats.GetLock();
436502 stats.GetStats(*stats_lock, column_id).SetDistinct(std::move(distinct_stats));
436503}
const column_t COLUMN_IDENTIFIER_ROW_ID
Special value used to signify the ROW ID of a table.
Definition duckdb.cpp:50303

◆ GetAttached()

AttachedDatabase & duckdb::RowGroupCollection::GetAttached ( )
434572 {
434573 return GetTableInfo().GetDB();
434574}

◆ GetBlockManager()

BlockManager & duckdb::RowGroupCollection::GetBlockManager ( )
inline
50588 {
50589 return block_manager;
50590 }

◆ GetMetadataManager()

MetadataManager & duckdb::RowGroupCollection::GetMetadataManager ( )
434576 {
434577 return GetBlockManager().GetMetadataManager();
434578}

◆ GetTableInfo()

DataTableInfo & duckdb::RowGroupCollection::GetTableInfo ( )
inline
50592 {
50593 return *info;
50594 }

◆ GetAllocationSize()

idx_t duckdb::RowGroupCollection::GetAllocationSize ( ) const
inline
50596 {
50597 return allocation_size;
50598 }

◆ GetRowGroupSize()

idx_t duckdb::RowGroupCollection::GetRowGroupSize ( ) const
inline
50600 {
50601 return row_group_size;
50602 }

◆ SetAppendRequiresNewRowGroup()

void duckdb::RowGroupCollection::SetAppendRequiresNewRowGroup ( )
434620 {
434621 requires_new_row_group = true;
434622}

◆ GetSegmentCount()

idx_t duckdb::RowGroupCollection::GetSegmentCount ( )

Returns the total amount of segments - use sparingly, as this forces all segments to be loaded.

434653 {
434654 auto row_groups = GetRowGroups();
434655 return row_groups->GetSegmentCount();
434656}

◆ NextUpdateRowGroup()

optional_ptr< SegmentNode< RowGroup > > duckdb::RowGroupCollection::NextUpdateRowGroup ( RowGroupSegmentTree & row_groups,
row_t * ids,
idx_t & pos,
idx_t count ) const
private
435247 {
435248 auto row_group = row_groups.GetSegment(UnsafeNumericCast<idx_t>(ids[pos]));
435249
435250 auto &current_row_group = row_group->GetNode();
435251 auto row_start = row_group->GetRowStart();
435252 row_t base_id = UnsafeNumericCast<row_t>(
435253 row_start + ((UnsafeNumericCast<idx_t>(ids[pos]) - row_start) / STANDARD_VECTOR_SIZE * STANDARD_VECTOR_SIZE));
435254 auto max_id =
435255 MinValue<row_t>(base_id + STANDARD_VECTOR_SIZE, UnsafeNumericCast<row_t>(row_start + current_row_group.count));
435256 for (pos++; pos < count; pos++) {
435257 D_ASSERT(ids[pos] >= 0);
435258 // check if this id still belongs to this vector in this row group
435259 if (ids[pos] < base_id) {
435260 // id is before vector start -> it does not
435261 break;
435262 }
435263 if (ids[pos] >= max_id) {
435264 // id is after the maximum id in this vector -> it does not
435265 break;
435266 }
435267 }
435268 return row_group;
435269}

◆ GetRowGroups()

shared_ptr< RowGroupSegmentTree > duckdb::RowGroupCollection::GetRowGroups ( ) const
private
434580 {
434581 lock_guard<mutex> guard(row_group_pointer_lock);
434582 return owned_row_groups;
434583}
mutex row_group_pointer_lock
Lock held when accessing or modifying the owned_row_groups pointer.
Definition duckdb.hpp:50626

◆ SetRowGroups()

void duckdb::RowGroupCollection::SetRowGroups ( shared_ptr< RowGroupSegmentTree > row_groups)
private
434585 {
434586 lock_guard<mutex> guard(row_group_pointer_lock);
434587 owned_row_groups = std::move(new_row_groups);
434588}

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