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

FileLogStorage implements a file-based logging system in CSV format. It implements CSVLogStorage to provide persistent log storage in CSV files. The FileLogStorage can operate in normalized (separate files for entries and contexts) or denormalized mode (single file). More...

#include <duckdb.hpp>

Inheritance diagram for duckdb::FileLogStorage:
Collaboration diagram for duckdb::FileLogStorage:

Classes

struct  TableWriter
 Writer for a table. More...

Public Member Functions

 FileLogStorage (DatabaseInstance &db)
const string GetStorageName () override
void Truncate () override
 Implement LogStorage interface.
unique_ptr< TableRef > BindReplace (ClientContext &context, TableFunctionBindInput &input, LoggingTargetTable table) override
 Bind replace function to scan the different tables.
Public Member Functions inherited from duckdb::CSVLogStorage
 CSVLogStorage (DatabaseInstance &db, bool normalize, idx_t buffer_size)
Public Member Functions inherited from duckdb::BufferingLogStorage
 BufferingLogStorage (DatabaseInstance &db_p, idx_t buffer_size, bool normalize)
void WriteLogEntry (timestamp_t timestamp, LogLevel level, const string &log_type, const string &log_message, const RegisteredLoggingContext &context) final
 (Partially) Implements LogStorage API
void WriteLogEntries (DataChunk &chunk, const RegisteredLoggingContext &context) final
 Write out the chunk to the buffers.
void FlushAll () final
 Flushes buffers for all tables.
void Flush (LoggingTargetTable table) final
 Flushes buffer for a specific table.
void UpdateConfig (DatabaseInstance &db, case_insensitive_map_t< Value > &config) override
 Apply a new log storage configuration.
bool IsEnabled (LoggingTargetTable table) override
 Returns whether the table is enabled for this storage.
Public Member Functions inherited from duckdb::LogStorage
virtual DUCKDB_API bool CanScan (LoggingTargetTable table)
 READING (OPTIONAL).
virtual DUCKDB_API unique_ptr< LogStorageScanState > CreateScanState (LoggingTargetTable table) const
virtual DUCKDB_API bool Scan (LogStorageScanState &state, DataChunk &result) const
virtual DUCKDB_API void InitializeScan (LogStorageScanState &state) const

Protected Member Functions

void UpdateConfigInternal (DatabaseInstance &db, case_insensitive_map_t< Value > &config) override
 Implement CSVLogStorage interface.
void BeforeFlush (LoggingTargetTable table, DataChunk &chunk) override
 Lazily initializes the CSV files before first flush.
void AfterFlush (LoggingTargetTable table, DataChunk &chunk) override
 Calls Sync on the FileWriters to ensure a LogStorage Flush is flushed to disk immediately.
Protected Member Functions inherited from duckdb::CSVLogStorage
void FlushChunk (LoggingTargetTable table, DataChunk &chunk) final
 Implement the BufferingLogStorage interface.
void ResetAllBuffers () override
 Resets all buffers and state.
void RegisterWriter (LoggingTargetTable table, unique_ptr< CSVWriter > writer)
 Helper functions.
CSVWriter & GetWriter (LoggingTargetTable table)
 Returns the writer for a table.
void SetWriterConfigs (CSVWriter &Writer, vector< string > column_names)
 Configure a CSV writer by initializing its settings with the writer_options and reader_options settings.
CSVWriterOptions & GetCSVWriterOptions ()
 Allows child classes to manipulate options.
CSVReaderOptions & GetCSVReaderOptions ()
 Allows child classes to manipulate options.
Protected Member Functions inherited from duckdb::BufferingLogStorage
void FlushAllInternal ()
 Helper methods.
void FlushInternal (LoggingTargetTable table)
 Flushes one of the tables.
bool IsEnabledInternal (LoggingTargetTable table)
 Whether a specific table is available in the log storage.
idx_t GetBufferLimit () const

Private Member Functions

void InitializeFile (DatabaseInstance &db, LoggingTargetTable table)
 Intialize the csv file for table.
void Initialize (LoggingTargetTable table)
 Ensures the table is initialized, used in lazy initialization. If already initialized this will NOP.
unique_ptr< TableRef > BindReplaceInternal (ClientContext &context, TableFunctionBindInput &input, const string &path, const string &select_clause, const string &csv_columns)
 Internal helper function to handle the BindReplace generation.
void SetPaths (const string &base_path)

Static Private Member Functions

static unique_ptr< BufferedFileWriter > InitializeFileWriter (DatabaseInstance &db, const string &path)
 Initialize the filewriter to be passed to the CSVWriter.

Private Attributes

DatabaseInstance & db
 DB reference to get the DB filesystem.
