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

SingleFileBlockManager is an implementation for a BlockManager which manages blocks in a single file. More...

Inheritance diagram for duckdb::SingleFileBlockManager:
Collaboration diagram for duckdb::SingleFileBlockManager:

Public Member Functions

 SingleFileBlockManager (AttachedDatabase &db_p, const string &path_p, const StorageManagerOptions &options_p)
FileOpenFlags GetFileFlags (bool create_new) const
void CreateNewDatabase (QueryContext context)
 Creates a new database.
void LoadExistingDatabase (QueryContext context)
unique_ptr< Block > ConvertBlock (block_id_t block_id, FileBuffer &source_buffer) override
 Creates a new Block using the specified block_id and returns a pointer.
unique_ptr< Block > CreateBlock (block_id_t block_id, FileBuffer *source_buffer) override
block_id_t GetFreeBlockId () override
 Return the next free block id.
block_id_t GetFreeBlockIdForCheckpoint () override
 Return the next free block id.
block_id_t PeekFreeBlockId () override
 Check the next free block id - but do not assign or allocate it.
bool IsRootBlock (MetaBlockPointer root) override
 Returns whether or not a specified block is the root block.
void MarkBlockAsCheckpointed (block_id_t block_id) override
 Mark a block as included in a checkpoint.
void MarkBlockAsUsed (block_id_t block_id) override
 Mark a block as used (no longer re-writeable).
void MarkBlockAsModified (block_id_t block_id) override
 Mark a block as modified (re-writeable after a checkpoint).
void IncreaseBlockReferenceCount (block_id_t block_id) override
 Increase the reference count of a block. The block should hold at least one reference.
void UnregisterBlock (block_id_t id) override
 UnregisterBlock, only accepts non-temporary block ids.
idx_t GetMetaBlock () override
 Return the meta block id.
void Read (QueryContext context, Block &block) override
 Read the content of the block from disk.
void ReadBlock (Block &block, bool skip_block_header=false) const
 Read individual blocks.
void ReadBlock (data_ptr_t internal_buffer, uint64_t block_size, bool skip_block_header=false) const
void ReadBlocks (FileBuffer &buffer, block_id_t start_block, idx_t block_count) override
 Read the content of a range of blocks into a buffer.
void Write (FileBuffer &buffer, block_id_t block_id) override
 Write the block to disk. Use Write with client context instead.
void Write (QueryContext context, FileBuffer &buffer, block_id_t block_id) override
 Write the block to disk.
void WriteHeader (QueryContext context, DatabaseHeader header) override
 Write the header to disk, this is the final step of the checkpointing process.
void FileSync () override
 Sync changes to the underlying file.
void Truncate () override
 Truncate the underlying database file after a checkpoint.
bool InMemory () override
 Whether or not the attached database is in-memory.
idx_t TotalBlocks () override
 Returns the number of total blocks.
idx_t FreeBlocks () override
 Returns the number of free blocks.
bool IsRemote () override
 Whether or not the attached database is a remote file.
bool Prefetch () override
 Whether or not to prefetch.
uint64_t GetCheckpointIteration () const
 Return the checkpoint iteration of the file.
uint64_t GetVersionNumber () const
 Return the version number of the file.
data_ptr_t GetDBIdentifier ()
 Return the database identifier.
Public Member Functions inherited from duckdb::BlockManager
 BlockManager (BufferManager &buffer_manager, const optional_idx block_alloc_size_p, const optional_idx block_header_size_p)
BufferManager & GetBufferManager () const
void Write (Block &block)
 Writes the block to disk.
shared_ptr< BlockHandle > RegisterBlock (block_id_t block_id)
 Register a block with the given block id in the base file.
shared_ptr< BlockHandle > ConvertToPersistent (QueryContext context, block_id_t block_id, shared_ptr< BlockHandle > old_block, BufferHandle old_handle, ConvertToPersistentMode mode=ConvertToPersistentMode::DESTRUCTIVE)
 Convert an existing in-memory buffer into a persistent disk-backed block If mode is set to destructive (default) - the old_block will be destroyed as part of this method This can only be safely used when there is no other (lingering) usage of old_block If there is concurrent usage of the block elsewhere - use the THREAD_SAFE mode which creates an extra copy.
shared_ptr< BlockHandle > ConvertToPersistent (QueryContext context, block_id_t block_id, shared_ptr< BlockHandle > old_block, ConvertToPersistentMode mode=ConvertToPersistentMode::DESTRUCTIVE)
void UnregisterPersistentBlock (BlockHandle &block)
MetadataManager & GetMetadataManager ()
 Returns a reference to the metadata manager of this block manager.
idx_t GetBlockAllocSize () const
 Returns the block allocation size of this block manager.
optional_idx GetOptionalBlockAllocSize () const
 Returns the possibly invalid block allocation size of this block manager.
optional_idx GetOptionalBlockHeaderSize () const
 Returns the possibly invalid block header size of this block manager.
idx_t GetBlockHeaderSize () const
 Returns the block header size including the 8-byte checksum of this block manager.
idx_t GetBlockSize () const
 Returns the size of the block that is available for usage.
void SetBlockAllocSize (const optional_idx block_alloc_size_p)
 Sets the block allocation size. This should only happen when initializing an existing database. When initializing an existing database, we construct the block manager before reading the file header, which contains the file's actual block allocation size.
void SetBlockHeaderSize (const optional_idx block_header_size_p)
 Sets the block header size. Idem as above. This is only set once upon initialization of the database For now this method is unused.
template<class TARGET>
TARGET & Cast ()
template<class TARGET>
const TARGET & Cast () const

Private Member Functions

void LoadFreeList (QueryContext context)
 Loads the free list of the file.
void Initialize (const DatabaseHeader &header, const optional_idx block_alloc_size)
void CheckChecksum (FileBuffer &block, uint64_t location, uint64_t delta, bool skip_block_header=false) const
void CheckChecksum (data_ptr_t start_ptr, uint64_t delta, bool skip_block_header=false) const
void ReadAndChecksum (QueryContext context, FileBuffer &handle, uint64_t location, bool skip_block_header=false) const
void ChecksumAndWrite (QueryContext context, FileBuffer &handle, uint64_t location, bool skip_block_header=false) const
idx_t GetBlockLocation (block_id_t block_id) const
void StoreEncryptionMetadata (MainHeader &main_header) const
void CheckAndAddEncryptionKey (MainHeader &main_header, string &user_key)
 Check and adding Encryption Keys.
void CheckAndAddEncryptionKey (MainHeader &main_header)
vector< MetadataHandle > GetFreeListBlocks ()
 Return the blocks to which we will write the free list and modified blocks.
void TrimFreeBlocks (const set< block_id_t > &blocks)
void TrimFreeBlockRange (block_id_t start, block_id_t end)
void IncreaseBlockReferenceCountInternal (block_id_t block_id)
void VerifyBlocks (const unordered_map< block_id_t, idx_t > &block_usage_count) override
 Verify the block usage count.
void AddStorageVersionTag ()
block_id_t GetFreeBlockIdInternal (FreeBlockType type)
bool AddFreeBlock (unique_lock< mutex > &lock, block_id_t block_id)
 Adds a free block to the free_list, returns true if it was added to the regular free_list.

Static Private Member Functions

static void StoreEncryptedCanary (AttachedDatabase &db, MainHeader &main_header, const string &key_id)
static void StoreDBIdentifier (MainHeader &main_header, const data_ptr_t db_identifier)
template<typename T>
static void WriteEncryptionData (MemoryStream &stream, const T &val)

Private Attributes

AttachedDatabase & db
uint8_t active_header
 The active DatabaseHeader, either 0 (h1) or 1 (h2).
string path
 The path where the file is stored.
unique_ptr< FileHandle > handle
 The file handle.
FileBuffer header_buffer
 The buffer used to read/write to the headers.
set< block_id_t > free_list
 The list of free blocks that can be written to currently.
set< block_id_t > free_blocks_in_use
 The list of blocks that have been freed, but cannot yet be re-used because they are still in-use.
set< block_id_t > newly_used_blocks
 The list of blocks that are in-use, but haven't been written as part of a checkpoint yet.
unordered_map< block_id_t, uint32_t > multi_use_blocks
unordered_set< block_id_t > modified_blocks
 The list of blocks that are no longer in-use, but cannot be re-used until the next checkpoint.
idx_t meta_block
 The current meta block id.
block_id_t max_block
 The current maximum block id, this id will be given away first after the free_list runs out.
idx_t free_list_id
 The block id where the free list can be found.
uint64_t iteration_count
 The current header iteration count.
StorageManagerOptions options
 The storage manager options.
mutex single_file_block_lock
 Lock for performing various operations in the single file block manager.

Static Private Attributes

static constexpr uint64_t BLOCK_START = Storage::FILE_HEADER_SIZE * 3
 The location in the file where the block writing starts.

Additional Inherited Members

Public Attributes inherited from duckdb::BlockManager
BufferManager & buffer_manager
 The buffer manager.
