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

Stores the database in a single file. More...

Inheritance diagram for duckdb::SingleFileStorageManager:
Collaboration diagram for duckdb::SingleFileStorageManager:

Public Member Functions

 SingleFileStorageManager (AttachedDatabase &db, string path, AttachOptions &options)
bool AutomaticCheckpoint (idx_t estimated_wal_bytes) override
unique_ptr< StorageCommitState > GenStorageCommitState (WriteAheadLog &wal) override
bool IsCheckpointClean (MetaBlockPointer checkpoint_id) override
void CreateCheckpoint (QueryContext context, CheckpointOptions options) override
DatabaseSize GetDatabaseSize () override
vector< MetadataBlockInfo > GetMetadataInfo () override
shared_ptr< TableIOManager > GetTableIOManager (BoundCreateTableInfo *info) override
BlockManager & GetBlockManager () override
void Destroy () override
Public Member Functions inherited from duckdb::StorageManager
 StorageManager (AttachedDatabase &db, string path, AttachOptions &options)
void Initialize (QueryContext context)
DatabaseInstance & GetDatabase ()
AttachedDatabase & GetAttached () const
idx_t GetWALSize ()
 Gets the size of the WAL, or zero, if there is no WAL.
bool HasWAL () const
void AddWALSize (idx_t size)
void SetWALSize (idx_t size)
idx_t GetWALEntriesCount () const
 Gets the number of WAL entries since last checkpoint.
void ResetWALEntriesCount ()
void IncrementWALEntriesCount ()
optional_ptr< WriteAheadLog > GetWAL ()
 Gets the WAL of the StorageManager, or nullptr, if there is no WAL.
bool WALStartCheckpoint (MetaBlockPointer meta_block, CheckpointOptions &options)
 Write that we started a checkpoint to the WAL if there is one - returns whether or not there is a WAL.
void WALFinishCheckpoint (lock_guard< mutex > &wal_lock)
 Finishes a checkpoint.
unique_ptr< lock_guard< mutex > > GetWALLock ()
string GetDBPath () const
 Returns the database file path.
bool IsLoaded () const
string GetWALPath (const string &suffix=".wal")
 The path to the WAL, derived from the database file path.
string GetCheckpointWALPath ()
 The path to the WAL that is used while a checkpoint is running.
string GetRecoveryWALPath ()
 The path to the WAL that is used while recovering from a crash involving the checkpoint WAL.
bool InMemory () const
void SetStorageVersion (idx_t version)
bool HasStorageVersion () const
idx_t GetStorageVersion () const
bool CompressionIsEnabled () const
EncryptionTypes::CipherType GetCipher () const
void SetCipher (EncryptionTypes::CipherType cipher_p)
void SetEncryptionVersion (EncryptionTypes::EncryptionVersion version)
bool IsEncrypted () const
EncryptionTypes::EncryptionVersion GetEncryptionVersion () const
template<class TARGET>
TARGET & Cast ()
template<class TARGET>
const TARGET & Cast () const

Public Attributes

unique_ptr< BlockManager > block_manager
 The BlockManager to read from and write to blocks, both for the metadata and the data itself.
unique_ptr< TableIOManager > table_io_manager
 The table I/O manager.

Protected Member Functions

void LoadDatabase (QueryContext context) override
unique_ptr< CheckpointWriter > CreateCheckpointWriter (QueryContext context, CheckpointOptions options)

Additional Inherited Members

Static Public Member Functions inherited from duckdb::StorageManager
static StorageManager & Get (AttachedDatabase &db)
static StorageManager & Get (Catalog &catalog)
Protected Attributes inherited from duckdb::StorageManager
AttachedDatabase & db
 The attached database managed by this storage manager.
string path
 The path of the database.
string wal_path
 The WAL path.
unique_ptr< WriteAheadLog > wal
 The WriteAheadLog of the storage manager.
mutex wal_lock
 Mutex used to control writes to the WAL.
bool read_only
 Whether or not the database is opened in read-only mode.
bool load_complete = false
optional_idx storage_version
 The serialization compatibility version when reading and writing from this database.
atomic< idx_t > wal_size
atomic< idx_t > wal_entries_count
StorageOptions storage_options
 Storage options passed in through configuration.

Detailed Description

Stores the database in a single file.

Constructor & Destructor Documentation

◆ SingleFileStorageManager()

duckdb::SingleFileStorageManager::SingleFileStorageManager ( AttachedDatabase & db,
string path,
AttachOptions & options )
426537 : StorageManager(db, std::move(path), options) {
426538}
AttachedDatabase & db
The attached database managed by this storage manager.
Definition duckdb.cpp:11205
string path
The path of the database.
Definition duckdb.cpp:11207