map< LoggingTargetTable, TableWriter > tables
 The table info per table.
string base_path
 Base path to generate the file paths from.

Additional Inherited Members

Static Public Member Functions inherited from duckdb::LogStorage
static vector< LogicalType > GetSchema (LoggingTargetTable table)
static vector< string > GetColumnNames (LoggingTargetTable table)
Protected Attributes inherited from duckdb::BufferingLogStorage
mutex lock
 lock to be used by this class and child classes to ensure thread safety TODO: maybe remove and delegate thread-safety to LogManager?
bool normalize_contexts = true
 Switches between using false = use LoggingTargetTable::ALL_LOGS, true = use LoggingTargetTable::LOG_ENTIRES + LoggingTargetTable::CONTEXTS.

Detailed Description

FileLogStorage implements a file-based logging system in CSV format. It implements CSVLogStorage to provide persistent log storage in CSV files. The FileLogStorage can operate in normalized (separate files for entries and contexts) or denormalized mode (single file).

Constructor & Destructor Documentation

◆ FileLogStorage()

duckdb::FileLogStorage::FileLogStorage ( DatabaseInstance & db)
explicit
260175 : CSVLogStorage(db_p, true, STANDARD_VECTOR_SIZE), db(db_p) {
260176 tables[LoggingTargetTable::ALL_LOGS] = TableWriter();
260177 tables[LoggingTargetTable::LOG_CONTEXTS] = TableWriter();
260178 tables[LoggingTargetTable::LOG_ENTRIES] = TableWriter();
260179
260180 // Set storage specific defaults
260182 GetCSVReaderOptions().dialect_options.state_machine_options.delimiter = CSVOption<string>(",");
260183}
CSVReaderOptions & GetCSVReaderOptions()
Allows child classes to manipulate options.
Definition duckdb.cpp:260109
CSVWriterOptions & GetCSVWriterOptions()
Allows child classes to manipulate options.
Definition duckdb.cpp:260113
DatabaseInstance & db
DB reference to get the DB filesystem.
Definition duckdb.hpp:39734
map< LoggingTargetTable, TableWriter > tables
The table info per table.
Definition duckdb.hpp:39747
@ WRITE_BEFORE
Definition duckdb.cpp:50829
DialectOptions dialect_options
See struct above.
Definition duckdb.hpp:51726
CSVOption< string > delimiter
Delimiter to separate columns within each line.
Definition duckdb.hpp:46401
CSVNewLineMode newline_writing_mode
How to write newlines.
Definition duckdb.cpp:50846
Writer for a table.
Definition duckdb.hpp:39737

◆ ~FileLogStorage()

duckdb::FileLogStorage::~FileLogStorage ( )
override
260185 {
260186}

Member Function Documentation

◆ GetStorageName()

const string duckdb::FileLogStorage::GetStorageName ( )
inlineoverridevirtual

Implements duckdb::LogStorage.

39700 {
39701 return "FileLogStorage";
39702 }

◆ Truncate()

void duckdb::FileLogStorage::Truncate ( )
overridevirtual

Implement LogStorage interface.

Truncates the csv files

Reimplemented from duckdb::BufferingLogStorage.

260243 {
260244 lock_guard<mutex> lck(lock);
260245
260246 // Reset buffers
260247 ResetAllBuffers();
260248
260249 for (const auto &it : tables) {
260250 auto &file_writer = it.second.file_writer;
260251 if (!file_writer) {
260252 continue;
260253 }
260254 // Truncate the file writer
260255 file_writer->Truncate(0);
260256 // Re-initialize the corresponding CSVWriter
260257 GetWriter(it.first).Initialize(true);
260258 }
260259}
mutex lock
lock to be used by this class and child classes to ensure thread safety TODO: maybe remove and delega...
Definition duckdb.hpp:39592
CSVWriter & GetWriter(LoggingTargetTable table)
Returns the writer for a table.
Definition duckdb.cpp:260081
void ResetAllBuffers() override
Resets all buffers and state.
Definition duckdb.cpp:260044
void Initialize(bool force=false)
Writes header and prefix if necessary.
Definition duckdb.cpp:51037
Here is the call graph for this function:

◆ BindReplace()

unique_ptr< TableRef > duckdb::FileLogStorage::BindReplace ( ClientContext & context,
TableFunctionBindInput & input,
LoggingTargetTable table )
overridevirtual

Bind replace function to scan the different tables.

Reimplemented from duckdb::LogStorage.

