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::DataTable Class Reference

DataTable represents a physical table on disk. More...

#include <duckdb.hpp>

Inheritance diagram for duckdb::DataTable:
Collaboration diagram for duckdb::DataTable:

Public Member Functions

 DataTable (AttachedDatabase &db, shared_ptr< TableIOManager > table_io_manager, const string &schema, const string &table, vector< ColumnDefinition > column_definitions_p, unique_ptr< PersistentTableData > data=nullptr)
 Constructs a new data table from an (optional) set of persistent segments.
 DataTable (ClientContext &context, DataTable &parent, ColumnDefinition &new_column, Expression &default_value)
 Constructs a DataTable as a delta on an existing data table with a newly added column.
 DataTable (ClientContext &context, DataTable &parent, idx_t removed_column)
 Constructs a DataTable as a delta on an existing data table but with one column removed.
 DataTable (ClientContext &context, DataTable &parent, idx_t changed_idx, const LogicalType &target_type, const vector< StorageIndex > &bound_columns, Expression &cast_expr)
 Constructs a DataTable as a delta on an existing data table but with one column changed type.
 DataTable (ClientContext &context, DataTable &parent, BoundConstraint &constraint)
 Constructs a DataTable as a delta on an existing data table but with one column added new constraint.
AttachedDatabase & GetAttached ()
TableIOManager & GetTableIOManager ()
bool IsTemporary () const
vector< LogicalType > GetTypes ()
 Returns a list of types of the table.
const vector< ColumnDefinition > & Columns () const
void InitializeScan (ClientContext &context, DuckTransaction &transaction, TableScanState &state, const vector< StorageIndex > &column_ids, optional_ptr< TableFilterSet > table_filters=nullptr)
idx_t MaxThreads (ClientContext &context) const
 Returns the maximum amount of threads that should be assigned to scan this data table.
void InitializeParallelScan (ClientContext &context, ParallelTableScanState &state, const vector< ColumnIndex > &column_indexes)
idx_t NextParallelScan (ClientContext &context, ParallelTableScanState &state, TableScanState &scan_state)
void Scan (DuckTransaction &transaction, DataChunk &result, TableScanState &state)
 Scans up to STANDARD_VECTOR_SIZE elements from the table starting from offset and store them in result. Offset is incremented with how many elements were returned. Returns true if all pushed down filters were executed during data fetching.
void Fetch (DuckTransaction &transaction, DataChunk &result, const vector< StorageIndex > &column_ids, const Vector &row_ids, idx_t fetch_count, ColumnFetchState &state)
 Fetch data from the specific row identifiers from the base table.
void FetchCommitted (DataChunk &result, const vector< StorageIndex > &column_ids, const Vector &row_identifiers, idx_t fetch_count, ColumnFetchState &state)
bool CanFetch (DuckTransaction &transaction, const row_t row_id)
 Returns true, if the transaction can fetch the row ID.