Member Function Documentation

◆ AutomaticCheckpoint()

bool duckdb::SingleFileStorageManager::AutomaticCheckpoint ( idx_t estimated_wal_bytes)
overridevirtual

Implements duckdb::StorageManager.

426948 {
426949 auto &config = DBConfig::Get(db).options;
426950
426951 // Check size-based threshold
426952 auto initial_size = NumericCast<idx_t>(GetWALSize());
426953 idx_t expected_wal_size = initial_size + estimated_wal_bytes;
426954 if (expected_wal_size > config.checkpoint_wal_size) {
426955 return true;
426956 }
426957
426958 // Check entry-based threshold (if enabled)
426959 auto entry_limit = Settings::Get<WalAutocheckpointEntriesSetting>(DBConfig::Get(db));
426960 if (entry_limit > 0 && GetWALEntriesCount() >= entry_limit) {
426961 return true;
426962 }
426963
426964 return false;
426965}
idx_t GetWALEntriesCount() const
Gets the number of WAL entries since last checkpoint.
Definition duckdb.cpp:426361
idx_t GetWALSize()
Gets the size of the WAL, or zero, if there is no WAL.
Definition duckdb.cpp:426349
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ GenStorageCommitState()

unique_ptr< StorageCommitState > duckdb::SingleFileStorageManager::GenStorageCommitState ( WriteAheadLog & wal)
overridevirtual

Implements duckdb::StorageManager.

426837 {
426838 return make_uniq<SingleFileStorageCommitState>(*this, wal);
426839}
unique_ptr< WriteAheadLog > wal
The WriteAheadLog of the storage manager.
Definition duckdb.cpp:11211

◆ IsCheckpointClean()

bool duckdb::SingleFileStorageManager::IsCheckpointClean ( MetaBlockPointer checkpoint_id)
overridevirtual

Implements duckdb::StorageManager.

426841 {
426842 return block_manager->IsRootBlock(checkpoint_id);
426843}
unique_ptr< BlockManager > block_manager
The BlockManager to read from and write to blocks, both for the metadata and the data itself.
Definition duckdb.cpp:11248

◆ CreateCheckpoint()

void duckdb::SingleFileStorageManager::CreateCheckpoint ( QueryContext context,
CheckpointOptions options )
overridevirtual

Implements duckdb::StorageManager.

426853 {
426854 if (read_only || !load_complete) {
426855 return;
426856 }
426857 unique_ptr<StorageLockKey> vacuum_lock;
426858 if (options.type != CheckpointType::CONCURRENT_CHECKPOINT) {
426859 auto &transaction_manager = GetAttached().GetTransactionManager().Cast<DuckTransactionManager>();
426860 vacuum_lock = transaction_manager.TryGetVacuumLock();
426861 if (!vacuum_lock) {
426862 if (options.type == CheckpointType::FULL_CHECKPOINT) {
426864 } else {
426865 // nothing to do
426866 return;
426867 }
426868 }
426869 }
426870
426871 if (db.GetStorageExtension()) {
426872 db.GetStorageExtension()->OnCheckpointStart(db, options);
426873 }
426874
426875 auto &config = DBConfig::Get(db);
426876 // We only need to checkpoint if there is anything in the WAL.
426877 auto wal_size = GetWALSize();
426878 if (wal_size > 0 || config.options.force_checkpoint || options.action == CheckpointAction::ALWAYS_CHECKPOINT) {
426879 try {
426880 // Start timing the checkpoint.
426881 auto client_context = context.GetClientContext();
426882 ActiveTimer profiler;
426883 if (client_context) {
426884 profiler = client_context->client_data->profiler->StartTimer(MetricType::CHECKPOINT_LATENCY);
426885 }
426886
426887 // Write the checkpoint.
426888 auto checkpointer = CreateCheckpointWriter(context, options);
426889 checkpointer->CreateCheckpoint();
426890
426891 } catch (std::exception &ex) {
426892 ErrorData error(ex);
426893 throw FatalException("Failed to create checkpoint because of error: %s", error.Message());
426894 }
426895 }
426896
426897 if (db.GetStorageExtension()) {
426898 db.GetStorageExtension()->OnCheckpointEnd(db, options);
426899 }
426900}
atomic< idx_t > wal_size
Definition duckdb.cpp:11223
bool load_complete
Definition duckdb.cpp:11218
bool read_only
Whether or not the database is opened in read-only mode.
Definition duckdb.cpp:11215
@ CONCURRENT_CHECKPOINT
Definition duckdb.hpp:23135
@ FULL_CHECKPOINT
Definition duckdb.hpp:23132
@ ALWAYS_CHECKPOINT
Always checkpoint regardless of whether or not there is data in the WAL to flush.
Definition duckdb.hpp:23126