260390 {
260391 lock_guard<mutex> lck(lock);
260392
260393 // We only allow scanning enabled tables
260394 if (!IsEnabledInternal(table)) {
260395 return nullptr;
260396 }
260397
260398 // We start by flushing the table to ensure we scan the latest version
260399 FlushInternal(table);
260400
260401 if (normalize_contexts && table == LoggingTargetTable::ALL_LOGS) {
260402 throw InvalidConfigurationException("Can not scan ALL_LOGS table when logs are normalized");
260403 }
260404 if (!normalize_contexts && table != LoggingTargetTable::ALL_LOGS) {
260405 throw InvalidConfigurationException("Can only scan ALL_LOGS table when logs are normalized");
260406 }
260407
260408 string select = "SELECT *";
260409 string path = tables[table].path;
260410
260411 string columns;
260412 if (table == LoggingTargetTable::LOG_ENTRIES) {
260413 columns = "'context_id': 'UBIGINT', 'timestamp': 'TIMESTAMP WITH TIME ZONE', 'type': 'VARCHAR', 'log_level': "
260414 "'VARCHAR' , "
260415 "'message': 'VARCHAR'";
260416 } else if (table == LoggingTargetTable::LOG_CONTEXTS) {
260417 columns = "'context_id': 'UBIGINT', 'scope': 'VARCHAR', 'connection_id': 'UBIGINT', 'transaction_id': "
260418 "'UBIGINT', 'query_id': 'UBIGINT', 'thread_id': 'UBIGINT'";
260419 } else if (table == LoggingTargetTable::ALL_LOGS) {
260420 select = "SELECT context_id, scope, connection_id, transaction_id, query_id, thread_id, timestamp, type, "
260421 "log_level, message ";
260422 columns = "'context_id': 'UBIGINT', 'scope': 'VARCHAR', 'connection_id': 'UBIGINT', 'transaction_id': "
260423 "'UBIGINT', 'query_id': 'UBIGINT', 'thread_id': 'UBIGINT', 'timestamp': 'TIMESTAMP WITH TIME ZONE', "
260424 "'type': "
260425 "'VARCHAR', 'log_level': 'VARCHAR' , 'message': 'VARCHAR'";
260426 } else {
260427 throw InternalException("Invalid logging target table");
260428 }
260429
260430 return BindReplaceInternal(context, input, path, select, columns);
260431}
bool normalize_contexts
Switches between using false = use LoggingTargetTable::ALL_LOGS, true = use LoggingTargetTable::LOG_E...
Definition duckdb.hpp:39595
void FlushInternal(LoggingTargetTable table)
Flushes one of the tables.
Definition duckdb.cpp:260625
bool IsEnabledInternal(LoggingTargetTable table)
Whether a specific table is available in the log storage.
Definition duckdb.cpp:260018
unique_ptr< TableRef > BindReplaceInternal(ClientContext &context, TableFunctionBindInput &input, const string &path, const string &select_clause, const string &csv_columns)
Internal helper function to handle the BindReplace generation.
Definition duckdb.cpp:260373
GMat select(const GMat &src1, const GMat &src2, const GMat &mask)
Here is the call graph for this function:

◆ UpdateConfigInternal()

void duckdb::FileLogStorage::UpdateConfigInternal ( DatabaseInstance & db,
case_insensitive_map_t< Value > & config )
overrideprotectedvirtual

Implement CSVLogStorage interface.

Handles the config related to the FileLogStorage

We implicitly set normalize to false when a path ending in .csv is specified

Reimplemented from duckdb::CSVLogStorage.

