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

Copy the contents of a query into a table. More...

Inheritance diagram for duckdb::PhysicalCopyToFile:
Collaboration diagram for duckdb::PhysicalCopyToFile:

Public Member Functions

 PhysicalCopyToFile (PhysicalPlan &physical_plan, vector< LogicalType > types, CopyFunction function, unique_ptr< FunctionData > bind_data, idx_t estimated_cardinality)
unique_ptr< GlobalSourceState > GetGlobalSourceState (ClientContext &context) const override
SourceResultType GetDataInternal (ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const override
bool IsSource () const override
SinkResultType Sink (ExecutionContext &context, DataChunk &chunk, OperatorSinkInput &input) const override
SinkCombineResultType Combine (ExecutionContext &context, OperatorSinkCombineInput &input) const override
SinkFinalizeType Finalize (Pipeline &pipeline, Event &event, ClientContext &context, OperatorSinkFinalizeInput &input) const override
SinkFinalizeType FinalizeInternal (ClientContext &context, GlobalSinkState &gstate) const
unique_ptr< LocalSinkState > GetLocalSinkState (ExecutionContext &context) const override
unique_ptr< GlobalSinkState > GetGlobalSinkState (ClientContext &context) const override
bool IsSink () const override
bool SinkOrderDependent () const override
bool ParallelSink () const override
string GetTrimmedPath (ClientContext &context) const
Public Member Functions inherited from duckdb::PhysicalOperator
 PhysicalOperator (PhysicalPlan &physical_plan, PhysicalOperatorType type, vector< LogicalType > types, idx_t estimated_cardinality)
 PhysicalOperator (const PhysicalOperator &other)=delete
 Deleted copy constructors.
PhysicalOperator & operator= (const PhysicalOperator &)=delete
virtual string GetName () const
virtual InsertionOrderPreservingMap< string > ParamsToString () const
virtual string ToString (ExplainFormat format=ExplainFormat::DEFAULT) const
void Print () const
virtual vector< const_reference< PhysicalOperator > > GetChildren () const
const vector< LogicalType > & GetTypes () const
 Return a vector of the types that will be returned by this operator.
virtual bool Equals (const PhysicalOperator &other) const
idx_t EstimatedThreadCount () const
 Functions to help decide how to set up pipeline dependencies.
bool CanSaturateThreads (ClientContext &context) const
virtual void Verify ()
virtual unique_ptr< OperatorState > GetOperatorState (ExecutionContext &context) const
virtual unique_ptr< GlobalOperatorState > GetGlobalOperatorState (ClientContext &context) const
virtual OperatorResultType Execute (ExecutionContext &context, DataChunk &input, DataChunk &chunk, GlobalOperatorState &gstate, OperatorState &state) const
virtual OperatorFinalizeResultType FinalExecute (ExecutionContext &context, DataChunk &chunk, GlobalOperatorState &gstate, OperatorState &state) const
virtual OperatorFinalResultType OperatorFinalize (Pipeline &pipeline, Event &event, ClientContext &context, OperatorFinalizeInput &input) const
virtual bool ParallelOperator () const
virtual bool RequiresFinalExecute () const
virtual bool RequiresOperatorFinalize () const
virtual OrderPreservationType OperatorOrder () const
 The influence the operator has on order (insertion order means no influence).
virtual unique_ptr< LocalSourceState > GetLocalSourceState (ExecutionContext &context, GlobalSourceState &gstate) const
SourceResultType GetData (ExecutionContext &context, DataChunk &chunk, OperatorSourceInput &input) const
virtual OperatorPartitionData GetPartitionData (ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate, LocalSourceState &lstate, const OperatorPartitionInfo &partition_info) const
virtual bool ParallelSource () const
virtual bool SupportsPartitioning (const OperatorPartitionInfo &partition_info) const
virtual OrderPreservationType SourceOrder () const
 The type of order emitted by the operator (as a source).
virtual ProgressData GetProgress (ClientContext &context, GlobalSourceState &gstate) const
 Returns the current progress percentage, or a negative value if progress bars are not supported.
virtual ProgressData GetSinkProgress (ClientContext &context, GlobalSinkState &gstate, const ProgressData source_progress) const
 Returns the current progress percentage, or a negative value if progress bars are not supported.
virtual InsertionOrderPreservingMap< string > ExtraSourceParams (GlobalSourceState &gstate, LocalSourceState &lstate) const
virtual void PrepareFinalize (ClientContext &context, GlobalSinkState &sink_state) const
virtual SinkNextBatchType NextBatch (ExecutionContext &context, OperatorSinkNextBatchInput &input) const
virtual OperatorPartitionInfo RequiredPartitionInfo () const
virtual vector< const_reference< PhysicalOperator > > GetSources () const
bool AllSourcesSupportBatchIndex () const
virtual void BuildPipelines (Pipeline &current, MetaPipeline &meta_pipeline)
template<class TARGET>
TARGET & Cast ()
template<class TARGET>
const TARGET & Cast () const

Static Public Member Functions

static void MoveTmpFile (ClientContext &context, const string &tmp_file_path)
static string GetNonTmpFile (ClientContext &context, const string &tmp_file_path)
static void ReturnStatistics (DataChunk &chunk, idx_t row_idx, CopyToFileInfo &written_file_info)
Static Public Member Functions inherited from duckdb::PhysicalOperator
static void SetEstimatedCardinality (InsertionOrderPreservingMap< string > &result, idx_t estimated_cardinality)
static idx_t GetMaxThreadMemory (ClientContext &context)
 The maximum amount of memory the operator should use per thread.
static OperatorCachingMode SelectOperatorCachingMode (ExecutionContext &context)
 Whether operator caching is allowed in the current execution context.

Public Attributes

CopyFunction function
unique_ptr< FunctionData > bind_data
string file_path
bool use_tmp_file
FilenamePattern filename_pattern
string file_extension
CopyOverwriteMode overwrite_mode
bool parallel
bool per_thread_output
optional_idx file_size_bytes
bool rotate
CopyFunctionReturnType return_type
bool partition_output
bool write_partition_columns
bool write_empty_file
bool hive_file_pattern
vector< idx_t > partition_columns
vector< string > names
vector< LogicalType > expected_types
Public Attributes inherited from duckdb::PhysicalOperator
ArenaLinkedList< reference< PhysicalOperator > > children
 The child operators.
PhysicalOperatorType type
 The physical operator type.
vector< LogicalType > types
 The return types.
idx_t estimated_cardinality
 The estimated cardinality.
unique_ptr< GlobalSinkState > sink_state
 The global sink state.
unique_ptr< GlobalOperatorState > op_state
 The global operator state.
mutex lock
 Lock for (re)setting any of the operator states.

Static Public Attributes

static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::COPY_TO_FILE
Static Public Attributes inherited from duckdb::PhysicalOperator
static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::INVALID

Private Member Functions

unique_ptr< GlobalFunctionData > CreateFileState (ClientContext &context, GlobalSinkState &sink, StorageLockKey &global_lock) const
void WriteRotateInternal (ExecutionContext &context, GlobalSinkState &global_state, const std::function< void(GlobalFunctionData &)> &fun) const

Detailed Description

Copy the contents of a query into a table.

Constructor & Destructor Documentation

◆ PhysicalCopyToFile()

duckdb::PhysicalCopyToFile::PhysicalCopyToFile ( PhysicalPlan & physical_plan,
vector< LogicalType > types,
CopyFunction function,
unique_ptr< FunctionData > bind_data,
idx_t estimated_cardinality )
194432 : PhysicalOperator(physical_plan, PhysicalOperatorType::COPY_TO_FILE, std::move(types), estimated_cardinality),
194433 function(std::move(function_p)), bind_data(std::move(bind_data)), parallel(false) {
194434}
vector< LogicalType > types
The return types.
Definition duckdb.hpp:22152
idx_t estimated_cardinality
The estimated cardinality.
Definition duckdb.hpp:22154

Member Function Documentation

◆ GetGlobalSourceState()

unique_ptr< GlobalSourceState > duckdb::PhysicalCopyToFile::GetGlobalSourceState ( ClientContext & context) const
overridevirtual

Reimplemented from duckdb::PhysicalOperator.

194604 {
194605 return make_uniq<CopyToFileGlobalSourceState>();
194606}

◆ GetDataInternal()

SourceResultType duckdb::PhysicalCopyToFile::GetDataInternal ( ExecutionContext & context,
DataChunk & chunk,
OperatorSourceInput & input ) const
overridevirtual

Reimplemented from duckdb::PhysicalOperator.

194668 {
194669 auto &g = sink_state->Cast<CopyToFunctionGlobalState>();
194670 if (return_type == CopyFunctionReturnType::WRITTEN_FILE_STATISTICS) {
194671 auto &source_state = input.global_state.Cast<CopyToFileGlobalSourceState>();
194672 idx_t next_end = MinValue<idx_t>(source_state.offset + STANDARD_VECTOR_SIZE, g.written_files.size());
194673 idx_t count = next_end - source_state.offset;
194674 for (idx_t i = 0; i < count; i++) {
194675 auto &file_entry = *g.written_files[source_state.offset + i];
194676 if (use_tmp_file) {
194677 file_entry.file_path = GetNonTmpFile(context.client, file_entry.file_path);
194678 }
194679 ReturnStatistics(chunk, i, file_entry);
194680 }
194681 chunk.SetCardinality(count);
194682 source_state.offset += count;
194683 return source_state.offset < g.written_files.size() ? SourceResultType::HAVE_MORE_OUTPUT
194684 : SourceResultType::FINISHED;
194685 }
194686
194687 chunk.SetCardinality(1);
194688 switch (return_type) {
194689 case CopyFunctionReturnType::CHANGED_ROWS:
194690 chunk.SetValue(0, 0, Value::BIGINT(NumericCast<int64_t>(g.rows_copied.load())));
194691 break;
194692 case CopyFunctionReturnType::CHANGED_ROWS_AND_FILE_LIST: {
194693 chunk.SetValue(0, 0, Value::BIGINT(NumericCast<int64_t>(g.rows_copied.load())));
194694 vector<Value> file_name_list;
194695 for (auto &file_info : g.written_files) {
194696 if (use_tmp_file) {
194697 file_name_list.emplace_back(GetNonTmpFile(context.client, file_info->file_path));
194698 } else {
194699 file_name_list.emplace_back(file_info->file_path);
194700 }
194701 }
194702 chunk.SetValue(1, 0, Value::LIST(LogicalType::VARCHAR, std::move(file_name_list)));
194703 break;
194704 }
194705 default:
194706 throw NotImplementedException("Unknown CopyFunctionReturnType");
194707 }
194708
194709 return SourceResultType::FINISHED;
194710}
unique_ptr< GlobalSinkState > sink_state
The global sink state.
Definition duckdb.hpp:22157
static DUCKDB_API Value BIGINT(int64_t value)
Create a bigint Value from a specified value.
Definition duckdb.cpp:132146
static DUCKDB_API Value LIST(const LogicalType &child_type, vector< Value > values)
Create a list value with the given entries.
Definition duckdb.cpp:132555
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ IsSource()

bool duckdb::PhysicalCopyToFile::IsSource ( ) const
inlineoverridevirtual

Reimplemented from duckdb::PhysicalOperator.

191962 {
191963 return true;
191964 }

◆ Sink()

SinkResultType duckdb::PhysicalCopyToFile::Sink ( ExecutionContext & context,
DataChunk & chunk,
OperatorSinkInput & input ) const
overridevirtual

The sink method is called constantly with new input, as long as new input is available. Note that this method CAN be called in parallel, proper locking is needed when accessing dat a inside the GlobalSinkState.

Reimplemented from duckdb::PhysicalOperator.

194476 {
194477 auto &g = input.global_state.Cast<CopyToFunctionGlobalState>();
194478 auto &l = input.local_state.Cast<CopyToFunctionLocalState>();
194479
194480 if (!write_empty_file && !rotate) {
194481 // if we are only writing the file when there are rows to write we need to initialize here
194482 g.Initialize(context.client, *this);
194483 }
194484 l.total_rows_copied += chunk.size();
194485
194486 if (partition_output) {
194487 l.AppendToPartition(context, *this, g, chunk);
194488 return SinkResultType::NEED_MORE_INPUT;
194489 }
194490
194491 if (per_thread_output) {
194492 auto &gstate = l.global_state;
194493 if (!gstate) {
194494 // Lazily create file state here to prevent creating empty files
194495 auto global_lock = g.lock.GetExclusiveLock();
194496 gstate = CreateFileState(context.client, *sink_state, *global_lock);
194497 } else if (rotate && function.rotate_next_file(*gstate, *bind_data, file_size_bytes)) {
194498 function.copy_to_finalize(context.client, *bind_data, *gstate);
194499 auto global_lock = g.lock.GetExclusiveLock();
194500 gstate = CreateFileState(context.client, *sink_state, *global_lock);
194501 }
194502 function.copy_to_sink(context, *bind_data, *gstate, *l.local_state, chunk);
194503 return SinkResultType::NEED_MORE_INPUT;
194504 }
194505
194506 if (!file_size_bytes.IsValid() && !rotate) {
194507 function.copy_to_sink(context, *bind_data, *g.global_state, *l.local_state, chunk);
194508 return SinkResultType::NEED_MORE_INPUT;
194509 }
194510
194511 WriteRotateInternal(context, input.global_state, [&](GlobalFunctionData &gstate) {
194512 function.copy_to_sink(context, *bind_data, gstate, *l.local_state, chunk);
194513 });
194514
194515 return SinkResultType::NEED_MORE_INPUT;
194516}

◆ Combine()

SinkCombineResultType duckdb::PhysicalCopyToFile::Combine ( ExecutionContext & context,
OperatorSinkCombineInput & input ) const
overridevirtual

The combine is called when a single thread has completed execution of its part of the pipeline, it is the final time that a specific LocalSinkState is accessible. This method can be called in parallel while other Sink() or Combine() calls are active on the same GlobalSinkState.

Reimplemented from duckdb::PhysicalOperator.

194518 {
194519 auto &g = input.global_state.Cast<CopyToFunctionGlobalState>();
194520 auto &l = input.local_state.Cast<CopyToFunctionLocalState>();
194521 if (l.total_rows_copied == 0) {
194522 // no rows copied
194523 return SinkCombineResultType::FINISHED;
194524 }
194525 g.rows_copied += l.total_rows_copied;
194526
194527 if (partition_output) {
194528 // flush all remaining partitions
194529 l.FlushPartitions(context, *this, g);
194530 } else if (function.copy_to_combine) {
194531 if (per_thread_output) {
194532 // For PER_THREAD_OUTPUT, we can combine/finalize immediately (if there is a gstate)
194533 if (l.global_state) {
194534 function.copy_to_combine(context, *bind_data, *l.global_state, *l.local_state);
194535 function.copy_to_finalize(context.client, *bind_data, *l.global_state);
194536 }
194537 } else if (rotate) {
194538 WriteRotateInternal(context, input.global_state, [&](GlobalFunctionData &gstate) {
194539 function.copy_to_combine(context, *bind_data, gstate, *l.local_state);
194540 });
194541 } else if (g.global_state) {
194542 function.copy_to_combine(context, *bind_data, *g.global_state, *l.local_state);
194543 }
194544 }
194545
194546 return SinkCombineResultType::FINISHED;
194547}

◆ Finalize()

SinkFinalizeType duckdb::PhysicalCopyToFile::Finalize ( Pipeline & pipeline,
Event & event,
ClientContext & context,
OperatorSinkFinalizeInput & input ) const
overridevirtual

The finalize is called when ALL threads are finished execution. It is called only once per pipeline, and is entirely single threaded. If Finalize returns SinkResultType::Finished, the sink is marked as finished

Reimplemented from duckdb::PhysicalOperator.

194581 {
194582 auto &gstate = input.global_state.Cast<CopyToFunctionGlobalState>();
194583 auto result = FinalizeInternal(context, input.global_state);
194584 gstate.finalized = true;
194585 return result;
194586}

◆ FinalizeInternal()

SinkFinalizeType duckdb::PhysicalCopyToFile::FinalizeInternal ( ClientContext & context,
GlobalSinkState & gstate ) const
194549 {
194550 auto &gstate = global_state.Cast<CopyToFunctionGlobalState>();
194551 if (partition_output) {
194552 // finalize any outstanding partitions
194553 gstate.FinalizePartitions(context, *this);
194554 return SinkFinalizeType::READY;
194555 }
194556 if (per_thread_output) {
194557 // already happened in combine
194558 if (NumericCast<int64_t>(gstate.rows_copied.load()) == 0 && sink_state != nullptr) {
194559 // no rows from source, write schema to file
194560 auto global_lock = gstate.lock.GetExclusiveLock();
194561 gstate.global_state = CreateFileState(context, *sink_state, *global_lock);
194562 function.copy_to_finalize(context, *bind_data, *gstate.global_state);
194563 }
194564 return SinkFinalizeType::READY;
194565 }
194566 if (function.copy_to_finalize && gstate.global_state) {
194567 function.copy_to_finalize(context, *bind_data, *gstate.global_state);
194568
194569 if (use_tmp_file) {
194570 D_ASSERT(!per_thread_output);
194571 D_ASSERT(!partition_output);
194572 D_ASSERT(!file_size_bytes.IsValid());
194573 D_ASSERT(!rotate);
194574 MoveTmpFile(context, file_path);
194575 }
194576 }
194577 return SinkFinalizeType::READY;
194578}

◆ GetLocalSinkState()

unique_ptr< LocalSinkState > duckdb::PhysicalCopyToFile::GetLocalSinkState ( ExecutionContext & context) const
overridevirtual

Reimplemented from duckdb::PhysicalOperator.

194320 {
194321 if (partition_output) {
194322 auto &g = sink_state->Cast<CopyToFunctionGlobalState>();
194323
194324 auto state = make_uniq<CopyToFunctionLocalState>(context.client, nullptr);
194325 state->InitializeAppendState(context.client, *this, g);
194326 return std::move(state);
194327 }
194328 auto res =
194329 make_uniq<CopyToFunctionLocalState>(context.client, function.copy_to_initialize_local(context, *bind_data));
194330 return std::move(res);
194331}

◆ GetGlobalSinkState()

unique_ptr< GlobalSinkState > duckdb::PhysicalCopyToFile::GetGlobalSinkState ( ClientContext & context) const
overridevirtual

Reimplemented from duckdb::PhysicalOperator.

194363 {
194364 if (partition_output || per_thread_output || rotate) {
194365 auto &fs = FileSystem::GetFileSystem(context);
194366 if (!fs.IsRemoteFile(file_path)) {
194367 if (fs.FileExists(file_path)) {
194368 // the target file exists AND is a file (not a directory)
194369 // for local files we can remove the file if OVERWRITE_OR_IGNORE is enabled
194370 if (overwrite_mode == CopyOverwriteMode::COPY_OVERWRITE) {
194371 fs.RemoveFile(file_path);
194372 } else {
194373 throw IOException("Cannot write to \"%s\" - it exists and is a file, not a directory! Enable "
194374 "OVERWRITE option to overwrite the file",
194375 file_path);
194376 }
194377 }
194378 }
194379 // what if the target exists and is a directory
194380 if (!fs.DirectoryExists(file_path)) {
194381 fs.CreateDirectory(file_path);
194382 } else {
194383 CheckDirectory(fs, file_path, overwrite_mode);
194384 }
194385
194386 auto state = make_uniq<CopyToFunctionGlobalState>(context);
194387 if (!per_thread_output && rotate && write_empty_file) {
194388 auto global_lock = state->lock.GetExclusiveLock();
194389 state->global_state = CreateFileState(context, *state, *global_lock);
194390 }
194391
194392 if (partition_output) {
194393 state->partition_state = make_shared_ptr<GlobalHivePartitionState>();
194394 }
194395
194396 return std::move(state);
194397 }
194398
194399 auto state = make_uniq<CopyToFunctionGlobalState>(context);
194400 if (write_empty_file) {
194401 // if we are writing the file also if it is empty - initialize now
194402 state->Initialize(context, *this);
194403 }
194404 return std::move(state);
194405}

◆ IsSink()

bool duckdb::PhysicalCopyToFile::IsSink ( ) const
inlineoverridevirtual

Reimplemented from duckdb::PhysicalOperator.

191976 {
191977 return true;
191978 }

◆ SinkOrderDependent()

bool duckdb::PhysicalCopyToFile::SinkOrderDependent ( ) const
inlineoverridevirtual

Whether or not the sink operator depends on the order of the input chunks If this is set to true, we cannot do things like caching intermediate vectors

Reimplemented from duckdb::PhysicalOperator.

191980 {
191981 return true;
191982 }

◆ ParallelSink()

bool duckdb::PhysicalCopyToFile::ParallelSink ( ) const
inlineoverridevirtual

Reimplemented from duckdb::PhysicalOperator.

191984 {
191985 return per_thread_output || partition_output || parallel;
191986 }

◆ MoveTmpFile()

void duckdb::PhysicalCopyToFile::MoveTmpFile ( ClientContext & context,
const string & tmp_file_path )
static
194410 {
194411 auto &fs = FileSystem::GetFileSystem(context);
194412 auto file_path = GetNonTmpFile(context, tmp_file_path);
194413 fs.MoveFile(tmp_file_path, file_path);
194414}

◆ GetNonTmpFile()

string duckdb::PhysicalCopyToFile::GetNonTmpFile ( ClientContext & context,
const string & tmp_file_path )
static
194416 {
194417 auto &fs = FileSystem::GetFileSystem(context);
194418
194419 auto path = StringUtil::GetFilePath(tmp_file_path);
194420 auto base = StringUtil::GetFileName(tmp_file_path);
194421
194422 auto prefix = base.find("tmp_");
194423 if (prefix == 0) {
194424 base = base.substr(4);
194425 }
194426
194427 return fs.JoinPath(path, base);
194428}

◆ GetTrimmedPath()

string duckdb::PhysicalCopyToFile::GetTrimmedPath ( ClientContext & context) const
194193 {
194194 auto &fs = FileSystem::GetFileSystem(context);
194195 string trimmed_path = file_path;
194196 StringUtil::RTrim(trimmed_path, fs.PathSeparator(trimmed_path));
194197 return trimmed_path;
194198}
static DUCKDB_API void RTrim(string &str)
Remove the whitespace char in the right end of the string.
Definition duckdb.cpp:109360

◆ ReturnStatistics()

void duckdb::PhysicalCopyToFile::ReturnStatistics ( DataChunk & chunk,
idx_t row_idx,
CopyToFileInfo & written_file_info )
static
194645 {
194646 auto &file_stats = *info.file_stats;
194647
194648 // filename VARCHAR
194649 chunk.SetValue(0, row_idx, info.file_path);
194650 // count BIGINT
194651 chunk.SetValue(1, row_idx, Value::UBIGINT(file_stats.row_count));
194652 // file size bytes BIGINT
194653 chunk.SetValue(2, row_idx, Value::UBIGINT(file_stats.file_size_bytes));
194654 // footer size bytes BIGINT
194655 chunk.SetValue(3, row_idx, file_stats.footer_size_bytes);
194656 // column statistics map(varchar, map(varchar, varchar))
194657 auto column_stats = CreateColumnStatistics(file_stats.column_statistics);
194658 auto map_val_type = LogicalType::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR);
194659 chunk.SetValue(
194660 4, row_idx,
194661 Value::MAP(LogicalType::VARCHAR, map_val_type, std::move(column_stats.keys), std::move(column_stats.values)));
194662
194663 // partition_keys map(varchar, varchar)
194664 chunk.SetValue(5, row_idx, info.partition_keys);
194665}
static DUCKDB_API Value MAP(const LogicalType &child_type, vector< Value > values)
Create a map value with the given entries.
Definition duckdb.cpp:132466
static DUCKDB_API Value UBIGINT(uint64_t value)
Create an unsigned bigint Value from a specified value.
Definition duckdb.cpp:132202
static ColumnStatsMapData CreateColumnStatistics(const case_insensitive_map_t< case_insensitive_map_t< Value > > &column_statistics)
Definition duckdb.cpp:194618