◆ GetDatabaseSize()

DatabaseSize duckdb::SingleFileStorageManager::GetDatabaseSize ( )
overridevirtual

Implements duckdb::StorageManager.

426929 {
426930 // All members default to zero
426931 DatabaseSize ds;
426932 if (!InMemory()) {
426933 ds.total_blocks = block_manager->TotalBlocks();
426934 ds.block_size = block_manager->GetBlockAllocSize();
426935 ds.free_blocks = block_manager->FreeBlocks();
426936 ds.used_blocks = ds.total_blocks - ds.free_blocks;
426937 ds.bytes = (ds.total_blocks * ds.block_size);
426938 ds.wal_size = NumericCast<idx_t>(GetWALSize());
426939 }
426940 return ds;
426941}

◆ GetMetadataInfo()

vector< MetadataBlockInfo > duckdb::SingleFileStorageManager::GetMetadataInfo ( )
overridevirtual

Implements duckdb::StorageManager.

426943 {
426944 auto &metadata_manager = block_manager->GetMetadataManager();
426945 return metadata_manager.GetMetadataInfo();
426946}

◆ GetTableIOManager()

shared_ptr< TableIOManager > duckdb::SingleFileStorageManager::GetTableIOManager ( BoundCreateTableInfo * info)
overridevirtual

Implements duckdb::StorageManager.

426967 {
426968 // This is an unmanaged reference. No ref/deref overhead. Lifetime of the
426969 // TableIoManager follows lifetime of the StorageManager (this).
426970 return shared_ptr<TableIOManager>(shared_ptr<char>(nullptr), table_io_manager.get());
426971}
unique_ptr< TableIOManager > table_io_manager
The table I/O manager.
Definition duckdb.cpp:11250

◆ GetBlockManager()

BlockManager & duckdb::SingleFileStorageManager::GetBlockManager ( )
overridevirtual

Implements duckdb::StorageManager.

426973 {
426974 return *block_manager;
426975}

◆ Destroy()

void duckdb::SingleFileStorageManager::Destroy ( )
overridevirtual

Reimplemented from duckdb::StorageManager.

426902 {
426903 if (!load_complete) {
426904 return;
426905 }
426906 vector<reference<SchemaCatalogEntry>> schemas;
426907 // we scan the set of committed schemas
426908 auto &catalog = Catalog::GetCatalog(db).Cast<DuckCatalog>();
426909 catalog.ScanSchemas([&](SchemaCatalogEntry &entry) { schemas.push_back(entry); });
426910
426911 vector<reference<DuckTableEntry>> tables;
426912 for (auto &schema : schemas) {
426913 schema.get().Scan(CatalogType::TABLE_ENTRY, [&](CatalogEntry &entry) {
426914 if (entry.internal) {
426915 return;
426916 }
426917 if (entry.type == CatalogType::TABLE_ENTRY) {
426918 tables.push_back(entry.Cast<DuckTableEntry>());
426919 }
426920 });
426921 }
426922
426923 for (auto &table : tables) {
426924 auto &data_table = table.get().GetStorage();
426925 data_table.Destroy();
426926 }
426927}
static DUCKDB_API Catalog & GetCatalog(ClientContext &context, const string &catalog_name)
Get the specified Catalog from the ClientContext.
Definition duckdb.cpp:7211

◆ LoadDatabase()

void duckdb::SingleFileStorageManager::LoadDatabase ( QueryContext context)
overrideprotectedvirtual

set the block header size for the encrypted database files set the database to encrypted update the storage version to 1.4.0

Implements duckdb::StorageManager.