Protected Member Functions inherited from duckdb::BlockManager
bool BlockIsRegistered (block_id_t block_id)
shared_ptr< BlockHandle > TryGetBlock (block_id_t block_id)
Protected Attributes inherited from duckdb::BlockManager
bool in_destruction = false
 A flag to be flipped in the destructor of the subclass, which is called first. Relevant for some Windows edge cases.

Detailed Description

SingleFileBlockManager is an implementation for a BlockManager which manages blocks in a single file.

Constructor & Destructor Documentation

◆ SingleFileBlockManager()

duckdb::SingleFileBlockManager::SingleFileBlockManager ( AttachedDatabase & db_p,
const string & path_p,
const StorageManagerOptions & options_p )
420558 : BlockManager(BufferManager::GetBufferManager(db_p), options.block_alloc_size, options.block_header_size),
420559 db(db_p), path(path_p), header_buffer(BlockAllocator::Get(db_p), FileBufferType::MANAGED_BUFFER,
420560 Storage::FILE_HEADER_SIZE - options.block_header_size.GetIndex(),
420561 options.block_header_size.GetIndex()),
420563}
string path
The path where the file is stored.
Definition duckdb.cpp:420214
uint64_t iteration_count
The current header iteration count.
Definition duckdb.cpp:420238
StorageManagerOptions options
The storage manager options.
Definition duckdb.cpp:420240
FileBuffer header_buffer
The buffer used to read/write to the headers.
Definition duckdb.cpp:420218
static constexpr idx_t FILE_HEADER_SIZE
Definition duckdb.hpp:9708

◆ ~SingleFileBlockManager()

duckdb::SingleFileBlockManager::~SingleFileBlockManager ( )
override
420565 {
420566 // flip the flag to not perform UnregisterBlock on the block manager that is being destructed
420567 this->in_destruction = true;
420568}
bool in_destruction
A flag to be flipped in the destructor of the subclass, which is called first. Relevant for some Wind...
Definition duckdb.hpp:45363

Member Function Documentation

◆ GetFileFlags()

FileOpenFlags duckdb::SingleFileBlockManager::GetFileFlags ( bool create_new) const
420570 {
420571 FileOpenFlags result;
420572 if (options.read_only) {
420573 D_ASSERT(!create_new);
420574 result = FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_NULL_IF_NOT_EXISTS | FileLockType::READ_LOCK;
420575 } else {
420576 result = FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_READ | FileLockType::WRITE_LOCK;
420577 if (create_new) {
420579 }
420580 }
420581 if (options.use_direct_io) {
420583 }
420584 // database files can be read from in parallel
420587 return result;
420588}
static constexpr FileOpenFlags FILE_FLAGS_PARALLEL_ACCESS
Multiple threads may perform reads and writes in parallel.
Definition duckdb.hpp:7868
static constexpr FileOpenFlags FILE_FLAGS_FILE_CREATE
Create file if not exists, can only be used together with WRITE.
Definition duckdb.hpp:7856
static constexpr FileOpenFlags FILE_FLAGS_NULL_IF_NOT_EXISTS
Return NULL if the file does not exist instead of throwing an error.
Definition duckdb.hpp:7865
static constexpr FileOpenFlags FILE_FLAGS_MULTI_CLIENT_ACCESS
Multiple clients may access the file at the same time.
Definition duckdb.hpp:7876
static constexpr FileOpenFlags FILE_FLAGS_READ
Open file with read access.
Definition duckdb.hpp:7850
static constexpr FileOpenFlags FILE_FLAGS_DIRECT_IO
Use direct IO when reading/writing to the file.
Definition duckdb.hpp:7854
static constexpr FileOpenFlags FILE_FLAGS_WRITE
Open file with write access.
Definition duckdb.hpp:7852

◆ CreateNewDatabase()

void duckdb::SingleFileBlockManager::CreateNewDatabase ( QueryContext context)

Creates a new database.

420703 {
420704 auto flags = GetFileFlags(true);
420705
420706 auto encryption_enabled = options.encryption_options.encryption_enabled;
420707 if (encryption_enabled) {
420708 // Check if we can read/write the encrypted database
420709 db.GetDatabase().GetEncryptionUtil(options.read_only);
420710 }
420711
420712 // open the RDBMS handle
420713 auto &fs = FileSystem::Get(db);
420714 handle = fs.OpenFile(path, flags);
420715 header_buffer.Clear();
420716
420717 options.version_number = GetVersionNumber();
420718 db.GetStorageManager().SetStorageVersion(options.storage_version.GetIndex());
420719 AddStorageVersionTag();
420720
420721 MainHeader main_header = ConstructMainHeader(options.version_number.GetIndex());
420722
420723 // Derive the encryption key and add it to the cache.
420724 // Not used for plain databases.
420726
420727 // We need the unique database identifier, if the storage version is new enough.
420728 // If encryption is enabled, we also use it as the salt.
420729 memset(options.db_identifier, 0, MainHeader::DB_IDENTIFIER_LEN);
420730 if (encryption_enabled || options.version_number.GetIndex() >= 67) {
420731 GenerateDBIdentifier(options.db_identifier);
420732 }
420733
420734 if (encryption_enabled) {
420735 // The key is given via ATTACH.
420736 EncryptionKeyManager::DeriveKey(*options.encryption_options.user_key, options.db_identifier, derived_key);
420737 options.encryption_options.user_key = nullptr;
420738
420739 // if no encryption cipher is specified, use GCM
420740 if (db.GetStorageManager().GetCipher() == EncryptionTypes::INVALID) {
420741 db.GetStorageManager().SetCipher(EncryptionTypes::GCM);
420742 }
420743
420744 // Set the encrypted DB bit to 1.
420745 main_header.SetEncrypted();
420746
420747 if (options.encryption_options.encryption_version == EncryptionTypes::NONE) {
420748 throw InvalidConfigurationException("No Encryption type set");
420749 }
420750
420751 main_header.SetEncryptionVersion(options.encryption_options.encryption_version);
420752
420753 // The derived key is wiped in AddKeyToCache.
420754 options.encryption_options.derived_key_id = EncryptionEngine::AddKeyToCache(db.GetDatabase(), derived_key);
420755 auto &catalog = db.GetCatalog().Cast<DuckCatalog>();
420756 catalog.SetEncryptionKeyId(options.encryption_options.derived_key_id);
420757 catalog.SetIsEncrypted();
420758 }
420759
420760 // Store all metadata in the main header.
420761 if (encryption_enabled) {
420762 StoreEncryptionMetadata(main_header);
420763 }
420764 // Always store the database identifier.
420765 StoreDBIdentifier(main_header, options.db_identifier);
420766 if (encryption_enabled) {
420767 StoreEncryptedCanary(db, main_header, options.encryption_options.derived_key_id);
420768 }
420769
420770 // Write the main database header.
420771 SerializeHeaderStructure<MainHeader>(main_header, header_buffer.buffer);
420772 ChecksumAndWrite(context, header_buffer, 0, true);
420773
420774 // write the database headers
420775 // initialize meta_block and free_list to INVALID_BLOCK because the database file does not contain any actual
420776 // content yet
420777 DatabaseHeader h1;
420778 // header 1
420779 h1.iteration = 0;
420780 h1.meta_block = idx_t(INVALID_BLOCK);
420781 h1.free_list = idx_t(INVALID_BLOCK);
420782 h1.block_count = 0;
420783 // We create the SingleFileBlockManager with the desired block allocation size before calling CreateNewDatabase.
420784 h1.block_alloc_size = GetBlockAllocSize();
420785 h1.vector_size = STANDARD_VECTOR_SIZE;
420786 h1.serialization_compatibility = options.storage_version.GetIndex();
420787 SerializeHeaderStructure<DatabaseHeader>(h1, header_buffer.buffer);
420789
420790 // header 2
420791 DatabaseHeader h2;
420792 h2.iteration = 0;
420793 h2.meta_block = idx_t(INVALID_BLOCK);
420794 h2.free_list = idx_t(INVALID_BLOCK);
420795 h2.block_count = 0;
420796 // We create the SingleFileBlockManager with the desired block allocation size before calling CreateNewDatabase.
420797 h2.block_alloc_size = GetBlockAllocSize();
420798 h2.vector_size = STANDARD_VECTOR_SIZE;
420799 h2.serialization_compatibility = options.storage_version.GetIndex();
420800 SerializeHeaderStructure<DatabaseHeader>(h2, header_buffer.buffer);
420802
420803 // ensure that writing to disk is completed before returning
420804 handle->Sync();
420805 // we start with h2 as active_header, this way our initial write will be in h1
420806 iteration_count = 0;
420807 active_header = 1;
420808 max_block = 0;
420809}
idx_t GetBlockAllocSize() const
Returns the block allocation size of this block manager.
Definition duckdb.hpp:45300
static void DeriveKey(string &user_key, data_ptr_t salt, data_ptr_t derived_key)
Definition duckdb.cpp:52234
static constexpr uint64_t DEFAULT_ENCRYPTION_KEY_LENGTH
The encryption key length.
Definition duckdb.hpp:9749
static constexpr idx_t DB_IDENTIFIER_LEN
The length of the unique database identifier.
Definition duckdb.hpp:9763
block_id_t max_block
The current maximum block id, this id will be given away first after the free_list runs out.
Definition duckdb.cpp:420234
uint8_t active_header
The active DatabaseHeader, either 0 (h1) or 1 (h2).
Definition duckdb.cpp:420212
void ChecksumAndWrite(QueryContext context, FileBuffer &handle, uint64_t location, bool skip_block_header=false) const
Definition duckdb.cpp:420976
uint64_t GetVersionNumber() const
Return the version number of the file.
Definition duckdb.cpp:420594
unique_ptr< FileHandle > handle
The file handle.
Definition duckdb.cpp:420216
uint8_t data_t
data pointers
Definition duckdb.hpp:246
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadExistingDatabase()