◆ CreateFileState()

unique_ptr< GlobalFunctionData > duckdb::PhysicalCopyToFile::CreateFileState ( ClientContext & context,
GlobalSinkState & sink,
StorageLockKey & global_lock ) const
private
194300 {
194301 auto &g = sink.Cast<CopyToFunctionGlobalState>();
194302 idx_t this_file_offset = g.last_file_offset++;
194303 auto &fs = FileSystem::GetFileSystem(context);
194304 string output_path(filename_pattern.CreateFilename(fs, file_path, file_extension, this_file_offset));
194305 g.created_files.push_back(output_path);
194306 optional_ptr<CopyToFileInfo> written_file_info;
194307 if (return_type != CopyFunctionReturnType::CHANGED_ROWS) {
194308 written_file_info = g.AddFile(global_lock, output_path, return_type);
194309 }
194310 auto result = function.copy_to_initialize_global(context, *bind_data, output_path);
194311 if (written_file_info) {
194312 function.copy_to_get_written_statistics(context, *bind_data, *result, *written_file_info->file_stats);
194313 }
194314 if (function.initialize_operator) {
194315 function.initialize_operator(*result, *this);
194316 }
194317 return result;
194318}

◆ WriteRotateInternal()

void duckdb::PhysicalCopyToFile::WriteRotateInternal ( ExecutionContext & context,
GlobalSinkState & global_state,
const std::function< void(GlobalFunctionData &)> & fun ) const
private
194437 {
194438 auto &g = global_state.Cast<CopyToFunctionGlobalState>();
194439
194440 // Loop until we can write (synchronize using locks when using parallel writes to the same files and "rotate")
194441 while (true) {
194442 // Grab global lock and dereference the current file state (and corresponding lock)
194443 auto global_guard = g.lock.GetExclusiveLock();
194444 if (!g.global_state) {
194445 g.global_state = CreateFileState(context.client, *sink_state, *global_guard);
194446 }
194447 auto &file_state = *g.global_state;
194448 auto &file_lock = *g.file_write_lock_if_rotating;
194449 if (rotate && function.rotate_next_file(file_state, *bind_data, file_size_bytes)) {
194450 // Global state must be rotated. Move to local scope, create an new one, and immediately release global lock
194451 auto owned_gstate = std::move(g.global_state);
194452 g.global_state = CreateFileState(context.client, *sink_state, *global_guard);
194453 auto owned_lock = std::move(g.file_write_lock_if_rotating);
194454 g.file_write_lock_if_rotating = make_uniq<StorageLock>();
194455 global_guard.reset();
194456
194457 // This thread now waits for the exclusive lock on this file while other threads complete their writes
194458 // Note that new writes can still start, as there is already a new global state
194459 auto file_guard = owned_lock->GetExclusiveLock();
194460 function.copy_to_finalize(context.client, *bind_data, *owned_gstate);
194461 } else {
194462 // Get shared file write lock while holding global lock,
194463 // so file can't be rotated before we get the write lock
194464 auto file_guard = file_lock.GetSharedLock();
194465
194466 // Because we got the shared lock on the file, we're sure that it will keep existing until we release it
194467 global_guard.reset();
194468
194469 // Sink/Combine!
194470 fun(file_state);
194471 break;
194472 }
194473 }
194474}

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