426540 {
426541 if (InMemory()) {
426542 block_manager = make_uniq<InMemoryBlockManager>(BufferManager::GetBufferManager(db), DEFAULT_BLOCK_ALLOC_SIZE,
426543 DEFAULT_BLOCK_HEADER_STORAGE_SIZE);
426544 table_io_manager = make_uniq<SingleFileTableIOManager>(*block_manager, DEFAULT_ROW_GROUP_SIZE);
426545 // in-memory databases can always use the latest storage version
426546 storage_version = GetSerializationVersion("latest");
426547 load_complete = true;
426548 return;
426549 }
426550 if (storage_options.compress_in_memory != CompressInMemory::AUTOMATIC) {
426551 throw InvalidInputException("COMPRESS can only be set for in-memory databases");
426552 }
426553
426554 auto &fs = FileSystem::Get(db);
426555 auto &config = DBConfig::Get(db);
426556
426557 StorageManagerOptions options;
426558 options.read_only = read_only;
426559 options.use_direct_io = config.options.use_direct_io;
426560 options.debug_initialize = config.options.debug_initialize;
426561 options.storage_version = storage_options.storage_version;
426562
426563 if (storage_options.encryption) {
426564 // key is given upon ATTACH
426565 D_ASSERT(storage_options.block_header_size == DEFAULT_ENCRYPTION_BLOCK_HEADER_SIZE);
426566 options.encryption_options.encryption_enabled = true;
426567 options.encryption_options.user_key = std::move(storage_options.user_key);
426568 options.encryption_options.encryption_version = storage_options.encryption_version;
426569 }
426570
426571 idx_t row_group_size = DEFAULT_ROW_GROUP_SIZE;
426572 if (storage_options.row_group_size.IsValid()) {
426573 row_group_size = storage_options.row_group_size.GetIndex();
426574 if (row_group_size == 0) {
426575 throw NotImplementedException("Invalid row group size: %llu - row group size must be bigger than 0",
426576 row_group_size);
426577 }
426578 if (row_group_size % STANDARD_VECTOR_SIZE != 0) {
426579 throw NotImplementedException(
426580 "Invalid row group size: %llu - row group size must be divisible by the vector size (%llu)",
426581 row_group_size, STANDARD_VECTOR_SIZE);
426582 }
426583 }
426584 // Check if the database file already exists.
426585 // Note: a file can also exist if there was a ROLLBACK on a previous transaction creating that file.
426586 if (!read_only && !fs.FileExists(path)) {
426587 // file does not exist and we are in read-write mode
426588 // create a new file
426589
426590 wal_path = GetWALPath();
426591 // try to remove the WAL file if it exists
426592 fs.TryRemoveFile(wal_path);
426593
426594 // Set the block allocation size for the new database file.
426595 if (storage_options.block_alloc_size.IsValid()) {
426596 // Use the option provided by the user.
426597 Storage::VerifyBlockAllocSize(storage_options.block_alloc_size.GetIndex());
426598 options.block_alloc_size = storage_options.block_alloc_size;
426599 } else {
426600 // No explicit option provided: use the default option.
426601 options.block_alloc_size = Settings::Get<DefaultBlockSizeSetting>(config);
426602 }
426606 if (storage_options.block_header_size.IsValid()) {
426607 // Use the header size for the corresponding encryption algorithm.
426608 Storage::VerifyBlockHeaderSize(storage_options.block_header_size.GetIndex());
426609 options.block_header_size = storage_options.block_header_size;
426610 options.storage_version = storage_options.storage_version;
426611 } else {
426612 // No encryption; use the default option.
426613 options.block_header_size = config.options.default_block_header_size;
426614 }
426615 if (!options.storage_version.IsValid()) {
426616 // when creating a new database we default to the serialization version specified in the config
426617 options.storage_version = config.options.serialization_compatibility.serialization_version;
426618 }
426619
426620 // Initialize the block manager before creating a new database.
426621 auto sf_block_manager = make_uniq<SingleFileBlockManager>(db, path, options);
426622 sf_block_manager->CreateNewDatabase(context);
426623 block_manager = std::move(sf_block_manager);
426624 table_io_manager = make_uniq<SingleFileTableIOManager>(*block_manager, row_group_size);
426625 wal = make_uniq<WriteAheadLog>(*this, wal_path);
426626
426627 } else {
426628 // Either the file exists, or we are in read-only mode, so we
426629 // try to read the existing file on disk.
426630
426631 // set the block header size for the encrypted database files
426632 // (also if they already exist)
426633 if (storage_options.encryption) {
426634 options.encryption_options.encryption_enabled = true;
426635 D_ASSERT(storage_options.block_header_size == DEFAULT_ENCRYPTION_BLOCK_HEADER_SIZE);
426636 }
426637 if (storage_options.block_header_size.IsValid()) {
426638 Storage::VerifyBlockHeaderSize(storage_options.block_header_size.GetIndex());
426639 options.block_header_size = storage_options.block_header_size;
426640 options.storage_version = storage_options.storage_version;
426641 } else {
426642 // No explicit option provided: use the default option.
426643 options.block_header_size = config.options.default_block_header_size;
426644 }
426645
426646 // Initialize the block manager while loading the database file.
426647 // We'll construct the SingleFileBlockManager with the default block allocation size,
426648 // and later adjust it when reading the file header.
426649 auto sf_block_manager = make_uniq<SingleFileBlockManager>(db, path, options);
426650 sf_block_manager->LoadExistingDatabase(context);
426651 block_manager = std::move(sf_block_manager);
426652 table_io_manager = make_uniq<SingleFileTableIOManager>(*block_manager, row_group_size);
426653
426654 if (storage_options.block_alloc_size.IsValid()) {
426655 // user-provided block alloc size
426656 idx_t block_alloc_size = storage_options.block_alloc_size.GetIndex();
426657 if (block_alloc_size != block_manager->GetBlockAllocSize()) {
426658 throw InvalidInputException(
426659 "block size parameter does not match the file's block size, got %llu, expected %llu",
426660 storage_options.block_alloc_size.GetIndex(), block_manager->GetBlockAllocSize());
426661 }
426662 }
426663
426664 if (storage_options.block_header_size.IsValid()) {
426665 // block header size for encrypted database files
426666 idx_t block_header_size = storage_options.block_header_size.GetIndex();
426667 if (block_header_size != block_manager->GetBlockHeaderSize()) {
426668 throw InvalidInputException(
426669 "block header size does not match the file's block header size, got %llu, expected %llu",
426670 storage_options.block_header_size.GetIndex(), block_manager->GetBlockHeaderSize());
426671 }
426672 }
426673
426674 unique_ptr<ActiveTimer> timer = nullptr;
426675
426676 // Start timing the storage load step.
426677 auto client_context = context.GetClientContext();
426678 if (client_context) {
426679 auto profiler = client_context->client_data->profiler;
426680 timer = make_uniq<ActiveTimer>(profiler->StartTimer(MetricType::ATTACH_LOAD_STORAGE_LATENCY));
426681 }
426682
426683 // Load the checkpoint from storage.
426684 auto checkpoint_reader = SingleFileCheckpointReader(*this);
426685 checkpoint_reader.LoadFromStorage();
426686
426687 // End timing the storage load step.
426688 if (timer) {
426689 timer->EndTimer();
426690 timer = nullptr;
426691 }
426692
426693 // Start timing the WAL replay step.
426694 if (client_context) {
426695 auto profiler = client_context->client_data->profiler;
426696 timer = make_uniq<ActiveTimer>(profiler->StartTimer(MetricType::ATTACH_REPLAY_WAL_LATENCY));
426697 }
426698
426699 // Replay the WAL.
426700 wal_path = GetWALPath();
426701 wal = WriteAheadLog::Replay(context, *this, wal_path);
426702
426703 // End timing the WAL replay step.
426704 if (timer) {
426705 timer->EndTimer();
426706 }
426707 }
426708
426709 if (row_group_size > 122880ULL && GetStorageVersion() < 4) {
426710 throw InvalidInputException("Unsupported row group size %llu - row group sizes >= 122_880 are only supported "
426711 "with STORAGE_VERSION '1.2.0' or above.\nExplicitly specify a newer storage "
426712 "version when creating the database to enable larger row groups",
426713 row_group_size);
426714 }
426715
426716 load_complete = true;
426717}
string wal_path
The WAL path.
Definition duckdb.cpp:11209
optional_idx storage_version
The serialization compatibility version when reading and writing from this database.
Definition duckdb.cpp:11220
StorageOptions storage_options
Storage options passed in through configuration.
Definition duckdb.cpp:11226
string GetWALPath(const string &suffix=".wal")
The path to the WAL, derived from the database file path.
Definition duckdb.cpp:426470
static unique_ptr< WriteAheadLog > Replay(QueryContext context, StorageManager &storage_manager, const string &wal_path)
Replay and initialize the WAL, QueryContext is passed for metric collection purposes only!...
Definition duckdb.cpp:444090
static void VerifyBlockAllocSize(const idx_t block_alloc_size)
Ensures that a user-provided block allocation size matches all requirements.
Definition duckdb.cpp:426037
Here is the call graph for this function:

◆ CreateCheckpointWriter()

unique_ptr< CheckpointWriter > duckdb::SingleFileStorageManager::CreateCheckpointWriter ( QueryContext context,
CheckpointOptions options )
protected
426846 {
426847 if (InMemory()) {
426848 return make_uniq<InMemoryCheckpointer>(context, db, *block_manager, *this, options);
426849 }
426850 return make_uniq<SingleFileCheckpointWriter>(context, db, *block_manager, options);
426851}

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