260299 {
260300 auto config_copy = config;
260301
260302 string new_path;
260303 bool normalize_contexts_new_value = normalize_contexts;
260304 bool normalize_set_explicitly = false;
260305 bool require_reinitializing_files = false;
260306
260307 vector<string> to_remove;
260308 for (const auto &it : config_copy) {
260309 auto key = StringUtil::Lower(it.first);
260310 if (key == "path") {
260311 auto path_value = it.second.ToString();
260313 if (!normalize_set_explicitly && StringUtil::EndsWith(path_value, ".csv")) {
260314 normalize_contexts_new_value = false;
260315 }
260316 new_path = path_value;
260317 to_remove.push_back(it.first);
260318 } else if (key == "normalize") {
260319 normalize_set_explicitly = true;
260320 normalize_contexts_new_value = it.second.GetValue<bool>();
260321 to_remove.push_back(it.first);
260322 } else if (key == "delim") {
260323 require_reinitializing_files = true;
260324 }
260325 }
260326
260327 if (StringUtil::EndsWith(new_path, ".csv") && normalize_contexts_new_value) {
260328 throw InvalidConfigurationException(
260329 "Can not set path to '%s' while normalize is true. Normalize will make DuckDB write multiple log files to "
260330 "more efficiently store log entries. Please specify a directory path instead of a csv file path, or set "
260331 "normalize to false.",
260332 new_path);
260333 }
260334
260335 // If any writer is initialized, we flush first:
260336 // - when switching between normalized and denormalized, this is necessary since we are changing the buffer schema
260337 // - when simply changing the path, it avoids writing log entries written before this change to end up in the new
260338 // file
260339 bool initialized = false;
260340 for (auto &it : tables) {
260341 initialized |= it.second.initialized;
260342 }
260343 if (initialized) {
260345 }
260346
260347 require_reinitializing_files |= normalize_contexts != normalize_contexts_new_value;
260348 normalize_contexts = normalize_contexts_new_value;
260349
260350 // Reset the buffers to ensure they have the correct schema
260351 if (require_reinitializing_files) {
260352 ResetAllBuffers();
260353
260354 // Mark tables as uninitialized
260355 for (auto &table : tables) {
260356 table.second.initialized = false;
260357 }
260358 }
260359
260360 // Apply any path change
260361 if (new_path != base_path) {
260362 base_path = new_path;
260363 SetPaths(new_path);
260364 }
260365
260366 for (const auto &it : to_remove) {
260367 config_copy.erase(it);
260368 }
260369
260371}
void FlushAllInternal()
Helper methods.
Definition duckdb.cpp:260616
void UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t< Value > &config) override
Implements CSVLogStorage specific config handling.
Definition duckdb.cpp:260049
string base_path
Base path to generate the file paths from.
Definition duckdb.hpp:39750
static DUCKDB_API string Lower(const string &str)
Convert a string to lowercase.
Definition duckdb.cpp:109630
static DUCKDB_API bool EndsWith(const string &str, const string &suffix)
Returns true if the target string ends with the given suffix.
Definition duckdb.cpp:109384
Here is the call graph for this function:

◆ BeforeFlush()

void duckdb::FileLogStorage::BeforeFlush ( LoggingTargetTable table,
DataChunk & chunk )
overrideprotectedvirtual

Lazily initializes the CSV files before first flush.

Reimplemented from duckdb::CSVLogStorage.

260261 {
260262 // Lazily initialize the files
260263 Initialize(table);
260264}
void Initialize(LoggingTargetTable table)
Ensures the table is initialized, used in lazy initialization. If already initialized this will NOP.
Definition duckdb.cpp:260270
Here is the call graph for this function:

◆ AfterFlush()

void duckdb::FileLogStorage::AfterFlush ( LoggingTargetTable table,
DataChunk & chunk )
overrideprotectedvirtual

Calls Sync on the FileWriters to ensure a LogStorage Flush is flushed to disk immediately.

Reimplemented from duckdb::CSVLogStorage.

260266 {
260267 tables[table].file_writer->Sync();
260268}

◆ InitializeFile()

void duckdb::FileLogStorage::InitializeFile ( DatabaseInstance & db,
LoggingTargetTable table )
private

Intialize the csv file for table.

260188 {
260189 auto &table_writer = tables[table];
260190
260191 // reset the files writer, we may be re-initializing it here and otherwise we hold 2 handles to the same file
260192 table_writer.file_writer.reset();
260193
260194 // (re)initialize the file writer
260195 table_writer.file_writer = InitializeFileWriter(db, table_writer.path);
260196 auto file_writer = table_writer.file_writer.get();
260197
260198 // Create CSV writer that writes to file
260199 auto column_names = GetColumnNames(table);
260200
260201 // Configure writer
260202 auto csv_writer = make_uniq<CSVWriter>(*file_writer, column_names, false);
260203 SetWriterConfigs(*csv_writer, column_names);
260204 bool should_write_header = file_writer->handle->GetFileSize() == 0;
260205
260206 // We write the header only if the file was empty: when appending to the file we don't
260207 csv_writer->options.dialect_options.header = {should_write_header, true};
260208
260209 // Initialize the writer, this writes out the header if required
260210 csv_writer->Initialize();
260211
260212 // Needed to ensure we correctly start with a newline
260213 csv_writer->SetWrittenAnything(true);
260214
260215 RegisterWriter(table, std::move(csv_writer));
260216
260217 // Ensures that the file is fully initialized when this function returns
260218 file_writer->Sync();
260219
260220 table_writer.initialized = true;
260221}
void RegisterWriter(LoggingTargetTable table, unique_ptr< CSVWriter > writer)
Helper functions.
Definition duckdb.cpp:260077
void SetWriterConfigs(CSVWriter &Writer, vector< string > column_names)
Configure a CSV writer by initializing its settings with the writer_options and reader_options settin...
Definition duckdb.cpp:260100
static unique_ptr< BufferedFileWriter > InitializeFileWriter(DatabaseInstance &db, const string &path)
Initialize the filewriter to be passed to the CSVWriter.
Definition duckdb.cpp:260223
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializeFileWriter()