void duckdb::SingleFileBlockManager::LoadExistingDatabase ( QueryContext context)

Loads an existing database. We pass the provided block allocation size as a parameter to detect inconsistencies with the file header.

Encryption is set

Check if our encryption module can write, if not, we throw

Check if the given key upon attach is correct

420811 {
420812 auto flags = GetFileFlags(false);
420813
420814 // open the RDBMS handle
420815 auto &fs = FileSystem::Get(db);
420816 handle = fs.OpenFile(path, flags);
420817 if (!handle) {
420818 // this can only happen in read-only mode - as that is when we set FILE_FLAGS_NULL_IF_NOT_EXISTS
420819 throw IOException("Cannot open database \"%s\" in read-only mode: database does not exist", path);
420820 }
420821
420822 MainHeader::CheckMagicBytes(context, *handle);
420823 // otherwise, we check the metadata of the file
420824 ReadAndChecksum(context, header_buffer, 0, true);
420825
420826 uint64_t delta = 0;
420827 if (GetBlockHeaderSize() > DEFAULT_BLOCK_HEADER_STORAGE_SIZE) {
420828 delta = GetBlockHeaderSize() - DEFAULT_BLOCK_HEADER_STORAGE_SIZE;
420829 }
420830
420831 MainHeader main_header = DeserializeMainHeader(header_buffer.buffer - delta);
420832 memcpy(options.db_identifier, main_header.GetDBIdentifier(), MainHeader::DB_IDENTIFIER_LEN);
420833
420834 if (!main_header.IsEncrypted() && options.encryption_options.encryption_enabled) {
420835 throw CatalogException("A key is explicitly specified, but database \"%s\" is not encrypted", path);
420836 // database is not encrypted, but is tried to be opened with a key
420837 }
420838
420839 if (main_header.IsEncrypted()) {
420840 auto &storage_manager = db.GetStorageManager();
420841 if (options.encryption_options.encryption_enabled) {
420843 D_ASSERT(db.GetStorageManager().IsEncrypted());
420844 options.encryption_options.encryption_version =
420845 static_cast<EncryptionTypes::EncryptionVersion>(main_header.GetEncryptionVersion());
420846
420848 db.GetDatabase().GetEncryptionUtil(options.read_only);
420849
420851 // Derive the encryption key and add it to cache
420852 CheckAndAddEncryptionKey(main_header);
420853 // delete user key ptr
420854 options.encryption_options.user_key = nullptr;
420855 } else {
420856 // if encrypted, but no encryption key given
420857 throw CatalogException("Cannot open encrypted database \"%s\" without a key", path);
420858 }
420859
420860 // if a cipher was provided, check if it is the same as in the config
420861 auto stored_cipher = static_cast<EncryptionTypes::CipherType>(main_header.GetEncryptionCipher());
420862 auto config_cipher = storage_manager.GetCipher();
420863 if (config_cipher != EncryptionTypes::INVALID && config_cipher != stored_cipher) {
420864 throw CatalogException("Cannot open encrypted database \"%s\" with a different cipher (%s) than the one "
420865 "used to create it (%s)",
420866 path, EncryptionTypes::CipherToString(config_cipher),
420867 EncryptionTypes::CipherToString(stored_cipher));
420868 }
420869
420870 // This avoids the cipher from being downgrades by an attacker
420871 // FIXME: we likely want to have a proper validation
420872 // of the cipher used instead of this trick to avoid downgrades
420873 if (stored_cipher != EncryptionTypes::GCM) {
420874 if (config_cipher == EncryptionTypes::INVALID) {
420875 throw CatalogException(
420876 "Cannot open encrypted database \"%s\" without explicitly specifying the "
420877 "encryption cipher for security reasons. Please make sure you understand the security implications "
420878 "and re-attach the database specifying the desired cipher.",
420879 path);
420880 }
420881 }
420882
420883 // this is ugly, but the storage manager does not know the cipher type before
420884 storage_manager.SetCipher(stored_cipher);
420885 // encryption version can be overridden by the serialized encryption version
420886 storage_manager.SetEncryptionVersion(
420887 static_cast<EncryptionTypes::EncryptionVersion>(main_header.GetEncryptionVersion()));
420888 }
420889
420890 options.version_number = main_header.version_number;
420891
420892 // read the database headers from disk
420893 DatabaseHeader h1;
420895 h1 = DeserializeDatabaseHeader(main_header, header_buffer.buffer);
420896
420897 DatabaseHeader h2;
420899 h2 = DeserializeDatabaseHeader(main_header, header_buffer.buffer);
420900
420901 // check the header with the highest iteration count
420902 if (h1.iteration > h2.iteration) {
420903 // h1 is active header
420904 active_header = 0;
420906 } else {
420907 // h2 is active header
420908 active_header = 1;
420910 }
420911 AddStorageVersionTag();
420912 LoadFreeList(context);
420913}
optional_idx GetOptionalBlockAllocSize() const
Returns the possibly invalid block allocation size of this block manager.
Definition duckdb.hpp:45304
idx_t GetBlockHeaderSize() const
Returns the block header size including the 8-byte checksum of this block manager.
Definition duckdb.hpp:45312
uint64_t version_number
The (storage) version of the database.
Definition duckdb.hpp:9756
void CheckAndAddEncryptionKey(MainHeader &main_header, string &user_key)
Check and adding Encryption Keys.
Definition duckdb.cpp:420659
void LoadFreeList(QueryContext context)
Loads the free list of the file.
Definition duckdb.cpp:421045
void Initialize(const DatabaseHeader &header, const optional_idx block_alloc_size)
Definition duckdb.cpp:421008
void ReadAndChecksum(QueryContext context, FileBuffer &handle, uint64_t location, bool skip_block_header=false) const
Definition duckdb.cpp:420960
::uint64_t uint64_t
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ConvertBlock()

unique_ptr< Block > duckdb::SingleFileBlockManager::ConvertBlock ( block_id_t block_id,
FileBuffer & source_buffer )
overridevirtual

Creates a new Block using the specified block_id and returns a pointer.

Implements duckdb::BlockManager.

421315 {
421316 D_ASSERT(source_buffer.AllocSize() == GetBlockAllocSize());
421317 // FIXME; maybe we should pass the block header size explicitly
421318 return make_uniq<Block>(source_buffer, block_id, GetBlockHeaderSize());
421319}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CreateBlock()

unique_ptr< Block > duckdb::SingleFileBlockManager::CreateBlock ( block_id_t block_id,
FileBuffer * source_buffer )
overridevirtual

Implements duckdb::BlockManager.

421321 {
421322 // FIXME; maybe we should pass the block header size explicitly
421323 unique_ptr<Block> result;
421324 if (source_buffer) {
421325 result = ConvertBlock(block_id, *source_buffer);
421326 } else {
421327 result = make_uniq<Block>(BlockAllocator::Get(db), block_id, *this);
421328 }
421329 result->Initialize(options.debug_initialize);
421330 return result;
421331}
unique_ptr< Block > ConvertBlock(block_id_t block_id, FileBuffer &source_buffer) override
Creates a new Block using the specified block_id and returns a pointer.
Definition duckdb.cpp:421315

◆ GetFreeBlockId()

block_id_t duckdb::SingleFileBlockManager::GetFreeBlockId ( )
overridevirtual

Return the next free block id.

Implements duckdb::BlockManager.

421094 {
421095 return GetFreeBlockIdInternal(FreeBlockType::NEWLY_USED_BLOCK);
421096}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetFreeBlockIdForCheckpoint()

block_id_t duckdb::SingleFileBlockManager::GetFreeBlockIdForCheckpoint ( )
overridevirtual

Return the next free block id.

Implements duckdb::BlockManager.

421098 {
421099 return GetFreeBlockIdInternal(FreeBlockType::CHECKPOINTED_BLOCK);
421100}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PeekFreeBlockId()

block_id_t duckdb::SingleFileBlockManager::PeekFreeBlockId ( )
overridevirtual

Check the next free block id - but do not assign or allocate it.

Implements duckdb::BlockManager.

421102 {
421103 lock_guard<mutex> lock(single_file_block_lock);
421104 if (!free_list.empty()) {
421105 return *free_list.begin();
421106 } else {
421107 return max_block;
421108 }
421109}
mutex single_file_block_lock
Lock for performing various operations in the single file block manager.
Definition duckdb.cpp:420242
set< block_id_t > free_list
The list of free blocks that can be written to currently.
Definition duckdb.cpp:420220
Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsRootBlock()