void InitializeLocalAppend (LocalAppendState &state, TableCatalogEntry &table, ClientContext &context, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
 Initializes appending to transaction-local storage.
void InitializeLocalStorage (LocalAppendState &state, TableCatalogEntry &table, ClientContext &context, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
 Initializes only the delete-indexes of the transaction-local storage.
void LocalAppend (LocalAppendState &state, ClientContext &context, DataChunk &chunk, bool unsafe)
 Append a DataChunk to the transaction-local storage of the table.
void FinalizeLocalAppend (LocalAppendState &state)
 Finalizes a transaction-local append.
void LocalAppend (TableCatalogEntry &table, ClientContext &context, DataChunk &chunk, const vector< unique_ptr< BoundConstraint > > &bound_constraints, Vector &row_ids, DataChunk &delete_chunk)
 Append a chunk to the transaction-local storage of this table and update the delete indexes.
void LocalAppend (TableCatalogEntry &table, ClientContext &context, DataChunk &chunk, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
 Appends to the transaction-local storage of this table.
void LocalWALAppend (TableCatalogEntry &table, ClientContext &context, DataChunk &chunk, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
 Append a chunk to the transaction-local storage of this table.
void LocalAppend (TableCatalogEntry &table, ClientContext &context, ColumnDataCollection &collection, const vector< unique_ptr< BoundConstraint > > &bound_constraints, optional_ptr< const vector< LogicalIndex > > column_ids)
 Append a column data collection with default values to the transaction-local storage of this table.
void LocalMerge (ClientContext &context, OptimisticWriteCollection &collection)
 Merge a row group collection into the transaction-local storage.
PhysicalIndex CreateOptimisticCollection (ClientContext &context, unique_ptr< OptimisticWriteCollection > collection)
 Create an optimistic row group collection for this table. Used for optimistically writing parallel appends. Returns the index into the optimistic_collections vector for newly created collection.
OptimisticWriteCollection & GetOptimisticCollection (ClientContext &context, const PhysicalIndex collection_index)
 Returns the optimistic row group collection corresponding to the index.
void ResetOptimisticCollection (ClientContext &context, const PhysicalIndex collection_index)
 Resets the optimistic row group collection corresponding to the index.
OptimisticDataWriter & GetOptimisticWriter (ClientContext &context)
 Returns the optimistic writer of the corresponding local table.
unique_ptr< TableDeleteState > InitializeDelete (TableCatalogEntry &table, ClientContext &context, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
idx_t Delete (TableDeleteState &state, ClientContext &context, Vector &row_ids, idx_t count)
 Delete the entries with the specified row identifier from the table.
unique_ptr< TableUpdateState > InitializeUpdate (TableCatalogEntry &table, ClientContext &context, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
void Update (TableUpdateState &state, ClientContext &context, Vector &row_ids, const vector< PhysicalIndex > &column_ids, DataChunk &data)
 Update the entries with the specified row identifier from the table.
void UpdateColumn (TableCatalogEntry &table, ClientContext &context, Vector &row_ids, const vector< column_t > &column_path, DataChunk &updates)
 Update a single (sub-)column along a column path The column_path vector is a path towards a column within the table i.e. if we have a table with a single column S STRUCT(A INT, B INT) and we update the validity mask of "S.B" the column path is: 0 (first column of table) -> 1 (second subcolumn of struct) -> 0 (first subcolumn of INT) This method should only be used from the WAL replay. It does not verify update constraints.
void AppendLock (DuckTransaction &transaction, TableAppendState &state)
 Fetches an append lock.
void InitializeAppend (DuckTransaction &transaction, TableAppendState &state)
 Begin appending structs to this table, obtaining necessary locks, etc.
void Append (DataChunk &chunk, TableAppendState &state)
 Append a chunk to the table using the AppendState obtained from InitializeAppend.
void FinalizeAppend (DuckTransaction &transaction, TableAppendState &state)
 Finalize an append.
void CommitAppend (transaction_t commit_id, idx_t row_start, idx_t count)
 Commit the append.
void WriteToLog (DuckTransaction &transaction, WriteAheadLog &log, idx_t row_start, idx_t count, optional_ptr< StorageCommitState > commit_state)
 Write a segment of the table to the WAL.
void RevertAppend (DuckTransaction &transaction, idx_t start_row, idx_t count)
 Revert a set of appends made by the given AppendState, used to revert appends in the event of an error during commit (e.g. because of an I/O exception).
void RevertAppendInternal (idx_t start_row)
void ScanTableSegment (DuckTransaction &transaction, idx_t start_row, idx_t count, const std::function< void(DataChunk &chunk)> &function)
void MergeStorage (RowGroupCollection &data, optional_ptr< StorageCommitState > commit_state)
 Merge a row group collection directly into this table - appending it to the end of the table without copying.
ErrorData AppendToIndexes (optional_ptr< TableIndexList > delete_indexes, DataChunk &table_chunk, DataChunk &index_chunk, const vector< StorageIndex > &mapped_column_ids, row_t row_start, const IndexAppendMode index_append_mode)
void RevertIndexAppend (TableAppendState &state, DataChunk &chunk, row_t row_start)
 Revert a previous append made to indexes in a chunk with the row ids [row_start, ..., row_start + chunk.size()].
void RevertIndexAppend (TableAppendState &state, DataChunk &chunk, Vector &row_identifiers)
 Revert a previous append made to indexes with the given row-ids.
void RemoveFromIndexes (const QueryContext &context, Vector &row_identifiers, idx_t count, IndexRemovalType removal_type, optional_idx checkpoint_id=optional_idx())
 Remove the row identifiers from all the indexes of the table.
void SetAsMainTable ()
void SetAsDropped ()
bool IsMainTable () const
bool IsRoot () const
string TableModification () const
unique_ptr< BaseStatistics > GetStatistics (ClientContext &context, const StorageIndex &column_id)
 Get statistics of a physical column within the table.
unique_ptr< BlockingSample > GetSample ()
 Get table sample.
void SetDistinct (column_t column_id, unique_ptr< DistinctStatistics > distinct_stats)
 Sets statistics of a physical column within the table.
unique_ptr< StorageLockKey > GetCheckpointLock ()
 Obtains a lock during a checkpoint operation that prevents other threads from reading this table.
void Checkpoint (TableDataWriter &writer, Serializer &serializer)
 Checkpoint the table to the specified table data writer.
void CommitDropTable ()
void CommitDropColumn (const idx_t column_index)
idx_t ColumnCount () const
idx_t GetTotalRows () const
vector< ColumnSegmentInfo > GetColumnSegmentInfo (const QueryContext &context)
bool CreateIndexScan (TableScanState &state, DataChunk &result)
 Scans the next chunk for the CREATE INDEX operator.
bool IndexNameIsUnique (const string &name)
 Returns true, if the index name is unique (i.e., no PK, UNIQUE, FK constraint has the same name) FIXME: This is only necessary until we treat all indexes as catalog entries, allowing to alter constraints.
unique_ptr< ConstraintState > InitializeConstraintState (TableCatalogEntry &table, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
 Initialize constraint verification state.
void VerifyAppendConstraints (ConstraintState &constraint_state, ClientContext &context, DataChunk &chunk, optional_ptr< LocalTableStorage > local_storage, optional_ptr< ConflictManager > manager)
 Verify constraints with a chunk from the Append containing all columns of the table.
shared_ptr< DataTableInfo > & GetDataTableInfo ()
void BindIndexes (ClientContext &context)
bool HasIndexes () const
bool HasUniqueIndexes () const
bool HasForeignKeyIndex (const vector< PhysicalIndex > &keys, ForeignKeyType type)
void SetIndexStorageInfo (vector< IndexStorageInfo > index_storage_info)
void VacuumIndexes ()
void VerifyIndexBuffers ()
void CleanupAppend (transaction_t lowest_transaction, idx_t start, idx_t count)
void Destroy ()
string GetTableName () const
void SetTableName (string new_name)
TableStorageInfo GetStorageInfo ()
idx_t GetRowGroupSize () const
void VerifyUniqueIndexes (TableIndexList &indexes, optional_ptr< LocalTableStorage > storage, DataChunk &chunk, optional_ptr< ConflictManager > manager)
 Verify any unique indexes using optional delete indexes in the local storage.
void AddIndex (const ColumnList &columns, const vector< LogicalIndex > &column_indexes, const IndexConstraintType type, IndexStorageInfo index_info)
 AddIndex initializes an index and adds it to the table's index list. It is either empty, or initialized via its index storage information.
void AddIndex (unique_ptr< Index > index)
 AddIndex moves an index to this table's index list.
vector< PartitionStatistics > GetPartitionStats (ClientContext &context)
 Returns a list of the partition stats.
Public Member Functions inherited from duckdb::enable_shared_from_this< DataTable >
shared_ptr< DataTable > shared_from_this ()

Static Public Member Functions

static ErrorData AppendToIndexes (TableIndexList &indexes, optional_ptr< TableIndexList > delete_indexes, DataChunk &table_chunk, DataChunk &index_chunk, const vector< StorageIndex > &mapped_column_ids, row_t row_start, const IndexAppendMode index_append_mode, optional_idx active_checkpoint)
 Appends a chunk with the row ids [row_start, ..., row_start + chunk.size()] to all indexes of the table. If an index is bound, it appends table_chunk. Else, it buffers index_chunk.

Public Attributes

AttachedDatabase & db
 A reference to the database instance.

Private Member Functions

void VerifyNewConstraint (LocalStorage &local_storage, DataTable &parent, const BoundConstraint &constraint)
 Verify the new added constraints against current persistent&local data.
void VerifyUpdateConstraints (ConstraintState &state, ClientContext &context, DataChunk &chunk, const vector< PhysicalIndex > &column_ids)
 Verify constraints with a chunk from the Update containing only the specified column_ids.
void VerifyDeleteConstraints (optional_ptr< LocalTableStorage > storage, TableDeleteState &state, ClientContext &context, DataChunk &chunk)
 Verify constraints with a chunk from the Delete containing all columns of the table.
void InitializeScanWithOffset (DuckTransaction &transaction, TableScanState &state, const vector< StorageIndex > &column_ids, idx_t start_row, idx_t end_row)
void RebuildIndexes ()
 Rebuild all indexes after vacuuming changed rowid's (used with vacuum_rebuild_indexes setting).
void VerifyForeignKeyConstraint (optional_ptr< LocalTableStorage > storage, const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context, DataChunk &chunk, VerifyExistenceType type)
void VerifyAppendForeignKeyConstraint (optional_ptr< LocalTableStorage > storage, const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context, DataChunk &chunk)
void VerifyDeleteForeignKeyConstraint (optional_ptr< LocalTableStorage > storage, const BoundForeignKeyConstraint &bound_foreign_key, ClientContext &context, DataChunk &chunk)

Private Attributes

shared_ptr< DataTableInfo > info
 The table info.
vector< ColumnDefinition > column_definitions
 The set of physical columns stored by this DataTable.
mutex append_lock
 Lock for appending entries to the table.
shared_ptr< RowGroupCollection > row_groups
 The row groups of the table.
atomic< DataTableVersion > version
 The version of the data table.

Additional Inherited Members

Protected Member Functions inherited from duckdb::enable_shared_from_this< DataTable >
enable_shared_from_this & operator= (enable_shared_from_this const &) noexcept

Detailed Description

DataTable represents a physical table on disk.

Constructor & Destructor Documentation

◆ DataTable() [1/5]

duckdb::DataTable::DataTable ( AttachedDatabase & db,
shared_ptr< TableIOManager > table_io_manager,
const string & schema,
const string & table,
vector< ColumnDefinition > column_definitions_p,
unique_ptr< PersistentTableData > data = nullptr )

Constructs a new data table from an (optional) set of persistent segments.

411398 : db(db), info(make_shared_ptr<DataTableInfo>(db, std::move(table_io_manager_p), schema, table)),
411399 column_definitions(std::move(column_definitions_p)), version(DataTableVersion::MAIN_TABLE) {
411400 // initialize the table with the existing data from disk, if any
411401 auto types = GetTypes();
411402 auto &io_manager = TableIOManager::Get(*this);
411403 this->row_groups = make_shared_ptr<RowGroupCollection>(info, io_manager, types, 0);
411404 if (data && data->row_group_count > 0) {
411405 this->row_groups->Initialize(*data);
411406 row_groups->SetAppendRequiresNewRowGroup();
411407 } else {
411408 this->row_groups->InitializeEmpty();
411409 D_ASSERT(row_groups->GetTotalRows() == 0);
411410 }
411411 row_groups->Verify();
411412}
vector< ColumnDefinition > column_definitions
The set of physical columns stored by this DataTable.
Definition duckdb.hpp:51254
atomic< DataTableVersion > version
The version of the data table.
Definition duckdb.hpp:51260
shared_ptr< DataTableInfo > info
The table info.
Definition duckdb.hpp:51252
AttachedDatabase & db
A reference to the database instance.
Definition duckdb.hpp:51008
shared_ptr< RowGroupCollection > row_groups
The row groups of the table.
Definition duckdb.hpp:51258
vector< LogicalType > GetTypes()
Returns a list of types of the table.
Definition duckdb.cpp:411543
static TableIOManager & Get(DataTable &table)
Obtains a reference to the TableIOManager of a specific table.
Definition duckdb.cpp:411568
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DataTable() [2/5]

duckdb::DataTable::DataTable ( ClientContext & context,
DataTable & parent,
ColumnDefinition & new_column,
Expression & default_value )

Constructs a DataTable as a delta on an existing data table with a newly added column.

411415 : db(parent.db), info(parent.info), version(DataTableVersion::MAIN_TABLE) {
411416 // add the column definitions from this DataTable
411417 for (auto &column_def : parent.column_definitions) {
411418 column_definitions.emplace_back(column_def.Copy());
411419 }
411420 column_definitions.emplace_back(new_column.Copy());
411421
411422 auto &local_storage = LocalStorage::Get(context, db);
411423
411424 ExpressionExecutor default_executor(context);
411425 default_executor.AddExpression(default_value);
411426
411427 // prevent any new tuples from being added to the parent
411428 lock_guard<mutex> parent_lock(parent.append_lock);
411429
411430 this->row_groups = parent.row_groups->AddColumn(context, new_column, default_executor);
411431
411432 // also add this column to client local storage
411433 local_storage.AddColumn(parent, *this, new_column, default_executor);
411434
411435 // this table replaces the previous table, hence the parent is no longer the root DataTable
411436 parent.version = DataTableVersion::ALTERED;
411437}
Here is the call graph for this function:

◆ DataTable() [3/5]

duckdb::DataTable::DataTable ( ClientContext & context,
DataTable & parent,
idx_t removed_column )

Constructs a DataTable as a delta on an existing data table but with one column removed.

411440 : db(parent.db), info(parent.info), version(DataTableVersion::MAIN_TABLE) {
411441 // prevent any new tuples from being added to the parent
411442 auto &local_storage = LocalStorage::Get(context, db);
411443 lock_guard<mutex> parent_lock(parent.append_lock);
411444
411445 for (auto &column_def : parent.column_definitions) {
411446 column_definitions.emplace_back(column_def.Copy());
411447 }
411448
411449 // Bind all indexes.
411450 info->BindIndexes(context);
411451
411452 // first check if there are any indexes that exist that point to the removed column
411453 for (auto &index : info->indexes.Indexes()) {
411454 for (auto &column_id : index.GetColumnIds()) {
411455 if (column_id == removed_column) {
411456 throw CatalogException("Cannot drop this column: an index depends on it!");
411457 } else if (column_id > removed_column) {
411458 throw CatalogException("Cannot drop this column: an index depends on a column after it!");
411459 }
411460 }
411461 }
411462
411463 // erase the column definitions from this DataTable
411464 D_ASSERT(removed_column < column_definitions.size());
411465 column_definitions.erase_at(removed_column);
411466
411467 storage_t storage_idx = 0;
411468 for (idx_t i = 0; i < column_definitions.size(); i++) {
411469 auto &col = column_definitions[i];
411470 col.SetOid(i);
411471 if (col.Generated()) {
411472 continue;
411473 }
411474 col.SetStorageOid(storage_idx++);
411475 }
411476
411477 // alter the row_groups and remove the column from each of them
411478 this->row_groups = parent.row_groups->RemoveColumn(removed_column);
411479
411480 // scan the original table, and fill the new column with the transformed value
411481 local_storage.DropColumn(parent, *this, removed_column);
411482
411483 // this table replaces the previous table, hence the parent is no longer the root DataTable
411484 parent.version = DataTableVersion::ALTERED;
411485}
index
idx_t storage_t
Type used for storage (column) identifiers.
Definition duckdb.hpp:261
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
Here is the call graph for this function:

◆ DataTable() [4/5]

duckdb::DataTable::DataTable ( ClientContext & context,
DataTable & parent,
idx_t changed_idx,
const LogicalType & target_type,
const vector< StorageIndex > & bound_columns,
Expression & cast_expr )

Constructs a DataTable as a delta on an existing data table but with one column changed type.

411509 : db(parent.db), info(parent.info), version(DataTableVersion::MAIN_TABLE) {
411510 auto &local_storage = LocalStorage::Get(context, db);
411511 // prevent any tuples from being added to the parent
411512 lock_guard<mutex> lock(append_lock);
411513 for (auto &column_def : parent.column_definitions) {
411514 column_definitions.emplace_back(column_def.Copy());
411515 }
411516
411517 // Bind all indexes.
411518 info->BindIndexes(context);
411519
411520 // first check if there are any indexes that exist that point to the changed column
411521 for (auto &index : info->indexes.Indexes()) {
411522 for (auto &column_id : index.GetColumnIds()) {
411523 if (column_id == changed_idx) {
411524 throw CatalogException("Cannot change the type of this column: an index depends on it!");
411525 }
411526 }
411527 }
411528
411529 // change the type in this DataTable
411530 column_definitions[changed_idx].SetType(target_type);
411531
411532 // set up the statistics for the table
411533 // the column that had its type changed will have the new statistics computed during conversion
411534 row_groups = parent.row_groups->AlterType(context, changed_idx, target_type, bound_columns, cast_expr);
411535
411536 // scan the original table, and fill the new column with the transformed value
411537 local_storage.ChangeType(parent, *this, changed_idx, target_type, bound_columns, cast_expr);
411538
411539 // this table replaces the previous table, hence the parent is no longer the root DataTable
411540 parent.version = DataTableVersion::ALTERED;
411541}
mutex append_lock
Lock for appending entries to the table.
Definition duckdb.hpp:51256
Here is the call graph for this function:

◆ DataTable() [5/5]

duckdb::DataTable::DataTable ( ClientContext & context,
DataTable & parent,
BoundConstraint & constraint )

Constructs a DataTable as a delta on an existing data table but with one column added new constraint.

411488 : db(parent.db), info(parent.info), row_groups(parent.row_groups), version(DataTableVersion::MAIN_TABLE) {
411489 // ALTER COLUMN to add a new constraint.
411490
411491 // Bind all indexes.
411492 info->BindIndexes(context);
411493
411494 auto &local_storage = LocalStorage::Get(context, db);
411495 lock_guard<mutex> parent_lock(parent.append_lock);
411496 for (auto &column_def : parent.column_definitions) {
411497 column_definitions.emplace_back(column_def.Copy());
411498 }
411499
411500 if (constraint.type != ConstraintType::UNIQUE) {
411501 VerifyNewConstraint(local_storage, parent, constraint);
411502 }
411503 local_storage.MoveStorage(parent, *this);
411504 parent.version = DataTableVersion::ALTERED;
411505}
void VerifyNewConstraint(LocalStorage &local_storage, DataTable &parent, const BoundConstraint &constraint)
Verify the new added constraints against current persistent&local data.
Definition duckdb.cpp:412140
Here is the call graph for this function:

Member Function Documentation

◆ GetAttached()

AttachedDatabase & duckdb::DataTable::GetAttached ( )
411555 {
411556 D_ASSERT(RefersToSameObject(db, info->db));
411557 return db;
411558}
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

◆ GetTableIOManager()

TableIOManager & duckdb::DataTable::GetTableIOManager ( )
411564 {
411565 return *info->table_io_manager;
411566}

◆ IsTemporary()

bool duckdb::DataTable::IsTemporary ( ) const
411551 {
411552 return info->IsTemporary();
411553}

◆ GetTypes()

vector< LogicalType > duckdb::DataTable::GetTypes ( )

Returns a list of types of the table.

411543 {
411544 vector<LogicalType> types;
411545 for (auto &it : column_definitions) {
411546 types.push_back(it.Type());
411547 }
411548 return types;
411549}
Here is the caller graph for this function:

◆ Columns()

const vector< ColumnDefinition > & duckdb::DataTable::Columns ( ) const
411560 {
411561 return column_definitions;
411562}

◆ InitializeScan()

void duckdb::DataTable::InitializeScan ( ClientContext & context,
DuckTransaction & transaction,
TableScanState & state,
const vector< StorageIndex > & column_ids,
optional_ptr< TableFilterSet > table_filters = nullptr )
411576 {
411577 auto &local_storage = LocalStorage::Get(transaction);
411578 state.Initialize(column_ids, context, table_filters);
411579 row_groups->InitializeScan(context, state.table_state, column_ids, table_filters);
411580 local_storage.InitializeScan(*this, state.local_state, table_filters);
411581}

◆ MaxThreads()

idx_t duckdb::DataTable::MaxThreads ( ClientContext & context) const

Returns the maximum amount of threads that should be assigned to scan this data table.

411601 {
411602 idx_t row_group_size = GetRowGroupSize();
411603 idx_t parallel_scan_vector_count = row_group_size / STANDARD_VECTOR_SIZE;
411604 if (ClientConfig::GetConfig(context).verify_parallelism) {
411605 parallel_scan_vector_count = 1;
411606 }
411607 idx_t parallel_scan_tuple_count = STANDARD_VECTOR_SIZE * parallel_scan_vector_count;
411608 return GetTotalRows() / parallel_scan_tuple_count + 1;
411609}

◆ InitializeParallelScan()

void duckdb::DataTable::InitializeParallelScan ( ClientContext & context,
ParallelTableScanState & state,
const vector< ColumnIndex > & column_indexes )
411612 {
411613 auto &local_storage = LocalStorage::Get(context, db);
411614 row_groups->InitializeParallelScan(state.scan_state);
411615
411616 local_storage.InitializeParallelScan(*this, state.local_state);
411617}

◆ NextParallelScan()

idx_t duckdb::DataTable::NextParallelScan ( ClientContext & context,
ParallelTableScanState & state,
TableScanState & scan_state )
411619 {
411620 if (row_groups->NextParallelScan(context, state.scan_state, scan_state.table_state)) {
411621 return scan_state.table_state.row_group->GetCount();
411622 }
411623 auto &local_storage = LocalStorage::Get(context, db);
411624 if (local_storage.NextParallelScan(context, *this, state.local_state, scan_state.local_state)) {
411625 return scan_state.local_state.row_group->GetCount();
411626 } else {
411627 // finished all scans: no more scans remaining
411628 return 0;
411629 }
411630}

◆ Scan()

void duckdb::DataTable::Scan ( DuckTransaction & transaction,
DataChunk & result,
TableScanState & state )

Scans up to STANDARD_VECTOR_SIZE elements from the table starting from offset and store them in result. Offset is incremented with how many elements were returned. Returns true if all pushed down filters were executed during data fetching.

411632 {
411633 // scan the persistent segments
411634 if (state.table_state.Scan(transaction, result)) {
411635 D_ASSERT(result.size() > 0);
411636 return;
411637 }
411638
411639 // scan the transaction-local segments
411640 auto &local_storage = LocalStorage::Get(transaction);
411641 local_storage.Scan(state.local_state, state.GetColumnIds(), result);
411642}

◆ Fetch()

void duckdb::DataTable::Fetch ( DuckTransaction & transaction,
DataChunk & result,
const vector< StorageIndex > & column_ids,
const Vector & row_ids,
idx_t fetch_count,
ColumnFetchState & state )

Fetch data from the specific row identifiers from the base table.

411817 {
411818 D_ASSERT(row_identifiers.GetVectorType() == VectorType::FLAT_VECTOR);
411819 auto row_ids = FlatVector::GetData<row_t>(row_identifiers);
411820
411821 // Quick scan to check for transaction-local row IDs (>= MAX_ROW_ID).
411822 bool has_local = false;
411823 for (idx_t i = 0; i < fetch_count; i++) {
411824 if (row_ids[i] >= MAX_ROW_ID) {
411825 has_local = true;
411826 break;
411827 }
411828 }
411829
411830 if (!has_local) {
411831 // All committed rows — fast path (common case).
411832 row_groups->Fetch(transaction, result, column_ids, row_identifiers, fetch_count, state);
411833 return;
411834 }
411835
411836 // There are local rows. Classify all row IDs to determine the split.
411837 auto &local_storage = transaction.GetLocalStorage();
411838 SelectionVector committed_sel(fetch_count);
411839 SelectionVector local_sel(fetch_count);
411840 idx_t committed_count = 0;
411841 idx_t local_count = 0;
411842 for (idx_t i = 0; i < fetch_count; i++) {
411843 if (row_ids[i] >= MAX_ROW_ID) {
411844 local_sel.set_index(local_count++, i);
411845 } else {
411846 committed_sel.set_index(committed_count++, i);
411847 }
411848 }
411849
411850 if (committed_count == 0) {
411851 // All local rows.
411852 local_storage.FetchChunk(*this, row_identifiers, fetch_count, column_ids, result, state);
411853 return;
411854 }
411855
411856 // Mixed: some rows are committed, some are local.
411857 // row_groups->Fetch silently skips local row IDs, packing committed rows at 0..committed_count-1.
411858 row_groups->Fetch(transaction, result, column_ids, row_identifiers, fetch_count, state);
411859 D_ASSERT(result.size() == committed_count);
411860
411861 // Fetch local rows into a separate chunk.
411862 auto &allocator = Allocator::Get(local_storage.GetClientContext());
411863 DataChunk local_chunk;
411864 local_chunk.Initialize(allocator, result.GetTypes());
411865 Vector local_row_ids(row_identifiers, local_sel, local_count);
411866 local_row_ids.Flatten(local_count);
411867 ColumnFetchState local_fetch_state;
411868 local_storage.FetchChunk(*this, local_row_ids, local_count, column_ids, local_chunk, local_fetch_state);
411869
411870 // Append local rows after committed rows in the result.
411871 for (idx_t col = 0; col < result.ColumnCount(); col++) {
411872 VectorOperations::Copy(local_chunk.data[col], result.data[col], local_count, 0, committed_count);
411873 }
411874 result.SetCardinality(committed_count + local_count);
411875
411876 // Build inverse permutation to restore original row order.
411877 // Current layout: [committed rows in relative order | local rows in relative order].
411878 SelectionVector inv_perm(fetch_count);
411879 for (idx_t i = 0; i < committed_count; i++) {
411880 inv_perm.set_index(committed_sel.get_index(i), i);
411881 }
411882 for (idx_t j = 0; j < local_count; j++) {
411883 inv_perm.set_index(local_sel.get_index(j), committed_count + j);
411884 }
411885 for (idx_t col = 0; col < result.ColumnCount(); col++) {
411886 result.data[col].Slice(inv_perm, fetch_count);
411887 }
411888}
DUCKDB_API void Initialize(ClientContext &context, const vector< LogicalType > &types, idx_t capacity=STANDARD_VECTOR_SIZE)
Definition duckdb.cpp:116791
vector< Vector > data
The vectors owned by the DataChunk.
Definition duckdb.hpp:11445
const row_t MAX_ROW_ID
The maximum row identifier used in tables.
Definition duckdb.cpp:50301
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FetchCommitted()

void duckdb::DataTable::FetchCommitted ( DataChunk & result,
const vector< StorageIndex > & column_ids,
const Vector & row_identifiers,
idx_t fetch_count,
ColumnFetchState & state )
411891 {
411892 TransactionData commit_transaction(MAX_TRANSACTION_ID, TRANSACTION_ID_START - 1);
411893 row_groups->Fetch(commit_transaction, result, column_ids, row_identifiers, fetch_count, state);
411894}

◆ CanFetch()

bool duckdb::DataTable::CanFetch ( DuckTransaction & transaction,
const row_t row_id )

Returns true, if the transaction can fetch the row ID.

411896 {
411897 return row_groups->CanFetch(transaction, row_id);
411898}
Here is the caller graph for this function:

◆ InitializeLocalAppend()

void duckdb::DataTable::InitializeLocalAppend ( LocalAppendState & state,
TableCatalogEntry & table,
ClientContext & context,
const vector< unique_ptr< BoundConstraint > > & bound_constraints )

Initializes appending to transaction-local storage.

412311 {
412312 if (!IsMainTable()) {
412313 throw TransactionException("Transaction conflict: attempting to insert into table \"%s\" but it has been %s by "
412314 "a different transaction",
412315 GetTableName(), TableModification());
412316 }
412317 auto &local_storage = LocalStorage::Get(context, db);
412318 local_storage.InitializeAppend(state, *this);
412319 state.constraint_state = InitializeConstraintState(table, bound_constraints);
412320}
unique_ptr< ConstraintState > InitializeConstraintState(TableCatalogEntry &table, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
Initialize constraint verification state.
Definition duckdb.cpp:412292
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializeLocalStorage()

void duckdb::DataTable::InitializeLocalStorage ( LocalAppendState & state,
TableCatalogEntry & table,
ClientContext & context,
const vector< unique_ptr< BoundConstraint > > & bound_constraints )

Initializes only the delete-indexes of the transaction-local storage.

412323 {
412324 if (!IsMainTable()) {
412325 throw TransactionException("Transaction conflict: attempting to insert into table \"%s\" but it has been %s by "
412326 "a different transaction",
412327 GetTableName(), TableModification());
412328 }
412329
412330 auto &local_storage = LocalStorage::Get(context, db);
412331 local_storage.InitializeStorage(state, *this);
412332 state.constraint_state = InitializeConstraintState(table, bound_constraints);
412333}
Here is the call graph for this function:

◆ LocalAppend() [1/4]

void duckdb::DataTable::LocalAppend ( LocalAppendState & state,
ClientContext & context,
DataChunk & chunk,
bool unsafe )

Append a DataChunk to the transaction-local storage of the table.

412335 {
412336 if (chunk.size() == 0) {
412337 return;
412338 }
412339 if (!IsMainTable()) {
412340 throw TransactionException("Transaction conflict: attempting to insert into table \"%s\" but it has been %s by "
412341 "a different transaction",
412342 GetTableName(), TableModification());
412343 }
412344 chunk.Verify();
412345
412346 // Insert any row ids into the DELETE ART and verify constraints afterward.
412347 // This happens only for the global indexes.
412348 if (!unsafe) {
412349 auto &constraint_state = *state.constraint_state;
412350 VerifyAppendConstraints(constraint_state, context, chunk, *state.storage, nullptr);
412351 }
412352
412353 // Append to the transaction-local data.
412354 auto data_table_info = GetDataTableInfo();
412355 LocalStorage::Append(state, chunk, *data_table_info);
412356}
DUCKDB_API void Verify()
Definition duckdb.cpp:117115
void VerifyAppendConstraints(ConstraintState &constraint_state, ClientContext &context, DataChunk &chunk, optional_ptr< LocalTableStorage > local_storage, optional_ptr< ConflictManager > manager)
Verify constraints with a chunk from the Append containing all columns of the table.
Definition duckdb.cpp:412231
static void Append(LocalAppendState &state, DataChunk &table_chunk, DataTableInfo &data_table_info)
Append a chunk to the local storage.
Definition duckdb.cpp:413944
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FinalizeLocalAppend()

void duckdb::DataTable::FinalizeLocalAppend ( LocalAppendState & state)

Finalizes a transaction-local append.

412366 {
412368}
static void FinalizeAppend(LocalAppendState &state)
Finish appending to the local storage.
Definition duckdb.cpp:413978
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LocalAppend() [2/4]

void duckdb::DataTable::LocalAppend ( TableCatalogEntry & table,
ClientContext & context,
DataChunk & chunk,
const vector< unique_ptr< BoundConstraint > > & bound_constraints,
Vector & row_ids,
DataChunk & delete_chunk )

Append a chunk to the transaction-local storage of this table and update the delete indexes.

412410 {
412411 LocalAppendState append_state;
412412 auto &storage = table.GetStorage();
412413 storage.InitializeLocalAppend(append_state, table, context, bound_constraints);
412414 append_state.storage->AppendToDeleteIndexes(row_ids, delete_chunk);
412415
412416 storage.LocalAppend(append_state, context, chunk, false);
412417 storage.FinalizeLocalAppend(append_state);
412418}
Here is the call graph for this function:

◆ LocalAppend() [3/4]

void duckdb::DataTable::LocalAppend ( TableCatalogEntry & table,
ClientContext & context,
DataChunk & chunk,
const vector< unique_ptr< BoundConstraint > > & bound_constraints )

Appends to the transaction-local storage of this table.

412359 {
412360 LocalAppendState append_state;
412361 InitializeLocalAppend(append_state, table, context, bound_constraints);
412362 LocalAppend(append_state, context, chunk, false);
412363 FinalizeLocalAppend(append_state);
412364}
void InitializeLocalAppend(LocalAppendState &state, TableCatalogEntry &table, ClientContext &context, const vector< unique_ptr< BoundConstraint > > &bound_constraints)
Initializes appending to transaction-local storage.
Definition duckdb.cpp:412310
void FinalizeLocalAppend(LocalAppendState &state)
Finalizes a transaction-local append.
Definition duckdb.cpp:412366
void LocalAppend(LocalAppendState &state, ClientContext &context, DataChunk &chunk, bool unsafe)
Append a DataChunk to the transaction-local storage of the table.
Definition duckdb.cpp:412335
Here is the call graph for this function:

◆ LocalWALAppend()

void duckdb::DataTable::LocalWALAppend ( TableCatalogEntry & table,
ClientContext & context,
DataChunk & chunk,
const vector< unique_ptr< BoundConstraint > > & bound_constraints )

Append a chunk to the transaction-local storage of this table.

412398 {
412399 LocalAppendState append_state;
412400 auto &storage = table.GetStorage();
412401 storage.InitializeLocalAppend(append_state, table, context, bound_constraints);
412402
412403 storage.LocalAppend(append_state, context, chunk, true);
412404 append_state.storage->index_append_mode = IndexAppendMode::INSERT_DUPLICATES;
412405 storage.FinalizeLocalAppend(append_state);
412406}
Here is the call graph for this function:

◆ LocalAppend() [4/4]

void duckdb::DataTable::LocalAppend ( TableCatalogEntry & table,
ClientContext & context,
ColumnDataCollection & collection,
const vector< unique_ptr< BoundConstraint > > & bound_constraints,
optional_ptr< const vector< LogicalIndex > > column_ids )

Append a column data collection with default values to the transaction-local storage of this table.

412422 {
412423 LocalAppendState append_state;
412424 auto &storage = table.GetStorage();
412425 storage.InitializeLocalAppend(append_state, table, context, bound_constraints);
412426
412427 if (!column_ids || column_ids->empty()) {
412428 for (auto &chunk : collection.Chunks()) {
412429 storage.LocalAppend(append_state, context, chunk, false);
412430 }
412431 storage.FinalizeLocalAppend(append_state);
412432 return;
412433 }
412434
412435 auto &column_list = table.GetColumns();
412436 map<PhysicalIndex, unique_ptr<Expression>> active_expressions;
412437 for (idx_t i = 0; i < column_ids->size(); i++) {
412438 auto &col = column_list.GetColumn((*column_ids)[i]);
412439 auto expr = make_uniq<BoundReferenceExpression>(col.Name(), col.Type(), i);
412440 active_expressions[col.Physical()] = std::move(expr);
412441 }
412442
412443 auto binder = Binder::CreateBinder(context);
412444 ConstantBinder default_binder(*binder, context, "DEFAULT value");
412445 vector<unique_ptr<Expression>> expressions;
412446 for (idx_t i = 0; i < column_list.PhysicalColumnCount(); i++) {
412447 auto expr = active_expressions.find(PhysicalIndex(i));
412448 if (expr != active_expressions.end()) {
412449 expressions.push_back(std::move(expr->second));
412450 continue;
412451 }
412452
412453 auto &col = column_list.GetColumn(PhysicalIndex(i));
412454 if (!col.HasDefaultValue()) {
412455 auto null_expr = make_uniq<BoundConstantExpression>(Value(col.Type()));
412456 expressions.push_back(std::move(null_expr));
412457 continue;
412458 }
412459
412460 auto default_copy = col.DefaultValue().Copy();
412461 default_binder.target_type = col.Type();
412462 auto bound_default = default_binder.Bind(default_copy);
412463 expressions.push_back(std::move(bound_default));
412464 }
412465
412466 ExpressionExecutor expression_executor(context, expressions);
412467 DataChunk result;
412468 result.Initialize(context, table.GetTypes());
412469
412470 for (auto &chunk : collection.Chunks()) {
412471 expression_executor.Execute(chunk, result);
412472 storage.LocalAppend(append_state, context, result, false);
412473 result.Reset();
412474 }
412475 storage.FinalizeLocalAppend(append_state);
412476}
Here is the call graph for this function:

◆ LocalMerge()

void duckdb::DataTable::LocalMerge ( ClientContext & context,
OptimisticWriteCollection & collection )

Merge a row group collection into the transaction-local storage.

412392 {
412393 auto &local_storage = LocalStorage::Get(context, db);
412394 local_storage.LocalMerge(*this, collection);
412395}
Here is the caller graph for this function:

◆ CreateOptimisticCollection()

PhysicalIndex duckdb::DataTable::CreateOptimisticCollection ( ClientContext & context,
unique_ptr< OptimisticWriteCollection > collection )

Create an optimistic row group collection for this table. Used for optimistically writing parallel appends. Returns the index into the optimistic_collections vector for newly created collection.

412371 {
412372 auto &local_storage = LocalStorage::Get(context, db);
412373 return local_storage.CreateOptimisticCollection(*this, std::move(collection));
412374}

◆ GetOptimisticCollection()

OptimisticWriteCollection & duckdb::DataTable::GetOptimisticCollection ( ClientContext & context,
const PhysicalIndex collection_index )

Returns the optimistic row group collection corresponding to the index.

412377 {
412378 auto &local_storage = LocalStorage::Get(context, db);
412379 return local_storage.GetOptimisticCollection(*this, collection_index);
412380}
Here is the caller graph for this function:

◆ ResetOptimisticCollection()

void duckdb::DataTable::ResetOptimisticCollection ( ClientContext & context,
const PhysicalIndex collection_index )

Resets the optimistic row group collection corresponding to the index.

412382 {
412383 auto &local_storage = LocalStorage::Get(context, db);
412384 local_storage.ResetOptimisticCollection(*this, collection_index);
412385}
Here is the caller graph for this function:

◆ GetOptimisticWriter()

OptimisticDataWriter & duckdb::DataTable::GetOptimisticWriter ( ClientContext & context)

Returns the optimistic writer of the corresponding local table.

412387 {
412388 auto &local_storage = LocalStorage::Get(context, db);
412389 return local_storage.GetOptimisticWriter(*this);
412390}
Here is the caller graph for this function:

◆ InitializeDelete()

unique_ptr< TableDeleteState > duckdb::DataTable::InitializeDelete ( TableCatalogEntry & table,
ClientContext & context,
const vector< unique_ptr< BoundConstraint > > & bound_constraints )
412872 {
412873 auto &transaction = DuckTransaction::Get(context, db);
412874 // Bind all indexes.
412875 info->BindIndexes(context);
412876
412877 auto binder = Binder::CreateBinder(context);
412878 vector<LogicalType> types;
412879 auto result = make_uniq<TableDeleteState>();
412880 result->has_delete_constraints = TableHasDeleteConstraints(table);
412881 if (result->has_delete_constraints) {
412882 // initialize the chunk if there are any constraints to verify
412883 for (idx_t i = 0; i < column_definitions.size(); i++) {
412884 result->col_ids.emplace_back(column_definitions[i].StorageOid());
412885 types.emplace_back(column_definitions[i].Type());
412886 }
412887 result->verify_chunk.Initialize(Allocator::Get(context), types);
412888 result->constraint_state = make_uniq<ConstraintState>(table, bound_constraints);
412889 }
412890 result->checkpoint_lock = transaction.SharedLockTable(*info);
412891 return result;
412892}

◆ Delete()

idx_t duckdb::DataTable::Delete ( TableDeleteState & state,
ClientContext & context,
Vector & row_ids,
idx_t count )

Delete the entries with the specified row identifier from the table.

412894 {
412895 D_ASSERT(row_identifiers.GetType().InternalType() == ROW_TYPE);
412896 if (count == 0) {
412897 return 0;
412898 }
412899
412900 auto &transaction = DuckTransaction::Get(context, db);
412901 auto &local_storage = LocalStorage::Get(transaction);
412902 auto storage = local_storage.GetStorage(*this);
412903
412904 row_identifiers.Flatten(count);
412905 auto ids = FlatVector::GetData<row_t>(row_identifiers);
412906
412907 idx_t pos = 0;
412908 idx_t delete_count = 0;
412909 while (pos < count) {
412910 idx_t start = pos;
412911 bool is_transaction_delete = ids[pos] >= MAX_ROW_ID;
412912 // figure out which batch of rows to delete now
412913 for (pos++; pos < count; pos++) {
412914 bool row_is_transaction_delete = ids[pos] >= MAX_ROW_ID;
412915 if (row_is_transaction_delete != is_transaction_delete) {
412916 break;
412917 }
412918 }
412919 idx_t current_offset = start;
412920 idx_t current_count = pos - start;
412921
412922 Vector offset_ids(row_identifiers, current_offset, pos);
412923
412924 // This is a transaction-local DELETE.
412925 if (is_transaction_delete) {
412926 if (state.has_delete_constraints) {
412927 // Verify any delete constraints.
412928 ColumnFetchState fetch_state;
412929 local_storage.FetchChunk(*this, offset_ids, current_count, state.col_ids, state.verify_chunk,
412930 fetch_state);
412931 VerifyDeleteConstraints(storage, state, context, state.verify_chunk);
412932 }
412933 delete_count += local_storage.Delete(*this, offset_ids, current_count);
412934 continue;
412935 }
412936
412937 // This is a regular DELETE.
412938 if (state.has_delete_constraints) {
412939 // Verify any delete constraints.
412940 ColumnFetchState fetch_state;
412941 Fetch(transaction, state.verify_chunk, state.col_ids, offset_ids, current_count, fetch_state);
412942 VerifyDeleteConstraints(storage, state, context, state.verify_chunk);
412943 }
412944 delete_count += row_groups->Delete(transaction, *this, ids + current_offset, current_count);
412945 }
412946 return delete_count;
412947}
void Fetch(DuckTransaction &transaction, DataChunk &result, const vector< StorageIndex > &column_ids, const Vector &row_ids, idx_t fetch_count, ColumnFetchState &state)
Fetch data from the specific row identifiers from the base table.
Definition duckdb.cpp:411816
void VerifyDeleteConstraints(optional_ptr< LocalTableStorage > storage, TableDeleteState &state, ClientContext &context, DataChunk &chunk)
Verify constraints with a chunk from the Delete containing all columns of the table.
Definition duckdb.cpp:412850
const PhysicalType ROW_TYPE
The PhysicalType used by the row identifiers column.
Definition duckdb.cpp:139304
Here is the call graph for this function:

◆ InitializeUpdate()

unique_ptr< TableUpdateState > duckdb::DataTable::InitializeUpdate ( TableCatalogEntry & table,
ClientContext & context,
const vector< unique_ptr< BoundConstraint > > & bound_constraints )
413038 {
413039 // Bind all indexes.
413040 info->BindIndexes(context);
413041 auto result = make_uniq<TableUpdateState>();
413042 result->constraint_state = InitializeConstraintState(table, bound_constraints);
413043 return result;
413044}

◆ Update()

void duckdb::DataTable::Update ( TableUpdateState & state,
ClientContext & context,
Vector & row_ids,
const vector< PhysicalIndex > & column_ids,
DataChunk & data )

Update the entries with the specified row identifier from the table.

413047 {
413048 D_ASSERT(row_ids.GetType().InternalType() == ROW_TYPE);
413049 D_ASSERT(column_ids.size() == updates.ColumnCount());
413050 updates.Verify();
413051
413052 auto count = updates.size();
413053 if (count == 0) {
413054 return;
413055 }
413056
413057 if (!IsMainTable()) {
413058 throw TransactionException(
413059 "Transaction conflict: attempting to update table \"%s\" but it has been %s by a different transaction",
413060 GetTableName(), TableModification());
413061 }
413062
413063 // first verify that no constraints are violated
413064 VerifyUpdateConstraints(*state.constraint_state, context, updates, column_ids);
413065
413066 // now perform the actual update
413067 Vector max_row_id_vec(Value::BIGINT(MAX_ROW_ID));
413068 Vector row_ids_slice(LogicalType::BIGINT);
413069 DataChunk updates_slice;
413070 updates_slice.InitializeEmpty(updates.GetTypes());
413071
413072 SelectionVector sel_local_update(count), sel_global_update(count);
413073 auto n_local_update = VectorOperations::GreaterThanEquals(row_ids, max_row_id_vec, nullptr, count,
413074 &sel_local_update, &sel_global_update);
413075 auto n_global_update = count - n_local_update;
413076
413077 // row id > MAX_ROW_ID? transaction-local storage
413078 if (n_local_update > 0) {
413079 updates_slice.Slice(updates, sel_local_update, n_local_update);
413080 updates_slice.Flatten();
413081 row_ids_slice.Slice(row_ids, sel_local_update, n_local_update);
413082 row_ids_slice.Flatten(n_local_update);
413083
413084 LocalStorage::Get(context, db).Update(*this, row_ids_slice, column_ids, updates_slice);
413085 }
413086
413087 // otherwise global storage
413088 if (n_global_update > 0) {
413089 auto &transaction = DuckTransaction::Get(context, db);
413090 transaction.ModifyTable(*this);
413091 updates_slice.Slice(updates, sel_global_update, n_global_update);
413092 updates_slice.Flatten();
413093 row_ids_slice.Slice(row_ids, sel_global_update, n_global_update);
413094 row_ids_slice.Flatten(n_global_update);
413095
413096 row_groups->Update(transaction, *this, FlatVector::GetData<row_t>(row_ids_slice), column_ids, updates_slice);
413097 }
413098}
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 Flatten()
Turn all the vectors from the chunk into flat vectors.
Definition duckdb.cpp:116989
void VerifyUpdateConstraints(ConstraintState &state, ClientContext &context, DataChunk &chunk, const vector< PhysicalIndex > &column_ids)
Verify constraints with a chunk from the Update containing only the specified column_ids.
Definition duckdb.cpp:412986
static DUCKDB_API Value BIGINT(int64_t value)
Create a bigint Value from a specified value.
Definition duckdb.cpp:132146
Here is the call graph for this function:

◆ UpdateColumn()

void duckdb::DataTable::UpdateColumn ( TableCatalogEntry & table,
ClientContext & context,
Vector & row_ids,
const vector< column_t > & column_path,
DataChunk & updates )

Update a single (sub-)column along a column path The column_path vector is a path towards a column within the table i.e. if we have a table with a single column S STRUCT(A INT, B INT) and we update the validity mask of "S.B" the column path is: 0 (first column of table) -> 1 (second subcolumn of struct) -> 0 (first subcolumn of INT) This method should only be used from the WAL replay. It does not verify update constraints.

413101 {
413102 D_ASSERT(row_ids.GetType().InternalType() == ROW_TYPE);
413103 D_ASSERT(updates.ColumnCount() == 1);
413104 updates.Verify();
413105 if (updates.size() == 0) {
413106 return;
413107 }
413108
413109 if (!IsMainTable()) {
413110 throw TransactionException(
413111 "Transaction conflict: attempting to update table \"%s\" but it has been %s by a different transaction",
413112 GetTableName(), TableModification());
413113 }
413114
413115 // now perform the actual update
413116 auto &transaction = DuckTransaction::Get(context, db);
413117
413118 updates.Flatten();
413119 row_ids.Flatten(updates.size());
413120 row_groups->UpdateColumn(transaction, *this, row_ids, column_path, updates);
413121}
Here is the call graph for this function:

◆ AppendLock()

void duckdb::DataTable::AppendLock ( DuckTransaction & transaction,
TableAppendState & state )

Fetches an append lock.

412478 {
412479 state.append_lock = unique_lock<mutex>(append_lock);
412480 if (!IsMainTable()) {
412481 throw TransactionException("Transaction conflict: attempting to insert into table \"%s\" but it has been %s by "
412482 "a different transaction",
412483 GetTableName(), TableModification());
412484 }
412485 state.table_lock = transaction.SharedLockTable(*info);
412486 state.row_start = NumericCast<row_t>(row_groups->GetTotalRows());
412487 state.current_row = state.row_start;
412488 auto &transaction_manager = transaction.GetTransactionManager();
412489 auto active_checkpoint = transaction_manager.GetActiveCheckpoint();
412490 if (info->AppendRequiresNewRowGroup(*row_groups, active_checkpoint)) {
412491 // there is a checkpoint active while we are appending
412492 // in this case we cannot just blindly append to the last row group, because we need to checkpoint that
412493 // always start a new row group in this case
412494 row_groups->SetAppendRequiresNewRowGroup();
412495 }
412496}
Here is the call graph for this function:

◆ InitializeAppend()

void duckdb::DataTable::InitializeAppend ( DuckTransaction & transaction,
TableAppendState & state )

Begin appending structs to this table, obtaining necessary locks, etc.

412523 {
412524 // obtain the append lock for this table
412525 if (!state.append_lock) {
412526 throw InternalException("DataTable::AppendLock should be called before DataTable::InitializeAppend");
412527 }
412528 row_groups->InitializeAppend(transaction, state);
412529}

◆ Append()

void duckdb::DataTable::Append ( DataChunk & chunk,
TableAppendState & state )

Append a chunk to the table using the AppendState obtained from InitializeAppend.

412531 {
412532 D_ASSERT(IsMainTable());
412533 row_groups->Append(chunk, state);
412534}

◆ FinalizeAppend()

void duckdb::DataTable::FinalizeAppend ( DuckTransaction & transaction,
TableAppendState & state )

Finalize an append.

412536 {
412537 row_groups->FinalizeAppend(transaction, state);
412538}

◆ CommitAppend()

void duckdb::DataTable::CommitAppend ( transaction_t commit_id,
idx_t row_start,
idx_t count )

Commit the append.

412635 {
412636 lock_guard<mutex> lock(append_lock);
412637 row_groups->CommitAppend(commit_id, row_start, count);
412638}

◆ WriteToLog()

void duckdb::DataTable::WriteToLog ( DuckTransaction & transaction,
WriteAheadLog & log,
idx_t row_start,
idx_t count,
optional_ptr< StorageCommitState > commit_state )

Write a segment of the table to the WAL.

412602 {
412603 log.WriteSetTable(info->schema, info->table);
412604 if (!commit_state) {
412605 ScanTableSegment(transaction, row_start, count, [&](DataChunk &chunk) { log.WriteInsert(chunk); });
412606 return;
412607 }
412608
412609 idx_t optimistic_count = 0;
412610 auto entry = commit_state->GetRowGroupData(*this, row_start, optimistic_count);
412611 if (!entry) {
412612 ScanTableSegment(transaction, row_start, count, [&](DataChunk &chunk) { log.WriteInsert(chunk); });
412613 return;
412614 }
412615
412616 // Optimistically write the entry.
412617 D_ASSERT(optimistic_count > 0);
412618 log.WriteRowGroupData(*entry);
412619 if (optimistic_count > count) {
412620 throw InternalException(
412621 "Optimistically written count cannot exceed actual count (got %llu, but expected count is %llu)",
412622 optimistic_count, count);
412623 }
412624
412625 // Write any remaining (non-optimistically written) rows to the WAL.
412626 row_start += optimistic_count;
412627 count -= optimistic_count;
412628 if (count == 0) {
412629 return;
412630 }
412631
412632 ScanTableSegment(transaction, row_start, count, [&](DataChunk &chunk) { log.WriteInsert(chunk); });
412633}
void log(InputArray src, OutputArray dst)

◆ RevertAppend()

void duckdb::DataTable::RevertAppend ( DuckTransaction & transaction,
idx_t start_row,
idx_t count )

Revert a set of appends made by the given AppendState, used to revert appends in the event of an error during commit (e.g. because of an I/O exception).

412646 {
412647 lock_guard<mutex> lock(append_lock);
412648 auto table_lock = transaction.SharedLockTable(*info);
412649
412650 // revert any appends to indexes
412651 if (!info->indexes.Empty()) {
412652 idx_t current_row_base = start_row;
412653 row_t row_data[STANDARD_VECTOR_SIZE];
412654 Vector row_identifiers(LogicalType::ROW_TYPE, data_ptr_cast(row_data));
412655 idx_t scan_count = MinValue<idx_t>(count, row_groups->GetTotalRows() - start_row);
412656 ScanTableSegment(transaction, start_row, scan_count, [&](DataChunk &chunk) {
412657 for (idx_t i = 0; i < chunk.size(); i++) {
412658 row_data[i] = NumericCast<row_t>(current_row_base + i);
412659 }
412660 for (auto &entry : info->indexes.IndexEntries()) {
412661 lock_guard<mutex> guard(entry.lock);
412662 auto &index = *entry.index;
412663 optional_ptr<BoundIndex> remove_index;
412664 if (entry.added_data_during_checkpoint) {
412665 remove_index = entry.added_data_during_checkpoint;
412666 } else {
412667 if (!index.IsBound()) {
412668 // We cannot add to unbound indexes, so there is no need to revert them.
412669 continue;
412670 }
412671 remove_index = index.Cast<BoundIndex>();
412672 }
412673 remove_index->Delete(chunk, row_identifiers);
412674 }
412675 current_row_base += chunk.size();
412676 });
412677 }
412678
412679#ifdef DEBUG
412680 // Verify that our index memory is stable.
412681 for (auto &index : info->indexes.Indexes()) {
412682 if (index.IsBound()) {
412683 index.Cast<BoundIndex>().VerifyBuffers();
412684 }
412685 }
412686#endif
412687
412688 // revert the data table append
412689 RevertAppendInternal(start_row);
412690}
int64_t row_t
The type used for row identifiers.
Definition duckdb.hpp:240
Here is the call graph for this function:

◆ RevertAppendInternal()

void duckdb::DataTable::RevertAppendInternal ( idx_t start_row)
412640 {
412641 D_ASSERT(IsMainTable());
412642 // revert appends made to row_groups
412643 row_groups->RevertAppendInternal(start_row);
412644}

◆ ScanTableSegment()

void duckdb::DataTable::ScanTableSegment ( DuckTransaction & transaction,
idx_t start_row,
idx_t count,
const std::function< void(DataChunk &chunk)> & function )
412541 {
412542 if (count == 0) {
412543 return;
412544 }
412545 idx_t end = row_start + count;
412546
412547 vector<StorageIndex> column_ids;
412548 vector<LogicalType> types;
412549 for (idx_t i = 0; i < this->column_definitions.size(); i++) {
412550 auto &col = this->column_definitions[i];
412551 column_ids.emplace_back(i);
412552 types.push_back(col.Type());
412553 }
412554 DataChunk chunk;
412555 chunk.Initialize(Allocator::Get(db), types);
412556
412557 CreateIndexScanState state;
412558
412559 InitializeScanWithOffset(transaction, state, column_ids, row_start, row_start + count);
412560 auto row_start_aligned =
412561 state.table_state.row_group->GetRowStart() + state.table_state.vector_index * STANDARD_VECTOR_SIZE;
412562
412563 idx_t current_row = row_start_aligned;
412564 while (current_row < end) {
412565 state.table_state.Scan(chunk, TableScanType::TABLE_SCAN_ALL_ROWS);
412566 if (chunk.size() == 0) {
412567 break;
412568 }
412569 idx_t end_row = current_row + chunk.size();
412570 // start of chunk is current_row
412571 // end of chunk is end_row
412572 // figure out if we need to write the entire chunk or just part of it
412573 idx_t chunk_start = MaxValue<idx_t>(current_row, row_start);
412574 idx_t chunk_end = MinValue<idx_t>(end_row, end);
412575 D_ASSERT(chunk_start < chunk_end);
412576 idx_t chunk_count = chunk_end - chunk_start;
412577 if (chunk_count != chunk.size()) {
412578 D_ASSERT(chunk_count <= chunk.size());
412579 // need to slice the chunk before insert
412580 idx_t start_in_chunk;
412581 if (current_row >= row_start) {
412582 start_in_chunk = 0;
412583 } else {
412584 start_in_chunk = row_start - current_row;
412585 }
412586 SelectionVector sel(start_in_chunk, chunk_count);
412587 chunk.Slice(sel, chunk_count);
412588 chunk.Verify();
412589 }
412590 function(chunk);
412591 chunk.Reset();
412592 current_row = end_row;
412593 }
412594}
DUCKDB_API void Reset()
Definition duckdb.cpp:116840
@ TABLE_SCAN_ALL_ROWS
Scan all rows, including any deleted rows. Committed updates are merged in.
Definition duckdb.hpp:22673

◆ MergeStorage()

void duckdb::DataTable::MergeStorage ( RowGroupCollection & data,
optional_ptr< StorageCommitState > commit_state )

Merge a row group collection directly into this table - appending it to the end of the table without copying.

412596 {
412597 row_groups->MergeStorage(data, this, commit_state);
412598 row_groups->Verify();
412599}

◆ AppendToIndexes() [1/2]

ErrorData duckdb::DataTable::AppendToIndexes ( TableIndexList & indexes,
optional_ptr< TableIndexList > delete_indexes,
DataChunk & table_chunk,
DataChunk & index_chunk,
const vector< StorageIndex > & mapped_column_ids,
row_t row_start,
const IndexAppendMode index_append_mode,
optional_idx active_checkpoint )
static

Appends a chunk with the row ids [row_start, ..., row_start + chunk.size()] to all indexes of the table. If an index is bound, it appends table_chunk. Else, it buffers index_chunk.

412698 {
412699 // Generate the vector of row identifiers.
412700 Vector row_ids(LogicalType::ROW_TYPE);
412701 VectorOperations::GenerateSequence(row_ids, table_chunk.size(), row_start, 1);
412702
412703 vector<reference<BoundIndex>> already_appended;
412704 bool append_failed = false;
412705
412706 // Append the entries to the indexes.
412707 ErrorData error;
412708 for (auto &entry : indexes.IndexEntries()) {
412709 lock_guard<mutex> guard(entry.lock);
412710 auto &index = *entry.index;
412711 if (!index.IsBound()) {
412712 // Buffer only the key columns, and store their mapping.
412713 auto &unbound_index = index.Cast<UnboundIndex>();
412714 unbound_index.BufferChunk(index_chunk, row_ids, mapped_column_ids, BufferedIndexReplay::INSERT_ENTRY);
412715 continue;
412716 }
412717
412718 auto &bound_index = index.Cast<BoundIndex>();
412719
412720 // Find the matching delete index.
412721 optional_ptr<BoundIndex> delete_index;
412722 if (bound_index.IsUnique()) {
412723 if (delete_indexes) {
412724 delete_index = delete_indexes->Find(bound_index.name);
412725 }
412726 }
412727 optional_ptr<BoundIndex> append_index = bound_index;
412728 optional_ptr<BoundIndex> lookup_index, lookup_delete_index;
412729 // check if there's an on-going checkpoint
412730 if (active_checkpoint.IsValid() && bound_index.SupportsDeltaIndexes()) {
412731 // there's an ongoing checkpoint - check if we need to use delta indexes or if we can write to the main
412732 // index
412733 if (!entry.last_written_checkpoint.IsValid() ||
412734 entry.last_written_checkpoint.GetIndex() != active_checkpoint.GetIndex()) {
412735 // there's an on-going checkpoint and we haven't flushed the index yet
412736 // we need to append to the "added_data_during_checkpoint" instead
412737 // create it if it does not exist
412738 if (!entry.added_data_during_checkpoint) {
412739 entry.added_data_during_checkpoint =
412740 bound_index.CreateDeltaIndex(DeltaIndexType::ADDED_DURING_CHECKPOINT);
412741 }
412742 if (bound_index.IsUnique()) {
412743 // before appending we still need to look-up in the main index to verify there are no conflicts
412744 lookup_index = bound_index;
412745 lookup_delete_index = delete_index;
412746 }
412747 append_index = entry.added_data_during_checkpoint;
412748 }
412749 }
412750
412751 try {
412752 if (lookup_index) {
412753 // if there's a look-up index - first verify we can append to that index before actually appending to
412754 // the main index
412755 IndexAppendInfo lookup_append_info;
412756 if (lookup_delete_index) {
412757 lookup_append_info.delete_indexes.push_back(*lookup_delete_index);
412758 }
412759 if (entry.removed_data_during_checkpoint) {
412760 lookup_append_info.delete_indexes.push_back(*entry.removed_data_during_checkpoint);
412761 }
412762 lookup_index->VerifyAppend(table_chunk, lookup_append_info, nullptr);
412763 }
412764
412765 // Append the mock chunk containing empty columns for non-key columns.
412766 IndexAppendInfo index_append_info(index_append_mode, delete_index);
412767 error = append_index->Append(table_chunk, row_ids, index_append_info);
412768 } catch (std::exception &ex) {
412769 error = ErrorData(ex);
412770 }
412771
412772 if (error.HasError()) {
412773 append_failed = true;
412774 break;
412775 }
412776
412777 already_appended.push_back(*append_index);
412778 }
412779
412780 if (append_failed) {
412781 // Constraint violation: remove any appended entries from previous indexes (if any).
412782 for (auto index : already_appended) {
412783 index.get().Delete(table_chunk, row_ids);
412784 }
412785 }
412786 return error;
412787}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AppendToIndexes() [2/2]

ErrorData duckdb::DataTable::AppendToIndexes ( optional_ptr< TableIndexList > delete_indexes,
DataChunk & table_chunk,
DataChunk & index_chunk,
const vector< StorageIndex > & mapped_column_ids,
row_t row_start,
const IndexAppendMode index_append_mode )
412791 {
412792 D_ASSERT(IsMainTable());
412793 auto active_checkpoint = GetAttached().GetTransactionManager().Cast<DuckTransactionManager>().GetActiveCheckpoint();
412794 auto checkpoint_id = active_checkpoint == MAX_TRANSACTION_ID ? optional_idx() : active_checkpoint;
412795 return AppendToIndexes(info->indexes, delete_indexes, table_chunk, index_chunk, mapped_column_ids, row_start,
412796 index_append_mode, checkpoint_id);
412797}
static ErrorData AppendToIndexes(TableIndexList &indexes, optional_ptr< TableIndexList > delete_indexes, DataChunk &table_chunk, DataChunk &index_chunk, const vector< StorageIndex > &mapped_column_ids, row_t row_start, const IndexAppendMode index_append_mode, optional_idx active_checkpoint)
Appends a chunk with the row ids [row_start, ..., row_start + chunk.size()] to all indexes of the tab...
Definition duckdb.cpp:412695

◆ RevertIndexAppend() [1/2]

void duckdb::DataTable::RevertIndexAppend ( TableAppendState & state,
DataChunk & chunk,
row_t row_start )

Revert a previous append made to indexes in a chunk with the row ids [row_start, ..., row_start + chunk.size()].

412799 {
412800 D_ASSERT(IsMainTable());
412801 if (info->indexes.Empty()) {
412802 return;
412803 }
412804 // first generate the vector of row identifiers
412805 Vector row_identifiers(LogicalType::ROW_TYPE);
412806 VectorOperations::GenerateSequence(row_identifiers, chunk.size(), row_start, 1);
412807
412808 // now remove the entries from the indices
412809 RevertIndexAppend(state, chunk, row_identifiers);
412810}
void RevertIndexAppend(TableAppendState &state, DataChunk &chunk, row_t row_start)
Revert a previous append made to indexes in a chunk with the row ids [row_start, ....
Definition duckdb.cpp:412799
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RevertIndexAppend() [2/2]

void duckdb::DataTable::RevertIndexAppend ( TableAppendState & state,
DataChunk & chunk,
Vector & row_identifiers )

Revert a previous append made to indexes with the given row-ids.

412812 {
412813 D_ASSERT(IsMainTable());
412814 for (auto &index : info->indexes.Indexes()) {
412815 auto &main_index = index.Cast<BoundIndex>();
412816 main_index.Delete(chunk, row_identifiers);
412817 }
412818}
Here is the call graph for this function:

◆ RemoveFromIndexes()

void duckdb::DataTable::RemoveFromIndexes ( const QueryContext & context,
Vector & row_identifiers,
idx_t count,
IndexRemovalType removal_type,
optional_idx checkpoint_id = optional_idx() )

Remove the row identifiers from all the indexes of the table.

412821 {
412822 D_ASSERT(IsMainTable());
412823 row_groups->RemoveFromIndexes(context, info->indexes, row_identifiers, count, removal_type, active_checkpoint);
412824}

◆ SetAsMainTable()

void duckdb::DataTable::SetAsMainTable ( )
inline
51142 {
51143 this->version = DataTableVersion::MAIN_TABLE;
51144 }

◆ SetAsDropped()

void duckdb::DataTable::SetAsDropped ( )
inline
51146 {
51147 this->version = DataTableVersion::DROPPED;
51148 }

◆ IsMainTable()

bool duckdb::DataTable::IsMainTable ( ) const
inline
51150 {
51151 return this->version == DataTableVersion::MAIN_TABLE;
51152 }

◆ IsRoot()

bool duckdb::DataTable::IsRoot ( ) const
inline
51153 {
51154 return IsMainTable();
51155 }

◆ TableModification()

string duckdb::DataTable::TableModification ( ) const
412297 {
412298 switch (version.load()) {
412299 case DataTableVersion::MAIN_TABLE:
412300 return "no changes";
412301 case DataTableVersion::ALTERED:
412302 return "altered";
412303 case DataTableVersion::DROPPED:
412304 return "dropped";
412305 default:
412306 throw InternalException("Unrecognized table version");
412307 }
412308}

◆ GetStatistics()

unique_ptr< BaseStatistics > duckdb::DataTable::GetStatistics ( ClientContext & context,
const StorageIndex & column_id )

Get statistics of a physical column within the table.

413126 {
413127 if (column_id.IsRowIdColumn()) {
413128 return nullptr;
413129 }
413130 return row_groups->CopyStats(column_id);
413131}

◆ GetSample()

unique_ptr< BlockingSample > duckdb::DataTable::GetSample ( )

Get table sample.

413138 {
413139 return row_groups->GetSample();
413140}

◆ SetDistinct()

void duckdb::DataTable::SetDistinct ( column_t column_id,
unique_ptr< DistinctStatistics > distinct_stats )

Sets statistics of a physical column within the table.

413133 {
413134 D_ASSERT(column_id != COLUMN_IDENTIFIER_ROW_ID);
413135 row_groups->SetDistinct(column_id, std::move(distinct_stats));
413136}
const column_t COLUMN_IDENTIFIER_ROW_ID
Special value used to signify the ROW ID of a table.
Definition duckdb.cpp:50303

◆ GetCheckpointLock()

unique_ptr< StorageLockKey > duckdb::DataTable::GetCheckpointLock ( )

Obtains a lock during a checkpoint operation that prevents other threads from reading this table.

413145 {
413146 return info->checkpoint_lock.GetExclusiveLock();
413147}

◆ Checkpoint()

void duckdb::DataTable::Checkpoint ( TableDataWriter & writer,
Serializer & serializer )

Checkpoint the table to the specified table data writer.

413149 {
413150 writer.SetRowGroupCount(info->CheckpointRowGroupCount(writer.GetCheckpointOptions()));
413151 // checkpoint each individual row group
413152 TableStatistics global_stats;
413153 row_groups->Checkpoint(writer, global_stats);
413154 row_groups->SetAppendRequiresNewRowGroup();
413155 if (writer.GetRebuildIndexes()) {
413156 RebuildIndexes();
413157 }
413158 // The row group payload data has been written. Now write:
413159 // sample
413160 // column stats
413161 // row-group pointers
413162 // table pointer
413163 // index data
413164 writer.FinalizeTable(global_stats, *info, *row_groups, serializer);
413165 row_groups->SetStats(global_stats);
413166}
void RebuildIndexes()
Rebuild all indexes after vacuuming changed rowid's (used with vacuum_rebuild_indexes setting).
Definition duckdb.cpp:411696
Here is the call graph for this function:

◆ CommitDropTable()

void duckdb::DataTable::CommitDropTable ( )
413184 {
413185 // commit a drop of this table: mark all blocks as modified, so they can be reclaimed later on
413186 row_groups->CommitDropTable();
413187
413188 // propagate dropping this table to its indexes: frees all index memory
413189 for (auto &index : info->indexes.Indexes()) {
413190 D_ASSERT(index.IsBound());
413191 index.Cast<BoundIndex>().CommitDrop();
413192 }
413193}

◆ CommitDropColumn()

void duckdb::DataTable::CommitDropColumn ( const idx_t column_index)
413168 {
413169 row_groups->CommitDropColumn(column_index);
413170}

◆ ColumnCount()

idx_t duckdb::DataTable::ColumnCount ( ) const
413176 {
413177 return column_definitions.size();
413178}

◆ GetTotalRows()

idx_t duckdb::DataTable::GetTotalRows ( ) const
413180 {
413181 return row_groups->GetTotalRows();
413182}

◆ GetColumnSegmentInfo()

vector< ColumnSegmentInfo > duckdb::DataTable::GetColumnSegmentInfo ( const QueryContext & context)
413198 {
413199 return row_groups->GetColumnSegmentInfo(context);
413200}

◆ CreateIndexScan()

bool duckdb::DataTable::CreateIndexScan ( TableScanState & state,
DataChunk & result )

Scans the next chunk for the CREATE INDEX operator.

411644 {
411645 return state.table_state.Scan(result, TableScanType::TABLE_SCAN_OMIT_PERMANENTLY_DELETED);
411646}
@ TABLE_SCAN_OMIT_PERMANENTLY_DELETED
Definition duckdb.hpp:22676

◆ IndexNameIsUnique()

bool duckdb::DataTable::IndexNameIsUnique ( const string & name)

Returns true, if the index name is unique (i.e., no PK, UNIQUE, FK constraint has the same name) FIXME: This is only necessary until we treat all indexes as catalog entries, allowing to alter constraints.

411773 {
411774 return info->indexes.NameIsUnique(name);
411775}
Here is the caller graph for this function:

◆ InitializeConstraintState()

unique_ptr< ConstraintState > duckdb::DataTable::InitializeConstraintState ( TableCatalogEntry & table,
const vector< unique_ptr< BoundConstraint > > & bound_constraints )

Initialize constraint verification state.

412293 {
412294 return make_uniq<ConstraintState>(table, bound_constraints);
412295}
Here is the caller graph for this function:

◆ VerifyAppendConstraints()

void duckdb::DataTable::VerifyAppendConstraints ( ConstraintState & constraint_state,
ClientContext & context,
DataChunk & chunk,
optional_ptr< LocalTableStorage > local_storage,
optional_ptr< ConflictManager > manager )

Verify constraints with a chunk from the Append containing all columns of the table.

412233 {
412234 auto &table = constraint_state.table;
412235 if (table.HasGeneratedColumns()) {
412236 // Verify the generated columns against the inserted values.
412237 auto binder = Binder::CreateBinder(context);
412238 physical_index_set_t bound_columns;
412239 CheckBinder generated_check_binder(*binder, context, table.name, table.GetColumns(), bound_columns);
412240 for (auto &col : table.GetColumns().Logical()) {
412241 if (!col.Generated()) {
412242 continue;
412243 }
412244 D_ASSERT(col.Type().id() != LogicalTypeId::ANY);
412245 generated_check_binder.target_type = col.Type();
412246 auto to_be_bound_expression = col.GeneratedExpression().Copy();
412247 auto bound_expression = generated_check_binder.Bind(to_be_bound_expression);
412248 VerifyGeneratedExpressionSuccess(context, table, chunk, *bound_expression, col.Oid());
412249 }
412250 }
412251
412252 if (HasUniqueIndexes()) {
412253 VerifyUniqueIndexes(info->indexes, storage, chunk, manager);
412254 }
412255
412256 auto &constraints = table.GetConstraints();
412257 for (idx_t i = 0; i < constraint_state.bound_constraints.size(); i++) {
412258 auto &base_constraint = constraints[i];
412259 auto &constraint = constraint_state.bound_constraints[i];
412260 switch (base_constraint->type) {
412261 case ConstraintType::NOT_NULL: {
412262 auto &bound_not_null = constraint->Cast<BoundNotNullConstraint>();
412263 auto &not_null = base_constraint->Cast<NotNullConstraint>();
412264 auto &col = table.GetColumns().GetColumn(LogicalIndex(not_null.index));
412265 VerifyNotNullConstraint(table, chunk.data[bound_not_null.index.index], chunk.size(), col.Name());
412266 break;
412267 }
412268 case ConstraintType::CHECK: {
412269 auto &check = base_constraint->Cast<CheckConstraint>();
412270 auto &bound_check = constraint->Cast<BoundCheckConstraint>();
412271 VerifyCheckConstraint(context, table, *bound_check.expression, chunk, check);
412272 break;
412273 }
412274 case ConstraintType::UNIQUE: {
412275 // These were handled earlier.
412276 break;
412277 }
412278 case ConstraintType::FOREIGN_KEY: {
412279 auto &bound_foreign_key = constraint->Cast<BoundForeignKeyConstraint>();
412280 if (bound_foreign_key.info.IsAppendConstraint()) {
412281 VerifyAppendForeignKeyConstraint(storage, bound_foreign_key, context, chunk);
412282 }
412283 break;
412284 }
412285 default:
412286 throw InternalException("invalid constraint type");
412287 }
412288 }
412289}
void VerifyUniqueIndexes(TableIndexList &indexes, optional_ptr< LocalTableStorage > storage, DataChunk &chunk, optional_ptr< ConflictManager > manager)
Verify any unique indexes using optional delete indexes in the local storage.
Definition duckdb.cpp:412149
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetDataTableInfo()

shared_ptr< DataTableInfo > & duckdb::DataTable::GetDataTableInfo ( )
411651 {
411652 return info;
411653}

◆ BindIndexes()

void duckdb::DataTable::BindIndexes ( ClientContext & context)
411655 {
411656 info->BindIndexes(context);
411657}

◆ HasIndexes()

bool duckdb::DataTable::HasIndexes ( ) const
411659 {
411660 return !info->indexes.Empty();
411661}

◆ HasUniqueIndexes()

bool duckdb::DataTable::HasUniqueIndexes ( ) const
411663 {
411664 if (!HasIndexes()) {
411665 return false;
411666 }
411667 for (auto &index : info->indexes.Indexes()) {
411668 if (index.IsUnique()) {
411669 return true;
411670 }
411671 }
411672 return false;
411673}

◆ HasForeignKeyIndex()

bool duckdb::DataTable::HasForeignKeyIndex ( const vector< PhysicalIndex > & keys,
ForeignKeyType type )
411679 {
411680 auto index = info->indexes.FindForeignKeyIndex(keys, type);
411681 return index != nullptr;
411682}

◆ SetIndexStorageInfo()

void duckdb::DataTable::SetIndexStorageInfo ( vector< IndexStorageInfo > index_storage_info)
411684 {
411685 info->index_storage_infos = std::move(index_storage_info);
411686}

◆ VacuumIndexes()

void duckdb::DataTable::VacuumIndexes ( )
411688 {
411689 for (auto &index : info->indexes.Indexes()) {
411690 if (index.IsBound()) {
411691 index.Cast<BoundIndex>().Vacuum();
411692 }
411693 }
411694}

◆ VerifyIndexBuffers()

void duckdb::DataTable::VerifyIndexBuffers ( )
411753 {
411754 info->VerifyIndexBuffers();
411755}

◆ CleanupAppend()

void duckdb::DataTable::CleanupAppend ( transaction_t lowest_transaction,
idx_t start,
idx_t count )
411769 {
411770 row_groups->CleanupAppend(lowest_transaction, start, count);
411771}

◆ Destroy()

void duckdb::DataTable::Destroy ( )
413172 {
413173 row_groups->Destroy();
413174}

◆ GetTableName()

string duckdb::DataTable::GetTableName ( ) const
411791 {
411792 return info->GetTableName();
411793}

◆ SetTableName()

void duckdb::DataTable::SetTableName ( string new_name)
411795 {
411796 info->SetTableName(std::move(new_name));
411797}

◆ GetStorageInfo()

TableStorageInfo duckdb::DataTable::GetStorageInfo ( )
411799 {
411800 TableStorageInfo result;
411801 result.cardinality = GetTotalRows();
411802 for (auto &index : info->indexes.Indexes()) {
411803 IndexInfo index_info;
411804 index_info.is_primary = index.IsPrimary();
411805 index_info.is_unique = index.IsUnique() || index_info.is_primary;
411806 index_info.is_foreign = index.IsForeign();
411807 index_info.column_set = index.GetColumnIdSet();
411808 result.index_info.push_back(std::move(index_info));
411809 }
411810 return result;
411811}

◆ GetRowGroupSize()

idx_t duckdb::DataTable::GetRowGroupSize ( ) const
411589 {
411590 return row_groups->GetRowGroupSize();
411591}

◆ VerifyUniqueIndexes()

void duckdb::DataTable::VerifyUniqueIndexes ( TableIndexList & indexes,
optional_ptr< LocalTableStorage > storage,
DataChunk & chunk,
optional_ptr< ConflictManager > manager )

Verify any unique indexes using optional delete indexes in the local storage.

412150 {
412151 // Verify the constraint without a conflict manager.
412152 if (!manager) {
412153 for (auto &entry : indexes.IndexEntries()) {
412154 auto &index = *entry.index;
412155 if (!index.IsUnique() || index.GetIndexType() != ART::TYPE_NAME) {
412156 continue;
412157 }
412158 D_ASSERT(index.IsBound());
412159 auto &art = index.Cast<ART>();
412160
412161 lock_guard<mutex> guard(entry.lock);
412162 IndexAppendInfo index_append_info;
412163 if (storage) {
412164 auto delete_index = storage->delete_indexes.Find(art.GetIndexName());
412165 if (delete_index) {
412166 index_append_info.delete_indexes.push_back(*delete_index);
412167 }
412168 }
412169 if (entry.removed_data_during_checkpoint) {
412170 index_append_info.delete_indexes.push_back(*entry.removed_data_during_checkpoint);
412171 }
412172 art.VerifyAppend(chunk, index_append_info, nullptr);
412173 }
412174 return;
412175 }
412176
412177 // The conflict manager is only provided for statements containing ON CONFLICT.
412178 auto &conflict_info = manager->GetConflictInfo();
412179
412180 // Find all indexes matching the conflict target.
412181 for (auto &index : indexes.Indexes()) {
412182 if (!index.IsUnique() || index.GetIndexType() != ART::TYPE_NAME) {
412183 continue;
412184 }
412185 if (!conflict_info.ConflictTargetMatches(index)) {
412186 continue;
412187 }
412188 D_ASSERT(index.IsBound());
412189 auto &art = index.Cast<ART>();
412190 if (storage) {
412191 auto delete_index = storage->delete_indexes.Find(art.GetIndexName());
412192 D_ASSERT(!delete_index || delete_index->IsBound());
412193 manager->AddIndex(art, delete_index);
412194 } else {
412195 manager->AddIndex(art, nullptr);
412196 }
412197 }
412198
412199 // Verify indexes matching the conflict target.
412200 manager->SetMode(ConflictManagerMode::SCAN);
412201 auto &matching_indexes = manager->MatchingIndexes();
412202 auto &matching_delete_indexes = manager->MatchingDeleteIndexes();
412203 for (idx_t i = 0; i < matching_indexes.size(); i++) {
412204 IndexAppendInfo index_append_info(IndexAppendMode::DEFAULT, matching_delete_indexes[i]);
412205 matching_indexes[i].get().VerifyAppend(chunk, index_append_info, *manager);
412206 }
412207
412208 // Scan the other indexes and throw, if there are any conflicts.
412209 manager->SetMode(ConflictManagerMode::THROW);
412210 for (auto &index : indexes.Indexes()) {
412211 if (!index.IsUnique() || index.GetIndexType() != ART::TYPE_NAME) {
412212 continue;
412213 }
412214 if (manager->IndexMatches(index.Cast<BoundIndex>())) {
412215 continue;
412216 }
412217 D_ASSERT(index.IsBound());
412218 auto &art = index.Cast<ART>();
412219 if (storage) {
412220 auto delete_index = storage->delete_indexes.Find(art.GetIndexName());
412221 D_ASSERT(!delete_index || delete_index->IsBound());
412222 IndexAppendInfo index_append_info(IndexAppendMode::DEFAULT, delete_index);
412223 art.VerifyAppend(chunk, index_append_info, *manager);
412224 } else {
412225 IndexAppendInfo index_append_info;
412226 art.VerifyAppend(chunk, index_append_info, *manager);
412227 }
412228 }
412229}
static constexpr const char * TYPE_NAME
Index type name for the ART.
Definition duckdb.cpp:12136
Here is the caller graph for this function:

◆ AddIndex() [1/2]

void duckdb::DataTable::AddIndex ( const ColumnList & columns,
const vector< LogicalIndex > & column_indexes,
const IndexConstraintType type,
IndexStorageInfo index_info )

AddIndex initializes an index and adds it to the table's index list. It is either empty, or initialized via its index storage information.

413206 {
413207 if (!IsMainTable()) {
413208 throw TransactionException("Transaction conflict: attempting to add an index to table \"%s\" but it has been "
413209 "%s by a different transaction",
413210 GetTableName(), TableModification());
413211 }
413212
413213 // Fetch the column types and create bound column reference expressions.
413214 vector<column_t> physical_ids;
413215 vector<unique_ptr<Expression>> expressions;
413216
413217 for (const auto column_index : column_indexes) {
413218 auto binding = ColumnBinding(0, physical_ids.size());
413219 auto &col = columns.GetColumn(column_index);
413220 auto ref = make_uniq<BoundColumnRefExpression>(col.Name(), col.Type(), binding);
413221 expressions.push_back(std::move(ref));
413222 physical_ids.push_back(col.Physical().index);
413223 }
413224
413225 // Create an ART around the expressions.
413226 auto &io_manager = TableIOManager::Get(*this);
413227 auto art = make_uniq<ART>(index_info.name, type, physical_ids, io_manager, std::move(expressions), db, nullptr,
413228 index_info);
413229 info->indexes.AddIndex(std::move(art));
413230}
Here is the call graph for this function:

◆ AddIndex() [2/2]

void duckdb::DataTable::AddIndex ( unique_ptr< Index > index)

AddIndex moves an index to this table's index list.

411675 {
411676 info->indexes.AddIndex(std::move(index));
411677}

◆ GetPartitionStats()

vector< PartitionStatistics > duckdb::DataTable::GetPartitionStats ( ClientContext & context)

Returns a list of the partition stats.

411593 {
411594 auto result = row_groups->GetPartitionStats();
411595 auto &local_storage = LocalStorage::Get(context, db);
411596 auto local_partitions = local_storage.GetPartitionStats(*this);
411597 result.insert(result.end(), local_partitions.begin(), local_partitions.end());
411598 return result;
411599}

◆ VerifyNewConstraint()

void duckdb::DataTable::VerifyNewConstraint ( LocalStorage & local_storage,
DataTable & parent,
const BoundConstraint & constraint )
private

Verify the new added constraints against current persistent&local data.

412140 {
412141 if (constraint.type != ConstraintType::NOT_NULL) {
412142 throw NotImplementedException("FIXME: ALTER COLUMN with such constraint is not supported yet");
412143 }
412144
412145 parent.row_groups->VerifyNewConstraint(local_storage.GetClientContext(), parent, constraint);
412146 local_storage.VerifyNewConstraint(parent, constraint);
412147}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ VerifyUpdateConstraints()

void duckdb::DataTable::VerifyUpdateConstraints ( ConstraintState & state,
ClientContext & context,
DataChunk & chunk,
const vector< PhysicalIndex > & column_ids )
private

Verify constraints with a chunk from the Update containing only the specified column_ids.

412987 {
412988 auto &table = state.table;
412989 auto &constraints = table.GetConstraints();
412990 auto &bound_constraints = state.bound_constraints;
412991 for (idx_t constr_idx = 0; constr_idx < bound_constraints.size(); constr_idx++) {
412992 auto &base_constraint = constraints[constr_idx];
412993 auto &constraint = bound_constraints[constr_idx];
412994 switch (constraint->type) {
412995 case ConstraintType::NOT_NULL: {
412996 auto &bound_not_null = constraint->Cast<BoundNotNullConstraint>();
412997 auto &not_null = base_constraint->Cast<NotNullConstraint>();
412998 // check if the constraint is in the list of column_ids
412999 for (idx_t col_idx = 0; col_idx < column_ids.size(); col_idx++) {
413000 if (column_ids[col_idx] == bound_not_null.index) {
413001 // found the column id: check the data in
413002 auto &col = table.GetColumn(LogicalIndex(not_null.index));
413003 VerifyNotNullConstraint(table, chunk.data[col_idx], chunk.size(), col.Name());
413004 break;
413005 }
413006 }
413007 break;
413008 }
413009 case ConstraintType::CHECK: {
413010 auto &check = base_constraint->Cast<CheckConstraint>();
413011 auto &bound_check = constraint->Cast<BoundCheckConstraint>();
413012
413013 DataChunk mock_chunk;
413014 if (CreateMockChunk(table, column_ids, bound_check.bound_columns, chunk, mock_chunk)) {
413015 VerifyCheckConstraint(context, table, *bound_check.expression, mock_chunk, check);
413016 }
413017 break;
413018 }
413019 case ConstraintType::UNIQUE:
413020 case ConstraintType::FOREIGN_KEY:
413021 break;
413022 default:
413023 throw NotImplementedException("Constraint type not implemented!");
413024 }
413025 }
413026
413027#ifdef DEBUG
413028 // Ensure that we never call UPDATE for indexed columns.
413029 // Instead, we must rewrite these updates into DELETE + INSERT.
413030 for (auto &index : info->indexes.Indexes()) {
413031 D_ASSERT(index.IsBound());
413032 D_ASSERT(!index.Cast<BoundIndex>().IndexIsUpdated(column_ids));
413033 }
413034#endif
413035}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ VerifyDeleteConstraints()

void duckdb::DataTable::VerifyDeleteConstraints ( optional_ptr< LocalTableStorage > storage,
TableDeleteState & state,
ClientContext & context,
DataChunk & chunk )
private

Verify constraints with a chunk from the Delete containing all columns of the table.

412851 {
412852 for (auto &constraint : state.constraint_state->bound_constraints) {
412853 switch (constraint->type) {
412854 case ConstraintType::NOT_NULL:
412855 case ConstraintType::CHECK:
412856 case ConstraintType::UNIQUE:
412857 break;
412858 case ConstraintType::FOREIGN_KEY: {
412859 auto &bound_foreign_key = constraint->Cast<BoundForeignKeyConstraint>();
412860 if (bound_foreign_key.info.IsDeleteConstraint()) {
412861 VerifyDeleteForeignKeyConstraint(storage, bound_foreign_key, context, chunk);
412862 }
412863 break;
412864 }
412865 default:
412866 throw NotImplementedException("Constraint type not implemented!");
412867 }
412868 }
412869}
Here is the caller graph for this function:

◆ InitializeScanWithOffset()

void duckdb::DataTable::InitializeScanWithOffset ( DuckTransaction & transaction,
TableScanState & state,
const vector< StorageIndex > & column_ids,
idx_t start_row,
idx_t end_row )
private
411584 {
411585 state.Initialize(column_ids);
411586 row_groups->InitializeScanWithOffset(QueryContext(), state.table_state, column_ids, start_row, end_row);
411587}

◆ RebuildIndexes()

void duckdb::DataTable::RebuildIndexes ( )
private

Rebuild all indexes after vacuuming changed rowid's (used with vacuum_rebuild_indexes setting).

411696 {
411697 auto &indexes = info->indexes;
411698 auto &types = row_groups->GetTypes();
411699
411700 for (auto &index : indexes.Indexes()) {
411701 if (!index.IsBound()) {
411702 throw InternalException("RebuildIndexes expects all indexes to be bound during checkpoint");
411703 }
411704 auto &bound_index = index.Cast<BoundIndex>();
411705 bound_index.CommitDrop();
411706
411707 auto &col_ids = bound_index.GetColumnIds();
411708
411709 vector<StorageIndex> scan_column_ids;
411710 vector<LogicalType> scan_types;
411711 for (auto col_id : col_ids) {
411712 scan_column_ids.emplace_back(col_id);
411713 scan_types.push_back(types[col_id]);
411714 }
411715 scan_column_ids.emplace_back(COLUMN_IDENTIFIER_ROW_ID);
411716 scan_types.push_back(LogicalType::ROW_TYPE);
411717
411718 DataChunk scan_chunk;
411719 scan_chunk.Initialize(Allocator::Get(db), scan_types);
411720
411721 CreateIndexScanState state;
411723 state.Initialize(scan_column_ids, nullptr);
411724 QueryContext context;
411725 row_groups->InitializeScan(context, state.table_state, scan_column_ids, nullptr);
411726 row_groups->InitializeCreateIndexScan(state);
411727
411728 DataChunk table_chunk;
411729 table_chunk.InitializeEmpty(types);
411730
411731 while (true) {
411732 scan_chunk.Reset();
411733 state.table_state.Scan(scan_chunk, scan_type, state.segment_lock);
411734 if (scan_chunk.size() == 0) {
411735 break;
411736 }
411737 for (idx_t i = 0; i < col_ids.size(); i++) {
411738 table_chunk.data[col_ids[i]].Reference(scan_chunk.data[i]);
411739 }
411740 table_chunk.SetCardinality(scan_chunk);
411741 Vector &row_ids = scan_chunk.data[col_ids.size()];
411742
411743 auto error = bound_index.Append(table_chunk, row_ids);
411744 if (error.HasError()) {
411745 throw InternalException("Failed to rebuild index '%s' after vacuum: %s", bound_index.GetIndexName(),
411746 error.Message());
411747 }
411748 }
411749 bound_index.Verify();
411750 }
411751}
@ TABLE_SCAN_COMMITTED_ROWS
Scan the latest committed rows.
Definition duckdb.hpp:22678
Here is the call graph for this function:
Here is the caller graph for this function:

◆ VerifyForeignKeyConstraint()

void duckdb::DataTable::VerifyForeignKeyConstraint ( optional_ptr< LocalTableStorage > storage,
const BoundForeignKeyConstraint & bound_foreign_key,
ClientContext & context,
DataChunk & chunk,
VerifyExistenceType type )
private
412001 {
412002 reference<const vector<PhysicalIndex>> src_keys_ptr = bound_foreign_key.info.fk_keys;
412003 reference<const vector<PhysicalIndex>> dst_keys_ptr = bound_foreign_key.info.pk_keys;
412004
412005 auto is_append = IsAppend(verify_type);
412006 if (!is_append) {
412007 src_keys_ptr = bound_foreign_key.info.pk_keys;
412008 dst_keys_ptr = bound_foreign_key.info.fk_keys;
412009 }
412010
412011 // Get the column types in their physical order.
412012 auto &table_entry = Catalog::GetEntry<TableCatalogEntry>(context, db.GetName(), bound_foreign_key.info.schema,
412013 bound_foreign_key.info.table);
412014 vector<LogicalType> types;
412015 for (auto &col : table_entry.GetColumns().Physical()) {
412016 types.emplace_back(col.Type());
412017 }
412018
412019 // Create the data chunk that has to be verified.
412020 DataChunk dst_chunk;
412021 dst_chunk.InitializeEmpty(types);
412022 for (idx_t i = 0; i < src_keys_ptr.get().size(); i++) {
412023 auto &src_chunk = chunk.data[src_keys_ptr.get()[i].index];
412024 dst_chunk.data[dst_keys_ptr.get()[i].index].Reference(src_chunk);
412025 }
412026
412027 auto count = chunk.size();
412028 dst_chunk.SetCardinality(count);
412029 if (count <= 0) {
412030 return;
412031 }
412032
412033 // Record conflicts instead of throwing immediately.
412034 unordered_set<column_t> empty_column_list;
412035 ConflictInfo empty_conflict_info(empty_column_list, false);
412036
412037 ConflictManager global_conflict_manager(verify_type, count, &empty_conflict_info);
412038 global_conflict_manager.SetMode(ConflictManagerMode::SCAN);
412039 ConflictManager local_conflict_manager(verify_type, count, &empty_conflict_info);
412040 local_conflict_manager.SetMode(ConflictManagerMode::SCAN);
412041
412042 // Global constraint verification.
412043 auto &data_table = table_entry.GetStorage();
412044 data_table.info->indexes.VerifyForeignKey(storage, dst_keys_ptr, dst_chunk, global_conflict_manager);
412045
412046 // Check if we can insert the chunk into the local storage.
412047 auto &local_storage = LocalStorage::Get(context, db);
412048 bool local_error = false;
412049 auto local_verification = local_storage.Find(data_table);
412050
412051 // Local constraint verification.
412052 if (local_verification) {
412053 auto &local_indexes = local_storage.GetIndexes(context, data_table);
412054 local_indexes.VerifyForeignKey(storage, dst_keys_ptr, dst_chunk, local_conflict_manager);
412055 local_error = IsForeignKeyConstraintError(local_conflict_manager, is_append, count);
412056 }
412057 // Global constraint verification.
412058 auto global_error = IsForeignKeyConstraintError(global_conflict_manager, is_append, count);
412059
412060 // No constraint violation.
412061 if (!global_error && !local_error) {
412062 return;
412063 }
412064
412065 // Either a global or local error occurred.
412066 // We construct the error message and throw.
412067 optional_ptr<IndexEntry> index_entry;
412068 optional_ptr<IndexEntry> transaction_index_entry;
412069 auto fk_type = is_append ? ForeignKeyType::FK_TYPE_PRIMARY_KEY_TABLE : ForeignKeyType::FK_TYPE_FOREIGN_KEY_TABLE;
412070
412071 // Check whether we can insert into the foreign key table, or delete from the reference table.
412072 index_entry = data_table.info->indexes.FindForeignKeyIndex(dst_keys_ptr, fk_type);
412073 if (!local_verification) {
412074 auto conflict = LocateErrorIndex(global_conflict_manager, is_append, count);
412075 auto message = ConstructForeignKeyError(conflict, is_append, *index_entry->index, dst_chunk);
412076 throw ConstraintException(message);
412077 }
412078
412079 auto &transact_index = local_storage.GetIndexes(context, data_table);
412080 transaction_index_entry = transact_index.FindForeignKeyIndex(dst_keys_ptr, fk_type);
412081
412082 if (local_error && global_error && is_append) {
412083 // For appends, we throw if the foreign key neither exists in the transaction nor the local storage.
412084 optional_idx conflict;
412085 auto global_conflicts = global_conflict_manager.HasConflicts();
412086 auto local_conflicts = local_conflict_manager.HasConflicts();
412087 if (!global_conflicts && !local_conflicts) {
412088 conflict = 0;
412089 } else if (!global_conflicts && local_conflicts) {
412090 conflict = local_conflict_manager.GetFirstInvalidIndex(count);
412091 } else if (global_conflicts && !local_conflicts) {
412092 conflict = global_conflict_manager.GetFirstInvalidIndex(count);
412093 } else {
412094 auto &global_validity = global_conflict_manager.GetFirstValidity();
412095 auto &local_validity = local_conflict_manager.GetFirstValidity();
412096 for (idx_t i = 0; i < count; i++) {
412097 auto global_match = global_validity.RowIsValid(i);
412098 auto local_match = local_validity.RowIsValid(i);
412099 if (!global_match && !local_match) {
412100 conflict = i;
412101 break;
412102 }
412103 }
412104 }
412105
412106 if (!conflict.IsValid()) {
412107 // We don't throw, every value was present in either regular or transaction storage
412108 return;
412109 }
412110 auto message = ConstructForeignKeyError(conflict, true, *index_entry->index, dst_chunk);
412111 throw ConstraintException(message);
412112 }
412113
412114 if (!is_append) {
412115 if (global_error) {
412116 auto conflict = LocateErrorIndex(global_conflict_manager, false, count);
412117 auto message = ConstructForeignKeyError(conflict, false, *index_entry->index, dst_chunk);
412118 throw ConstraintException(message);
412119 }
412120
412121 D_ASSERT(local_conflict_manager.HasConflicts());
412122 auto conflict = LocateErrorIndex(local_conflict_manager, false, count);
412123 auto message = ConstructForeignKeyError(conflict, false, *transaction_index_entry->index, dst_chunk);
412124 throw ConstraintException(message);
412125 }
412126}
DUCKDB_API optional_ptr< CatalogEntry > GetEntry(ClientContext &context, const string &schema, const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found)
Gets the "schema.name" entry of the specified type, if entry does not exist behavior depends on OnEnt...
Definition duckdb.cpp:8156
GOpaque< Size > size(const GMat &src)

◆ VerifyAppendForeignKeyConstraint()

void duckdb::DataTable::VerifyAppendForeignKeyConstraint ( optional_ptr< LocalTableStorage > storage,
const BoundForeignKeyConstraint & bound_foreign_key,
ClientContext & context,
DataChunk & chunk )
private
412130 {
412131 VerifyForeignKeyConstraint(storage, bound_foreign_key, context, chunk, VerifyExistenceType::APPEND_FK);
412132}

◆ VerifyDeleteForeignKeyConstraint()

void duckdb::DataTable::VerifyDeleteForeignKeyConstraint ( optional_ptr< LocalTableStorage > storage,
const BoundForeignKeyConstraint & bound_foreign_key,
ClientContext & context,
DataChunk & chunk )
private
412136 {
412137 VerifyForeignKeyConstraint(storage, bound_foreign_key, context, chunk, VerifyExistenceType::DELETE_FK);
412138}

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