unique_ptr< BufferedFileWriter > duckdb::FileLogStorage::InitializeFileWriter ( DatabaseInstance & db,
const string & path )
staticprivate

Initialize the filewriter to be passed to the CSVWriter.

260223 {
260224 auto &fs = db.GetFileSystem();
260225
260226 // Create parent directories if non existent
260227 auto pos = path.find_last_of("/\\");
260228 if (pos != path.npos) {
260229 fs.CreateDirectoriesRecursive(path.substr(0, pos));
260230 }
260231
260232 FileOpenFlags flags;
260233 if (!fs.FileExists(path)) {
260235 FileFlags::FILE_FLAGS_FILE_CREATE_NEW | FileCompressionType::UNCOMPRESSED;
260236 } else {
260238 }
260239
260240 return make_uniq<BufferedFileWriter>(fs, path, flags);
260241}
static constexpr FileOpenFlags FILE_FLAGS_FILE_CREATE_NEW
Always create a new file. If a file exists, the file is truncated. Cannot be used together with CREAT...
Definition duckdb.hpp:7858
static constexpr FileOpenFlags FILE_FLAGS_DISABLE_LOGGING
Disables logging to avoid infinite loops when using FileHandle-backed log storage.
Definition duckdb.hpp:7879
static constexpr FileOpenFlags FILE_FLAGS_WRITE
Open file with write access.
Definition duckdb.hpp:7852
static constexpr FileOpenFlags FILE_FLAGS_APPEND
Open file in append mode.
Definition duckdb.hpp:7861
Here is the caller graph for this function:

◆ Initialize()

void duckdb::FileLogStorage::Initialize ( LoggingTargetTable table)
private

Ensures the table is initialized, used in lazy initialization. If already initialized this will NOP.

260270 {
260271 auto &table_writer = tables[table];
260272 if (!table_writer.initialized) {
260273 if (table_writer.path.empty()) {
260274 throw InvalidConfigurationException("Failed to initialize file log storage table, path wasn't set");
260275 }
260276
260277 InitializeFile(db, table);
260278 }
260279}
void InitializeFile(DatabaseInstance &db, LoggingTargetTable table)
Intialize the csv file for table.
Definition duckdb.cpp:260188
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BindReplaceInternal()

unique_ptr< TableRef > duckdb::FileLogStorage::BindReplaceInternal ( ClientContext & context,
TableFunctionBindInput & input,
const string & path,
const string & select_clause,
const string & csv_columns )
private

Internal helper function to handle the BindReplace generation.

260375 {
260376 string sub_query_string;
260377
260378 string escaped_path = KeywordHelper::WriteOptionallyQuoted(path);
260379 sub_query_string =
260380 StringUtil::Format("%s FROM read_csv_auto(%s, columns={%s})", select_clause, escaped_path, csv_columns);
260381
260382 Parser parser(context.GetParserOptions());
260383 parser.ParseQuery(sub_query_string);
260384 auto select_stmt = unique_ptr_cast<SQLStatement, SelectStatement>(std::move(parser.statements[0]));
260385
260386 return duckdb::make_uniq<SubqueryRef>(std::move(select_stmt));
260387}
static string WriteOptionallyQuoted(const string &text, char quote='"', bool allow_caps = true, KeywordCategory category = KeywordCategory::KEYWORD_NONE)
Writes a string that is optionally quoted + escaped so it can be used as an identifier.
Definition duckdb.cpp:338034
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetPaths()

void duckdb::FileLogStorage::SetPaths ( const string & base_path)
private
260281 {
260282 for (auto &it : tables) {
260283 it.second.path.clear();
260284 }
260285
260286 LocalFileSystem fs;
260287 if (normalize_contexts) {
260288 tables[LoggingTargetTable::LOG_CONTEXTS].path = fs.JoinPath(base_path, "duckdb_log_contexts.csv");
260289 tables[LoggingTargetTable::LOG_ENTRIES].path = fs.JoinPath(base_path, "duckdb_log_entries.csv");
260290 } else {
260291 if (StringUtil::EndsWith(base_path, ".csv")) {
260292 tables[LoggingTargetTable::ALL_LOGS].path = base_path;
260293 } else {
260294 tables[LoggingTargetTable::LOG_ENTRIES].path = fs.JoinPath(base_path, "duckdb_log_entries.csv");
260295 }
260296 }
260297}

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