bool duckdb::SingleFileBlockManager::IsRootBlock ( MetaBlockPointer root)
overridevirtual

Returns whether or not a specified block is the root block.

Implements duckdb::BlockManager.

421069 {
421070 return root.block_pointer == meta_block;
421071}
idx_t meta_block
The current meta block id.
Definition duckdb.cpp:420232
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MarkBlockAsCheckpointed()

void duckdb::SingleFileBlockManager::MarkBlockAsCheckpointed ( block_id_t block_id)
overridevirtual

Mark a block as included in a checkpoint.

Implements duckdb::BlockManager.

421111 {
421112 lock_guard<mutex> lock(single_file_block_lock);
421113 D_ASSERT(block_id >= 0);
421114 newly_used_blocks.erase(block_id);
421115}
set< block_id_t > newly_used_blocks
The list of blocks that are in-use, but haven't been written as part of a checkpoint yet.
Definition duckdb.cpp:420224
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MarkBlockAsUsed()

void duckdb::SingleFileBlockManager::MarkBlockAsUsed ( block_id_t block_id)
overridevirtual

Mark a block as used (no longer re-writeable).

Implements duckdb::BlockManager.

421117 {
421118 lock_guard<mutex> lock(single_file_block_lock);
421119 D_ASSERT(block_id >= 0);
421120 if (max_block <= block_id) {
421121 // the block is past the current max_block
421122 // in this case we need to increment "max_block" to "block_id"
421123 // any blocks in the middle are added to the free list
421124 // i.e. if max_block = 0, and block_id = 3, we need to add blocks 1 and 2 to the free list
421125 while (max_block < block_id) {
421126 free_list.insert(max_block);
421127 max_block++;
421128 }
421129 max_block++;
421130 } else if (free_list.find(block_id) != free_list.end()) {
421131 // block is currently in the free list - erase
421132 free_list.erase(block_id);
421133 } else {
421134 // block is already in use - increase reference count
421135 IncreaseBlockReferenceCountInternal(block_id);
421136 }
421137}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MarkBlockAsModified()

void duckdb::SingleFileBlockManager::MarkBlockAsModified ( block_id_t block_id)
overridevirtual

Mark a block as modified (re-writeable after a checkpoint).

Implements duckdb::BlockManager.

421139 {
421140 unique_lock<mutex> lock(single_file_block_lock);
421141 D_ASSERT(block_id >= 0);
421142 D_ASSERT(block_id < max_block);
421143
421144 // check if the block is a multi-use block
421145 auto entry = multi_use_blocks.find(block_id);
421146 if (entry != multi_use_blocks.end()) {
421147 // it is! reduce the reference count of the block
421148 entry->second--;
421149 // check the reference count: is the block still a multi-use block?
421150 if (entry->second <= 1) {
421151 // no longer a multi-use block!
421152 multi_use_blocks.erase(entry);
421153 }
421154 return;
421155 }
421156 // Check for multi-free
421157 if (modified_blocks.find(block_id) != modified_blocks.end()) {
421158 throw InternalException("MarkBlockAsModified called with already modified block id %d", block_id);
421159 }
421160 if (free_list.find(block_id) != free_list.end()) {
421161 throw InternalException("MarkBlockAsModified called with already freed block id %d", block_id);
421162 }
421163 auto newly_used_entry = newly_used_blocks.find(block_id);
421164 if (newly_used_entry != newly_used_blocks.end()) {
421165 // this block was newly used - and now we are labeling it as no longer being required
421166 // we can directly add it back to the free list
421167 newly_used_blocks.erase(block_id);
421168 AddFreeBlock(lock, block_id);
421169 } else {
421170 // this block was used in storage, we cannot directly re-use it
421171 // add it to the modified blocks indicating it will be re-usable after the next checkpoint
421172 modified_blocks.insert(block_id);
421173 }
421174}
unordered_map< block_id_t, uint32_t > multi_use_blocks
Definition duckdb.cpp:420228
bool AddFreeBlock(unique_lock< mutex > &lock, block_id_t block_id)
Adds a free block to the free_list, returns true if it was added to the regular free_list.
Definition duckdb.cpp:421473
unordered_set< block_id_t > modified_blocks
The list of blocks that are no longer in-use, but cannot be re-used until the next checkpoint.
Definition duckdb.cpp:420230
Here is the call graph for this function:
Here is the caller graph for this function:

◆ IncreaseBlockReferenceCount()

void duckdb::SingleFileBlockManager::IncreaseBlockReferenceCount ( block_id_t block_id)
overridevirtual

Increase the reference count of a block. The block should hold at least one reference.

Implements duckdb::BlockManager.

421278 {
421279 lock_guard<mutex> lock(single_file_block_lock);
421280 IncreaseBlockReferenceCountInternal(block_id);
421281}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UnregisterBlock()

void duckdb::SingleFileBlockManager::UnregisterBlock ( block_id_t id)
overridevirtual

UnregisterBlock, only accepts non-temporary block ids.

Reimplemented from duckdb::BlockManager.

421595 {
421596 // perform the actual unregistration
421598 // check if it is part of the newly free list
421599 lock_guard<mutex> lock(single_file_block_lock);
421600 auto entry = free_blocks_in_use.find(id);
421601 if (entry != free_blocks_in_use.end()) {
421602 // it is! move it to the regular free list so the block can be re-used
421603 free_list.insert(id);
421604 free_blocks_in_use.erase(entry);
421605 }
421606}
virtual void UnregisterBlock(block_id_t id)
UnregisterBlock, only accepts non-temporary block ids.
Definition duckdb.cpp:387139
set< block_id_t > free_blocks_in_use
The list of blocks that have been freed, but cannot yet be re-used because they are still in-use.
Definition duckdb.cpp:420222
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetMetaBlock()

idx_t duckdb::SingleFileBlockManager::GetMetaBlock ( )
overridevirtual

Return the meta block id.

Implements duckdb::BlockManager.

421283 {
421284 return meta_block;
421285}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Read()

void duckdb::SingleFileBlockManager::Read ( QueryContext context,
Block & block )
overridevirtual

Read the content of the block from disk.

Implements duckdb::BlockManager.

421365 {
421366 D_ASSERT(block.id >= 0);
421367 D_ASSERT(std::find(free_list.begin(), free_list.end(), block.id) == free_list.end());
421368 ReadAndChecksum(context, block, GetBlockLocation(block.id));
421369}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadBlock() [1/2]

void duckdb::SingleFileBlockManager::ReadBlock ( Block & block,
bool skip_block_header = false ) const

Read individual blocks.

calculate delta header bytes (if any)

421349 {
421350 // read the buffer from disk
421351 auto location = GetBlockLocation(block.id);
421352 block.Read(QueryContext(), *handle, location);
421353
421356
421357 if (options.encryption_options.encryption_enabled && !skip_block_header) {
421358 EncryptionEngine::DecryptBlock(db, options.encryption_options.derived_key_id, block.InternalBuffer(),
421359 block.Size(), delta);
421360 }
421361
421362 CheckChecksum(block, location, delta, skip_block_header);
421363}
static void DecryptBlock(AttachedDatabase &attached_db, const string &key_id, data_ptr_t internal_buffer, uint64_t block_size, uint64_t delta)
Definition duckdb.cpp:51972
void CheckChecksum(FileBuffer &block, uint64_t location, uint64_t delta, bool skip_block_header=false) const
Definition duckdb.cpp:420937
static constexpr idx_t DEFAULT_BLOCK_HEADER_SIZE
The default block header size for blocks written to storage.
Definition duckdb.hpp:9716
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReadBlock() [2/2]

void duckdb::SingleFileBlockManager::ReadBlock ( data_ptr_t internal_buffer,
uint64_t block_size,
bool skip_block_header = false ) const

calculate delta header bytes (if any)

421337 {
421340
421341 if (options.encryption_options.encryption_enabled && !skip_block_header) {
421342 EncryptionEngine::DecryptBlock(db, options.encryption_options.derived_key_id, internal_buffer, block_size,
421343 delta);
421344 }
421345
421346 CheckChecksum(internal_buffer, delta, skip_block_header);
421347}
Here is the call graph for this function:

◆ ReadBlocks()

void duckdb::SingleFileBlockManager::ReadBlocks ( FileBuffer & buffer,
block_id_t start_block,
idx_t block_count )
overridevirtual

Read the content of a range of blocks into a buffer.

Implements duckdb::BlockManager.

421371 {
421372 D_ASSERT(start_block >= 0);
421373 D_ASSERT(block_count >= 1);
421374
421375 // read the buffer from disk
421376 auto location = GetBlockLocation(start_block);
421377 buffer.Read(QueryContext(), *handle, location);
421378
421379 // for each of the blocks - verify the checksum
421380 auto ptr = buffer.InternalBuffer();
421381 for (idx_t i = 0; i < block_count; i++) {
421382 auto start_ptr = ptr + i * GetBlockAllocSize();
421383 ReadBlock(start_ptr, GetBlockSize());
421384 }
421385}
idx_t GetBlockSize() const
Returns the size of the block that is available for usage.
Definition duckdb.hpp:45319
void ReadBlock(Block &block, bool skip_block_header=false) const
Read individual blocks.
Definition duckdb.cpp:421349
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Write() [1/2]

void duckdb::SingleFileBlockManager::Write ( FileBuffer & buffer,
block_id_t block_id )
overridevirtual

Write the block to disk. Use Write with client context instead.

Implements duckdb::BlockManager.

421387 {
421388 Write(QueryContext(), buffer, block_id);
421389}
void Write(FileBuffer &buffer, block_id_t block_id) override
Write the block to disk. Use Write with client context instead.
Definition duckdb.cpp:421387
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Write() [2/2]

void duckdb::SingleFileBlockManager::Write ( QueryContext context,
FileBuffer & buffer,
block_id_t block_id )
overridevirtual

Write the block to disk.

Reimplemented from duckdb::BlockManager.

421391 {
421392 D_ASSERT(block_id >= 0);
421393 ChecksumAndWrite(context, buffer, BLOCK_START + NumericCast<idx_t>(block_id) * GetBlockAllocSize());
421394}
static constexpr uint64_t BLOCK_START
The location in the file where the block writing starts.
Definition duckdb.cpp:420086
Here is the call graph for this function:

◆ WriteHeader()

void duckdb::SingleFileBlockManager::WriteHeader ( QueryContext context,
DatabaseHeader header )
overridevirtual

Write the header to disk, this is the final step of the checkpointing process.

Ensure the header write ends up on disk

Implements duckdb::BlockManager.

421493 {
421494 auto free_list_blocks = GetFreeListBlocks();
421495
421496 // now handle the free list
421498 // add all modified blocks to the free list: they can now be written to again
421499 metadata_manager.MarkBlocksAsModified();
421500
421501 unique_lock<mutex> lock(single_file_block_lock);
421502 // set the iteration count
421503 header.iteration = ++iteration_count;
421504
421505 set<block_id_t> all_free_blocks = free_list;
421506 set<block_id_t> fully_freed_blocks;
421507 for (auto &block : modified_blocks) {
421508 all_free_blocks.insert(block);
421509 if (AddFreeBlock(lock, block)) {
421510 fully_freed_blocks.insert(block);
421511 }
421512 }
421513 auto written_multi_use_blocks = multi_use_blocks;
421514 // newly used blocks are still free blocks for this checkpoint - so add them to the free list that we write
421515 for (auto &newly_used_block : newly_used_blocks) {
421516 all_free_blocks.insert(newly_used_block);
421517 written_multi_use_blocks.erase(newly_used_block);
421518 }
421519 modified_blocks.clear();
421520
421521 if (!free_list_blocks.empty()) {
421522 // there are blocks to write, either in the free_list or in the modified_blocks
421523 // we write these blocks specifically to the free_list_blocks
421524 // a normal MetadataWriter will fetch blocks to use from the free_list
421525 // but since we are WRITING the free_list, this behavior is sub-optimal
421526 FreeListBlockWriter writer(metadata_manager, std::move(free_list_blocks));
421527
421528 auto ptr = writer.GetMetaBlockPointer();
421529 header.free_list = ptr.block_pointer;
421530
421531 writer.Write<uint64_t>(all_free_blocks.size());
421532 for (auto &block_id : all_free_blocks) {
421533 writer.Write<block_id_t>(block_id);
421534 }
421535 writer.Write<uint64_t>(written_multi_use_blocks.size());
421536 for (auto &entry : written_multi_use_blocks) {
421537 writer.Write<block_id_t>(entry.first);
421538 writer.Write<uint32_t>(entry.second);
421539 }
421540 GetMetadataManager().Write(writer);
421541 writer.Flush();
421542 } else {
421543 // no blocks in the free list
421544 header.free_list = DConstants::INVALID_INDEX;
421545 }
421546 lock.unlock();
421547 metadata_manager.Flush();
421548
421549 lock.lock();
421550 header.block_count = NumericCast<idx_t>(max_block);
421551 lock.unlock();
421552
421553 header.serialization_compatibility = options.storage_version.GetIndex();
421554
421555 auto debug_checkpoint_abort = Settings::Get<DebugCheckpointAbortSetting>(db.GetDatabase());
421556 if (debug_checkpoint_abort == CheckpointAbort::DEBUG_ABORT_AFTER_FREE_LIST_WRITE) {
421557 throw FatalException("Checkpoint aborted after free list write because of PRAGMA checkpoint_abort flag");
421558 }
421559
421560 // We need to fsync BEFORE we write the header to ensure that all the previous blocks are written as well
421561 handle->Sync();
421562
421563 header_buffer.Clear();
421564 // if we are upgrading the database from version 64 -> version 65, we need to re-write the main header
421565 if (options.version_number.GetIndex() == 64 && options.storage_version.GetIndex() >= 4) {
421566 // rewrite the main header
421567 options.version_number = 65;
421568 MainHeader main_header = ConstructMainHeader(options.version_number.GetIndex());
421569 SerializeHeaderStructure<MainHeader>(main_header, header_buffer.buffer);
421570 // now write the header to the file
421571 ChecksumAndWrite(context, header_buffer, 0);
421572 header_buffer.Clear();
421573 }
421574
421575 // set the header inside the buffer
421576 MemoryStream serializer(Allocator::Get(db));
421577 header.Write(serializer);
421578 memcpy(header_buffer.buffer, serializer.GetData(), serializer.GetPosition());
421579 // now write the header to the file, active_header determines whether we write to h1 or h2
421580 // note that if active_header is h1 we write to h2, and vice versa
421582 ChecksumAndWrite(context, header_buffer, location);
421583 // switch active header to the other header
421586 handle->Sync();
421587 // Release the free fully freed blocks to the filesystem.
421588 TrimFreeBlocks(fully_freed_blocks);
421589}
MetadataManager & GetMetadataManager()
Returns a reference to the metadata manager of this block manager.
Definition duckdb.cpp:387155
unique_ptr< MetadataManager > metadata_manager
The metadata manager.
Definition duckdb.hpp:45371
vector< MetadataHandle > GetFreeListBlocks()
Return the blocks to which we will write the free list and modified blocks.
Definition duckdb.cpp:421419
::uint32_t uint32_t
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FileSync()

void duckdb::SingleFileBlockManager::FileSync ( )
overridevirtual

Sync changes to the underlying file.

Implements duckdb::BlockManager.

421591 {
421592 handle->Sync();
421593}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Truncate()

void duckdb::SingleFileBlockManager::Truncate ( )
overridevirtual

Truncate the underlying database file after a checkpoint.

Reimplemented from duckdb::BlockManager.

421396 {
421398
421399 lock_guard<mutex> guard(single_file_block_lock);
421400 idx_t blocks_to_truncate = 0;
421401 // reverse iterate over the free-list
421402 for (auto entry = free_list.rbegin(); entry != free_list.rend(); entry++) {
421403 auto block_id = *entry;
421404 if (block_id + 1 != max_block) {
421405 break;
421406 }
421407 blocks_to_truncate++;
421408 max_block--;
421409 }
421410 if (blocks_to_truncate == 0) {
421411 // nothing to truncate
421412 return;
421413 }
421414 // truncate the file
421415 free_list.erase(free_list.lower_bound(max_block), free_list.end());
421416 handle->Truncate(NumericCast<int64_t>(BLOCK_START + NumericCast<idx_t>(max_block) * GetBlockAllocSize()));
421417}
virtual void Truncate()
Truncate the underlying database file after a checkpoint.
Definition duckdb.cpp:387164
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InMemory()

bool duckdb::SingleFileBlockManager::InMemory ( )
inlineoverridevirtual

Whether or not the attached database is in-memory.

Implements duckdb::BlockManager.

420141 {
420142 return false;
420143 }
Here is the caller graph for this function:

◆ TotalBlocks()

idx_t duckdb::SingleFileBlockManager::TotalBlocks ( )
overridevirtual

Returns the number of total blocks.

Implements duckdb::BlockManager.

421287 {
421288 lock_guard<mutex> lock(single_file_block_lock);
421289 return NumericCast<idx_t>(max_block);
421290}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FreeBlocks()

idx_t duckdb::SingleFileBlockManager::FreeBlocks ( )
overridevirtual

Returns the number of free blocks.

Implements duckdb::BlockManager.

421292 {
421293 lock_guard<mutex> lock(single_file_block_lock);
421294 return free_list.size();
421295}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsRemote()

bool duckdb::SingleFileBlockManager::IsRemote ( )
overridevirtual

Whether or not the attached database is a remote file.

Reimplemented from duckdb::BlockManager.

421297 {
421298 return !handle->OnDiskFile();
421299}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Prefetch()

bool duckdb::SingleFileBlockManager::Prefetch ( )
overridevirtual

Whether or not to prefetch.

Reimplemented from duckdb::BlockManager.

421301 {
421302 switch (Settings::Get<StorageBlockPrefetchSetting>(db.GetDatabase())) {
421303 case StorageBlockPrefetch::NEVER:
421304 return false;
421305 case StorageBlockPrefetch::DEBUG_FORCE_ALWAYS:
421306 case StorageBlockPrefetch::ALWAYS_PREFETCH:
421307 return !InMemory();
421308 case StorageBlockPrefetch::REMOTE_ONLY:
421309 return IsRemote();
421310 default:
421311 throw InternalException("Unknown StorageBlockPrefetch type");
421312 }
421313}
bool InMemory() override
Whether or not the attached database is in-memory.
Definition duckdb.cpp:420141
bool IsRemote() override
Whether or not the attached database is a remote file.
Definition duckdb.cpp:421297
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetCheckpointIteration()

uint64_t duckdb::SingleFileBlockManager::GetCheckpointIteration ( ) const
inline

Return the checkpoint iteration of the file.

420154 {
420155 return iteration_count;
420156 }
Here is the caller graph for this function:

◆ GetVersionNumber()

uint64_t duckdb::SingleFileBlockManager::GetVersionNumber ( ) const

Return the version number of the file.

420594 {
420595 auto storage_version = options.storage_version.GetIndex();
420596 if (storage_version < 4) {
420597 return VERSION_NUMBER;
420598 }
420599 // Look up the matching version number.
420600 auto version_name = GetStorageVersionName(storage_version, false);
420601 return GetStorageVersion(version_name.c_str()).GetIndex();
420602}
const uint64_t VERSION_NUMBER
The version number default, lower and upper bounds of the database storage format.
Definition duckdb.cpp:425834
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetDBIdentifier()

data_ptr_t duckdb::SingleFileBlockManager::GetDBIdentifier ( )
inline

Return the database identifier.

420160 {
420161 return options.db_identifier;
420162 }

◆ LoadFreeList()

void duckdb::SingleFileBlockManager::LoadFreeList ( QueryContext context)
private

Loads the free list of the file.

421045 {
421046 MetaBlockPointer free_pointer(free_list_id, 0);
421047 if (!free_pointer.IsValid()) {
421048 // no free list
421049 return;
421050 }
421051 MetadataReader reader(GetMetadataManager(), free_pointer, nullptr, BlockReaderType::REGISTER_BLOCKS);
421052 auto free_list_count = reader.Read<uint64_t>(context);
421053 free_list.clear();
421054 for (idx_t i = 0; i < free_list_count; i++) {
421055 auto block = reader.Read<block_id_t>(context);
421056 free_list.insert(block);
421057 }
421058 auto multi_use_blocks_count = reader.Read<uint64_t>(context);
421059 multi_use_blocks.clear();
421060 for (idx_t i = 0; i < multi_use_blocks_count; i++) {
421061 auto block_id = reader.Read<block_id_t>(context);
421062 auto usage_count = reader.Read<uint32_t>(context);
421063 multi_use_blocks[block_id] = usage_count;
421064 }
421065 GetMetadataManager().Read(reader);
421066 GetMetadataManager().MarkBlocksAsModified();
421067}
idx_t free_list_id
The block id where the free list can be found.
Definition duckdb.cpp:420236
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Initialize()

void duckdb::SingleFileBlockManager::Initialize ( const DatabaseHeader & header,
const optional_idx block_alloc_size )
private

Initializes the database header. We pass the provided block allocation size as a parameter to detect inconsistencies with the file header.

421008 {
421009 free_list_id = header.free_list;
421010 meta_block = header.meta_block;
421011 iteration_count = header.iteration;
421012 max_block = NumericCast<block_id_t>(header.block_count);
421013 if (options.storage_version.IsValid()) {
421014 // storage version specified explicity - use requested storage version
421015 auto requested_compat_version = options.storage_version.GetIndex();
421016 if (requested_compat_version < header.serialization_compatibility) {
421017 throw InvalidInputException(
421018 "Error opening \"%s\": cannot initialize database with storage version %d - which is lower than what "
421019 "the database itself uses (%d). The storage version of an existing database cannot be lowered.",
421020 path, requested_compat_version, header.serialization_compatibility);
421021 }
421022 } else {
421023 // load storage version from header
421024 options.storage_version = header.serialization_compatibility;
421025 }
421026 if (header.serialization_compatibility > SerializationCompatibility::Latest().serialization_version) {
421027 throw InvalidInputException(
421028 "Error opening \"%s\": file was written with a storage version greater than the latest version supported "
421029 "by this DuckDB instance. Try opening the file with a newer version of DuckDB.",
421030 path);
421031 }
421032
421033 db.GetStorageManager().SetStorageVersion(options.storage_version.GetIndex());
421034
421035 if (block_alloc_size.IsValid() && block_alloc_size.GetIndex() != header.block_alloc_size) {
421036 throw InvalidInputException(
421037 "Error opening \"%s\": cannot initialize the same database with a different block size: provided block "
421038 "size: %llu, file block size: %llu",
421039 path, GetBlockAllocSize(), header.block_alloc_size);
421040 }
421041
421042 SetBlockAllocSize(header.block_alloc_size);
421043}
optional_idx block_alloc_size
The allocation size of blocks managed by this block manager. Defaults to DEFAULT_BLOCK_ALLOC_SIZE for...
Definition duckdb.hpp:45375
void SetBlockAllocSize(const optional_idx block_alloc_size_p)
Sets the block allocation size. This should only happen when initializing an existing database....
Definition duckdb.hpp:45325
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckChecksum() [1/2]

void duckdb::SingleFileBlockManager::CheckChecksum ( FileBuffer & block,
uint64_t location,
uint64_t delta,
bool skip_block_header = false ) const
private

Even with encryption enabled, the main header should be plaintext

We do have to decrypt other headers

420938 {
420939 uint64_t stored_checksum;
420940 uint64_t computed_checksum;
420941
420942 if (skip_block_header && delta > 0) {
420944 stored_checksum = Load<uint64_t>(block.InternalBuffer());
420945 computed_checksum = Checksum(block.buffer - delta, block.Size() + delta);
420946 } else {
420948 stored_checksum = Load<uint64_t>(block.InternalBuffer() + delta);
420949 computed_checksum = Checksum(block.buffer, block.Size());
420950 }
420951
420952 // verify the checksum
420953 if (stored_checksum != computed_checksum) {
420954 throw IOException("Corrupt database file: computed checksum %llu does not match stored checksum %llu in block "
420955 "at location %llu",
420956 computed_checksum, stored_checksum, location);
420957 }
420958}
uint64_t Checksum(uint8_t *buffer, size_t size)
Compute a checksum over a buffer of size size.
Definition duckdb.cpp:49970
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckChecksum() [2/2]

void duckdb::SingleFileBlockManager::CheckChecksum ( data_ptr_t start_ptr,
uint64_t delta,
bool skip_block_header = false ) const
private

Even with encryption enabled, the main header should be plaintext

We do have to decrypt other headers

420915 {
420916 uint64_t stored_checksum;
420917 uint64_t computed_checksum;
420918
420919 if (skip_block_header && delta > 0) {
420921 stored_checksum = Load<uint64_t>(start_ptr);
420922 computed_checksum = Checksum(start_ptr + DEFAULT_BLOCK_HEADER_STORAGE_SIZE, GetBlockSize() + delta);
420923 } else {
420925 stored_checksum = Load<uint64_t>(start_ptr + delta);
420926 computed_checksum = Checksum(start_ptr + GetBlockHeaderSize(), GetBlockSize());
420927 }
420928
420929 // verify the checksum
420930 if (stored_checksum != computed_checksum) {
420931 throw IOException("Corrupt database file: computed checksum %llu does not match stored checksum %llu in block "
420932 "at location %llu",
420933 computed_checksum, stored_checksum, start_ptr);
420934 }
420935}
Here is the call graph for this function:

◆ ReadAndChecksum()

void duckdb::SingleFileBlockManager::ReadAndChecksum ( QueryContext context,
FileBuffer & handle,
uint64_t location,
bool skip_block_header = false ) const
private

calculate delta header bytes (if any)

420961 {
420962 // read the buffer from disk
420963 block.Read(context, *handle, location);
420964
420967
420968 if (options.encryption_options.encryption_enabled && !skip_block_header) {
420969 auto key_id = options.encryption_options.derived_key_id;
420970 EncryptionEngine::DecryptBlock(db, key_id, block.InternalBuffer(), block.Size(), delta);
420971 }
420972
420973 CheckChecksum(block, location, delta, skip_block_header);
420974}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ChecksumAndWrite()

void duckdb::SingleFileBlockManager::ChecksumAndWrite ( QueryContext context,
FileBuffer & handle,
uint64_t location,
bool skip_block_header = false ) const
private

This happens only for the main database header We do not encrypt the main database header

zero out the last bytes of the block

420977 {
420979 uint64_t checksum;
420980
420981 if (skip_block_header && delta > 0) {
420984 memmove(block.InternalBuffer() + Storage::DEFAULT_BLOCK_HEADER_SIZE, block.buffer, block.Size());
420986 memset(block.InternalBuffer() + block.Size() + Storage::DEFAULT_BLOCK_HEADER_SIZE, 0, delta);
420987 checksum = Checksum(block.buffer - delta, block.Size() + delta);
420988 delta = 0;
420989 } else {
420990 checksum = Checksum(block.buffer, block.Size());
420991 }
420992
420993 Store<uint64_t>(checksum, block.InternalBuffer() + delta);
420994
420995 // encrypt if required
420996 unique_ptr<FileBuffer> temp_buffer_manager;
420997 if (options.encryption_options.encryption_enabled && !skip_block_header) {
420998 auto key_id = options.encryption_options.derived_key_id;
420999 temp_buffer_manager =
421000 make_uniq<FileBuffer>(BlockAllocator::Get(db), block.GetBufferType(), block.Size(), GetBlockHeaderSize());
421001 EncryptionEngine::EncryptBlock(db, key_id, block, *temp_buffer_manager, delta);
421002 temp_buffer_manager->Write(context, *handle, location);
421003 } else {
421004 block.Write(context, *handle, location);
421005 }
421006}
static void EncryptBlock(AttachedDatabase &attached_db, const string &key_id, FileBuffer &block, FileBuffer &temp_buffer_manager, uint64_t delta)
Encryption Functions.
Definition duckdb.cpp:51936
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetBlockLocation()

idx_t duckdb::SingleFileBlockManager::GetBlockLocation ( block_id_t block_id) const
private
421333 {
421334 return BLOCK_START + NumericCast<idx_t>(block_id) * GetBlockAllocSize();
421335}

◆ StoreEncryptedCanary()

void duckdb::SingleFileBlockManager::StoreEncryptedCanary ( AttachedDatabase & db,
MainHeader & main_header,
const string & key_id )
staticprivate
420611 {
420612 const_data_ptr_t key = EncryptionEngine::GetKeyFromCache(db.GetDatabase(), key_id);
420613 // Encrypt canary with the derived key
420614 shared_ptr<EncryptionState> encryption_state;
420615 auto encryption_version = static_cast<EncryptionTypes::EncryptionVersion>(main_header.GetEncryptionVersion());
420616 if (encryption_version > EncryptionTypes::V0_0 && encryption_version != EncryptionTypes::NONE) {
420617 // From Encryption Version 1+, always encrypt canary with GCM
420618 auto metadata = make_uniq<EncryptionStateMetadata>(
420619 EncryptionTypes::GCM, MainHeader::DEFAULT_ENCRYPTION_KEY_LENGTH, encryption_version);
420620 encryption_state =
420621 db.GetDatabase().GetEncryptionUtil(db.IsReadOnly())->CreateEncryptionState(std::move(metadata));
420622 } else {
420623 auto metadata = make_uniq<EncryptionStateMetadata>(
420624 static_cast<EncryptionTypes::CipherType>(main_header.GetEncryptionCipher()),
420625 MainHeader::DEFAULT_ENCRYPTION_KEY_LENGTH, encryption_version);
420626 encryption_state =
420627 db.GetDatabase().GetEncryptionUtil(db.IsReadOnly())->CreateEncryptionState(std::move(metadata));
420628 }
420629
420630 EncryptCanary(main_header, encryption_state, key);
420631}
static const_data_ptr_t GetKeyFromCache(DatabaseInstance &db, const string &key_name)
General key management wrapper functions.
Definition duckdb.cpp:51888

◆ StoreDBIdentifier()

void duckdb::SingleFileBlockManager::StoreDBIdentifier ( MainHeader & main_header,
const data_ptr_t db_identifier )
staticprivate
420633 {
420634 main_header.SetDBIdentifier(db_identifier);
420635}

◆ StoreEncryptionMetadata()

void duckdb::SingleFileBlockManager::StoreEncryptionMetadata ( MainHeader & main_header) const
private
420642 {
420643 // The first byte is the key derivation function (kdf).
420644 // The second byte is for the usage of AAD.
420645 // The third byte is for the cipher.
420646 // The subsequent byte is empty.
420647 // The last 4 bytes are the key length.
420648 auto metadata_stream = make_uniq<MemoryStream>(ENCRYPTION_METADATA_LEN);
420649
420650 WriteEncryptionData<uint8_t>(*metadata_stream, options.encryption_options.kdf);
420651 WriteEncryptionData<uint8_t>(*metadata_stream, options.encryption_options.additional_authenticated_data);
420652 WriteEncryptionData<uint8_t>(*metadata_stream, db.GetStorageManager().GetCipher());
420653 WriteEncryptionData<uint8_t>(*metadata_stream, options.encryption_options.encryption_version);
420654 WriteEncryptionData<uint32_t>(*metadata_stream, options.encryption_options.key_length);
420655
420656 main_header.SetEncryptionMetadata(metadata_stream->GetData());
420657}

◆ WriteEncryptionData()

template<typename T>
void duckdb::SingleFileBlockManager::WriteEncryptionData ( MemoryStream & stream,
const T & val )
staticprivate
420638 {
420639 stream.WriteData(reinterpret_cast<const_data_ptr_t>(&val), sizeof(val));
420640}

◆ CheckAndAddEncryptionKey() [1/2]

void duckdb::SingleFileBlockManager::CheckAndAddEncryptionKey ( MainHeader & main_header,
string & user_key )
private

Check and adding Encryption Keys.

Get the database identifier.

Check if the correct key is used to decrypt the database

420659 {
420661 uint8_t db_identifier[MainHeader::DB_IDENTIFIER_LEN];
420662 memset(db_identifier, 0, MainHeader::DB_IDENTIFIER_LEN);
420663 memcpy(db_identifier, main_header.GetDBIdentifier(), MainHeader::DB_IDENTIFIER_LEN);
420664
420666 // Derive the encryption key and add it to cache
420668 EncryptionKeyManager::DeriveKey(user_key, db_identifier, derived_key);
420669
420670 shared_ptr<EncryptionState> encryption_state;
420671 auto encryption_version = static_cast<EncryptionTypes::EncryptionVersion>(main_header.GetEncryptionVersion());
420672 if (encryption_version > EncryptionTypes::V0_0 && encryption_version != EncryptionTypes::NONE) {
420673 // From Encryption Version 1+, always encrypt canary with GCM
420674 auto metadata = make_uniq<EncryptionStateMetadata>(
420675 EncryptionTypes::GCM, MainHeader::DEFAULT_ENCRYPTION_KEY_LENGTH, encryption_version);
420676 encryption_state =
420677 db.GetDatabase().GetEncryptionUtil(db.IsReadOnly())->CreateEncryptionState(std::move(metadata));
420678 } else {
420679 auto metadata = make_uniq<EncryptionStateMetadata>(
420680 static_cast<EncryptionTypes::CipherType>(main_header.GetEncryptionCipher()),
420681 MainHeader::DEFAULT_ENCRYPTION_KEY_LENGTH, encryption_version);
420682 encryption_state =
420683 db.GetDatabase().GetEncryptionUtil(db.IsReadOnly())->CreateEncryptionState(std::move(metadata));
420684 }
420685
420686 if (!DecryptCanary(main_header, encryption_state, derived_key)) {
420687 throw InvalidInputException("Wrong encryption key used to open the database file");
420688 }
420689
420690 options.encryption_options.derived_key_id = EncryptionEngine::AddKeyToCache(db.GetDatabase(), derived_key);
420691 auto &catalog = db.GetCatalog().Cast<DuckCatalog>();
420692 catalog.SetEncryptionKeyId(options.encryption_options.derived_key_id);
420693 catalog.SetIsEncrypted();
420694
420695 std::fill(user_key.begin(), user_key.end(), 0);
420696 user_key.clear();
420697}
::uint8_t uint8_t
bool DecryptCanary(MainHeader &main_header, const shared_ptr< EncryptionState > &encryption_state, data_ptr_t derived_key)
Definition duckdb.cpp:420377
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckAndAddEncryptionKey() [2/2]

void duckdb::SingleFileBlockManager::CheckAndAddEncryptionKey ( MainHeader & main_header)
private
420699 {
420700 return CheckAndAddEncryptionKey(main_header, *options.encryption_options.user_key);
420701}

◆ GetFreeListBlocks()

vector< MetadataHandle > duckdb::SingleFileBlockManager::GetFreeListBlocks ( )
private

Return the blocks to which we will write the free list and modified blocks.

421419 {
421420 vector<MetadataHandle> free_list_blocks;
421422
421423 // reserve all blocks that we are going to write the free list to
421424 // since these blocks are no longer free we cannot just include them in the free list!
421425 auto block_size = metadata_manager.GetMetadataBlockSize() - sizeof(idx_t);
421426 idx_t allocated_size = 0;
421427 while (true) {
421428 idx_t free_list_count;
421429 idx_t multi_use_blocks_count;
421430 {
421431 lock_guard<mutex> guard(single_file_block_lock);
421432 free_list_count =
421433 free_list.size() + modified_blocks.size() + free_blocks_in_use.size() + newly_used_blocks.size();
421434 multi_use_blocks_count = multi_use_blocks.size();
421435 }
421436 auto free_list_size = sizeof(uint64_t) + sizeof(block_id_t) * free_list_count;
421437 auto multi_use_blocks_size =
421438 sizeof(uint64_t) + (sizeof(block_id_t) + sizeof(uint32_t)) * multi_use_blocks_count;
421439 auto metadata_blocks =
421440 sizeof(uint64_t) + (sizeof(block_id_t) + sizeof(idx_t)) * GetMetadataManager().BlockCount();
421441 auto total_size = free_list_size + multi_use_blocks_size + metadata_blocks;
421442 if (total_size < allocated_size) {
421443 break;
421444 }
421445 auto free_list_handle = GetMetadataManager().AllocateHandle();
421446 free_list_blocks.push_back(std::move(free_list_handle));
421447 allocated_size += block_size;
421448 }
421449
421450 return free_list_blocks;
421451}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TrimFreeBlocks()

void duckdb::SingleFileBlockManager::TrimFreeBlocks ( const set< block_id_t > & blocks)
private
421613 {
421614 if (!DBConfig::Get(db).options.trim_free_blocks) {
421615 return;
421616 }
421617 lock_guard<mutex> lock(single_file_block_lock);
421618 for (auto itr = blocks.begin(); itr != blocks.end(); ++itr) {
421619 if (!free_list.count(*itr)) {
421620 continue;
421621 }
421622 block_id_t first = *itr;
421623 block_id_t last = first;
421624 // Find end of contiguous range.
421625 for (++itr; itr != blocks.end() && (*itr == last + 1) && free_list.count(*itr); ++itr) {
421626 last = *itr;
421627 }
421628 // We are now one too far.
421629 --itr;
421630 // Trim the range.
421631 TrimFreeBlockRange(first, last);
421632 }
421633}
unordered_map< block_id_t, weak_ptr< BlockHandle > > blocks
A mapping of block id -> BlockHandle.
Definition duckdb.hpp:45369

◆ TrimFreeBlockRange()

void duckdb::SingleFileBlockManager::TrimFreeBlockRange ( block_id_t start,
block_id_t end )
private
421608 {
421609 auto block_count = NumericCast<idx_t>(end + 1 - start);
421610 handle->Trim(BLOCK_START + (NumericCast<idx_t>(start) * GetBlockAllocSize()), block_count * GetBlockAllocSize());
421611}

◆ IncreaseBlockReferenceCountInternal()

void duckdb::SingleFileBlockManager::IncreaseBlockReferenceCountInternal ( block_id_t block_id)
private
421176 {
421177 D_ASSERT(block_id >= 0);
421178 D_ASSERT(block_id < max_block);
421179 D_ASSERT(free_list.find(block_id) == free_list.end());
421180 auto entry = multi_use_blocks.find(block_id);
421181 if (entry != multi_use_blocks.end()) {
421182 entry->second++;
421183 } else {
421184 multi_use_blocks[block_id] = 2;
421185 }
421186}

◆ VerifyBlocks()

void duckdb::SingleFileBlockManager::VerifyBlocks ( const unordered_map< block_id_t, idx_t > & block_usage_count)
overrideprivatevirtual

Verify the block usage count.

Reimplemented from duckdb::BlockManager.

421188 {
421189 // probably don't need this?
421190 lock_guard<mutex> lock(single_file_block_lock);
421191 // all blocks should be accounted for - either in the block_usage_count, or in the free list
421192 set<block_id_t> referenced_blocks;
421193 for (auto &block : block_usage_count) {
421194 if (block.first == INVALID_BLOCK) {
421195 continue;
421196 }
421197 if (block.first >= max_block) {
421198 throw InternalException("Block %lld is used, but it is bigger than the max block %d", block.first,
421199 max_block);
421200 }
421201 referenced_blocks.insert(block.first);
421202 if (block.second > 1) {
421203 // multi-use block
421204 auto entry = multi_use_blocks.find(block.first);
421205 if (entry == multi_use_blocks.end()) {
421206 throw InternalException("Block %lld was used %llu times, but not present in multi_use_blocks",
421207 block.first, block.second);
421208 }
421209 if (entry->second != block.second) {
421210 throw InternalException(
421211 "Block %lld was used %llu times, but multi_use_blocks says it is used %llu times", block.first,
421212 block.second, entry->second);
421213 }
421214 } else {
421215 D_ASSERT(block.second > 0);
421216 auto entry = free_list.find(block.first);
421217 if (entry != free_list.end()) {
421218 throw InternalException("Block %lld was used, but it is present in the free list", block.first);
421219 }
421220 }
421221 }
421222 for (auto &newly_used_block : newly_used_blocks) {
421223 referenced_blocks.insert(newly_used_block);
421224 }
421225 for (auto &free_block : free_list) {
421226 referenced_blocks.insert(free_block);
421227 }
421228 for (auto &free_block : free_blocks_in_use) {
421229 referenced_blocks.insert(free_block);
421230 }
421231 if (referenced_blocks.size() != NumericCast<idx_t>(max_block)) {
421232 // not all blocks are accounted for
421233 string missing_blocks;
421234 for (block_id_t i = 0; i < max_block; i++) {
421235 if (referenced_blocks.find(i) == referenced_blocks.end()) {
421236 if (!missing_blocks.empty()) {
421237 missing_blocks += ", ";
421238 }
421239 missing_blocks += to_string(i);
421240 }
421241 }
421242 string free_list_str;
421243 for (auto &block : free_list) {
421244 if (!free_list_str.empty()) {
421245 free_list_str += ", ";
421246 }
421247 free_list_str += to_string(block);
421248 }
421249 string block_usage_str;
421250 for (auto &entry : block_usage_count) {
421251 if (!block_usage_str.empty()) {
421252 block_usage_str += ", ";
421253 }
421254 block_usage_str += to_string(entry.first);
421255 }
421256 string multi_use_blocks_str;
421257 for (auto &entry : multi_use_blocks) {
421258 if (!multi_use_blocks_str.empty()) {
421259 multi_use_blocks_str += ", ";
421260 }
421261 multi_use_blocks_str += to_string(entry.first);
421262 }
421263 string newly_used_blocks_str;
421264 for (auto &block : newly_used_blocks) {
421265 if (!newly_used_blocks_str.empty()) {
421266 newly_used_blocks_str += ", ";
421267 }
421268 newly_used_blocks_str += to_string(block);
421269 }
421270
421271 throw InternalException(
421272 "Block verification failed - blocks \"%s\" were not found as being used OR marked as free\nMax block: "
421273 "%d\nBlock usage: %s\nFree list: %s\nMulti-use blocks: %s\nNewly used blocks: %s",
421274 missing_blocks, max_block, block_usage_str, free_list_str, multi_use_blocks_str, newly_used_blocks_str);
421275 }
421276}
std::string to_string(const T &value)
Definition duckdb.cpp:19425
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AddStorageVersionTag()

void duckdb::SingleFileBlockManager::AddStorageVersionTag ( )
private
420590 {
420591 db.tags["storage_version"] = GetStorageVersionName(options.storage_version.GetIndex(), true);
420592}

◆ GetFreeBlockIdInternal()

block_id_t duckdb::SingleFileBlockManager::GetFreeBlockIdInternal ( FreeBlockType type)
private
421073 {
421074 lock_guard<mutex> lock(single_file_block_lock);
421075 block_id_t block_id;
421076 if (!free_list.empty()) {
421077 // The free list is not empty, so we take its first element.
421078 block_id = *free_list.begin();
421079 // erase the entry from the free list again
421080 free_list.erase(free_list.begin());
421081 } else {
421082 block_id = max_block++;
421083 }
421084 // add the entry to the list of newly used blocks
421085 if (type == FreeBlockType::NEWLY_USED_BLOCK) {
421086 newly_used_blocks.insert(block_id);
421087 }
421088 if (BlockIsRegistered(block_id)) {
421089 throw InternalException("Free block %d is already registered", block_id);
421090 }
421091 return block_id;
421092}

◆ AddFreeBlock()

bool duckdb::SingleFileBlockManager::AddFreeBlock ( unique_lock< mutex > & lock,
block_id_t block_id )
private

Adds a free block to the free_list, returns true if it was added to the regular free_list.

421473 {
421474 if (!lock.owns_lock()) {
421475 throw InternalException("AddFreeBlock must be called while holding the lock");
421476 }
421477 shared_ptr<BlockHandle> block = TryGetBlock(block_id);
421478 if (!block) {
421479 // the block does not exist
421480 // regular free block
421481 free_list.insert(block_id);
421482 return true;
421483 }
421484 // the block exists - add to blocks in use
421485 free_blocks_in_use.insert(block_id);
421486
421487 // release the lock while destroying the block since the block destructor can call UnregisterBlock
421488 lock.unlock();
421489 block.reset();
421490 lock.lock();
421491 return false;
421492}
Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ multi_use_blocks

unordered_map<block_id_t, uint32_t> duckdb::SingleFileBlockManager::multi_use_blocks
private

The list of multi-use blocks (i.e. blocks that have >1 reference in the file) When a multi-use block is marked as modified, the reference count is decreased by 1 instead of directly Appending the block to the modified_blocks list


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