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

The ClientContext holds information relevant to the current client session during execution. More...

#include <duckdb.hpp>

Inheritance diagram for duckdb::ClientContext:
Collaboration diagram for duckdb::ClientContext:

Public Member Functions

DUCKDB_API ClientContext (shared_ptr< DatabaseInstance > db)
MetaTransaction & ActiveTransaction ()
DUCKDB_API void Interrupt ()
 Interrupt execution of a query.
DUCKDB_API bool IsInterrupted () const
DUCKDB_API void ClearInterrupt ()
DUCKDB_API void CancelTransaction ()
DUCKDB_API void EnableProfiling ()
 Enable query profiling.
DUCKDB_API void DisableProfiling ()
 Disable query profiling.
DUCKDB_API unique_ptr< QueryResult > Query (const string &query, QueryParameters query_parameters)
 Issue a query, returning a QueryResult. The QueryResult can be either a StreamQueryResult or a MaterializedQueryResult. The StreamQueryResult will only be returned in the case of a successful SELECT statement.
DUCKDB_API unique_ptr< QueryResult > Query (unique_ptr< SQLStatement > statement, QueryParameters query_parameters)
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery (const string &query, QueryParameters query_parameters)
 Issues a query to the database and returns a Pending Query Result. Note that "query" may only contain a single statement.
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery (unique_ptr< SQLStatement > statement, QueryParameters query_parameters)
 Issues a query to the database and returns a Pending Query Result.
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery (unique_ptr< SQLStatement > statement, case_insensitive_map_t< BoundParameterData > &values, QueryParameters query_parameters)
 Create a pending query with a list of parameters.
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery (const string &query, case_insensitive_map_t< BoundParameterData > &values, QueryParameters query_parameters)
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery (const string &query, PendingQueryParameters parameters)
DUCKDB_API void Destroy ()
 Destroy the client context.
DUCKDB_API unique_ptr< TableDescription > TableInfo (const string &database_name, const string &schema_name, const string &table_name)
 Get the table info of a specific table, or nullptr if it cannot be found.
DUCKDB_API unique_ptr< TableDescription > TableInfo (const string &schema_name, const string &table_name)
 Get the table info of a specific table, or nullptr if it cannot be found. Uses INVALID_CATALOG.
DUCKDB_API void Append (unique_ptr< SQLStatement > stmt)
 Executes a query with the given collection "attached" to the query using a CTE.
DUCKDB_API void Append (TableDescription &description, ColumnDataCollection &collection)
 Appends a ColumnDataCollection to the described table.
DUCKDB_API void TryBindRelation (Relation &relation, vector< ColumnDefinition > &result_columns)
 Try to bind a relation in the current client context; either throws an exception or fills the result_columns list with the set of returned columns.
DUCKDB_API void InternalTryBindRelation (Relation &relation, vector< ColumnDefinition > &result_columns)
 Internal function for try bind relation. It does not require a client-context lock.
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery (const shared_ptr< Relation > &relation, QueryParameters query_parameters)
 Execute a relation.
DUCKDB_API unique_ptr< QueryResult > Execute (const shared_ptr< Relation > &relation)
DUCKDB_API unique_ptr< PreparedStatement > Prepare (const string &query)
 Prepare a query.
DUCKDB_API unique_ptr< PreparedStatement > Prepare (unique_ptr< SQLStatement > statement)
 Directly prepare a SQL statement.
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery (const string &query, shared_ptr< PreparedStatementData > &prepared, const PendingQueryParameters &parameters)
 Create a pending query result from a prepared statement with the given name and set of parameters It is possible that the prepared statement will be re-bound. This will generally happen if the catalog is modified in between the prepared statement being bound and the prepared statement being run.
DUCKDB_API unique_ptr< QueryResult > Execute (const string &query, shared_ptr< PreparedStatementData > &prepared, case_insensitive_map_t< BoundParameterData > &values, QueryParameters query_parameters=QueryResultOutputType::ALLOW_STREAMING)
 Execute a prepared statement with the given name and set of parameters It is possible that the prepared statement will be re-bound. This will generally happen if the catalog is modified in between the prepared statement being bound and the prepared statement being run.
DUCKDB_API unique_ptr< QueryResult > Execute (const string &query, shared_ptr< PreparedStatementData > &prepared, const PendingQueryParameters &parameters)
DUCKDB_API QueryProgress GetQueryProgress ()
 Gets current percentage of the query's progress, returns 0 in case the progress bar is disabled.
DUCKDB_API void RegisterFunction (CreateFunctionInfo &info)
 Register function in the temporary schema.
DUCKDB_API vector< unique_ptr< SQLStatement > > ParseStatements (const string &query)
 Parse statements from a query.
DUCKDB_API unique_ptr< LogicalOperator > ExtractPlan (const string &query)
 Extract the logical plan of a query.
DUCKDB_API void PreprocessStatements (vector< unique_ptr< SQLStatement > > &statements)
DUCKDB_API void RunFunctionInTransaction (const std::function< void(void)> &fun, bool requires_valid_transaction=true)
 Runs a function with a valid transaction context, potentially starting a transaction if the context is in auto commit mode.
DUCKDB_API void RunFunctionInTransactionInternal (ClientContextLock &lock, const std::function< void(void)> &fun, bool requires_valid_transaction=true)
 Same as RunFunctionInTransaction, but does not obtain a lock on the client context or check for validation.
DUCKDB_API SettingLookupResult TryGetCurrentSetting (const string &key, Value &result) const
 Equivalent to CURRENT_SETTING(key) SQL function.
DUCKDB_API SettingLookupResult TryGetCurrentUserSetting (idx_t setting_index, Value &result) const
 Returns the value of the current setting set by the user - if the user has set it.
DUCKDB_API ParserOptions GetParserOptions () const
 Returns the parser options for this client context.
DUCKDB_API bool IsActiveResult (ClientContextLock &lock, BaseQueryResult &result)
 Whether or not the given result object (streaming query result or pending query result) is active.
Executor & GetExecutor ()
 Returns the current executor.
Logger & GetLogger () const
 Return the current logger.
const string & GetCurrentQuery ()
 Returns the current query string (if any).
connection_t GetConnectionId () const
DUCKDB_API unordered_set< string > GetTableNames (const string &query, const bool qualified=false)
 Fetch the set of tables names of the query. Returns the fully qualified, escaped table names, if qualified is set to true, else returns the not qualified, not escaped table names.
DUCKDB_API ClientProperties GetClientProperties ()
DUCKDB_API bool ExecutionIsFinished ()
 Returns true if execution of the current query is finished.
DUCKDB_API void ProcessError (ErrorData &error, const string &query) const
 Process an error for display to the user.
DUCKDB_API LogicalType ParseLogicalType (const string &type)
Public Member Functions inherited from duckdb::enable_shared_from_this< ClientContext >
shared_ptr< ClientContext > shared_from_this ()

Public Attributes

shared_ptr< DatabaseInstance > db
 The database that this client is connected to.
atomic< bool > interrupted
 Whether or not the query is interrupted.
unique_ptr< RegisteredStateManager > registered_state
 Set of optional states (e.g. Caches) that can be held by the ClientContext.
shared_ptr< Logger > logger
 The logger to be used by this ClientContext.
ClientConfig config
 The client configuration.
unique_ptr< ClientData > client_data
 The set of client-specific data.
TransactionContext transaction
 Data for the currently running transaction.

Private Member Functions

vector< unique_ptr< SQLStatement > > ParseStatements (ClientContextLock &lock, const string &query)
 Parse statements and resolve pragmas from a query.
unique_ptr< PendingQueryResult > PendingQueryInternal (ClientContextLock &lock, unique_ptr< SQLStatement > statement, const PendingQueryParameters &parameters, bool verify=true)
 Issues a query to the database and returns a Pending Query Result.
unique_ptr< QueryResult > ExecutePendingQueryInternal (ClientContextLock &lock, PendingQueryResult &query)
vector< unique_ptr< SQLStatement > > ParseStatementsInternal (ClientContextLock &lock, const string &query)
 Parse statements from a query.
ErrorData VerifyQuery (ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, PendingQueryParameters parameters)
 Perform aggressive query verification of a SELECT statement. Only called when query_verification_enabled is true.
void InitialCleanup (ClientContextLock &lock)
void CleanupInternal (ClientContextLock &lock, BaseQueryResult *result=nullptr, bool invalidate_transaction=false)
 Internal clean up, does not lock. Caller must hold the context_lock.
unique_ptr< PendingQueryResult > PendingStatementOrPreparedStatement (ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, shared_ptr< PreparedStatementData > &prepared, const PendingQueryParameters &parameters)
unique_ptr< PendingQueryResult > PendingPreparedStatement (ClientContextLock &lock, const string &query, shared_ptr< PreparedStatementData > statement_p, const PendingQueryParameters &parameters)
unique_ptr< PendingQueryResult > PendingPreparedStatementInternal (ClientContextLock &lock, shared_ptr< PreparedStatementData > statement_data_p, const PendingQueryParameters &parameters)
void CheckIfPreparedStatementIsExecutable (PreparedStatementData &statement)
shared_ptr< PreparedStatementData > CreatePreparedStatement (ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, PendingQueryParameters parameters, PreparedStatementMode mode=PreparedStatementMode::PREPARE_ONLY)
 Internally prepare a SQL statement. Caller must hold the context_lock.
unique_ptr< PendingQueryResult > PendingStatementInternal (ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, const PendingQueryParameters &parameters)
unique_ptr< QueryResult > RunStatementInternal (ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, const PendingQueryParameters &parameters, bool verify=true)
unique_ptr< PreparedStatement > PrepareInternal (ClientContextLock &lock, unique_ptr< SQLStatement > statement)
void LogQueryInternal (ClientContextLock &lock, const string &query)
unique_ptr< QueryResult > FetchResultInternal (ClientContextLock &lock, PendingQueryResult &pending)
unique_ptr< ClientContextLock > LockContext ()
void BeginQueryInternal (ClientContextLock &lock, const string &query)
ErrorData EndQueryInternal (ClientContextLock &lock, bool success, bool invalidate_transaction, optional_ptr< ErrorData > previous_error)
void WaitForTask (ClientContextLock &lock, BaseQueryResult &result)
 Wait until a task is available to execute.
PendingExecutionResult ExecuteTaskInternal (ClientContextLock &lock, BaseQueryResult &result, bool dry_run=false)
unique_ptr< PendingQueryResult > PendingStatementOrPreparedStatementInternal (ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, shared_ptr< PreparedStatementData > &prepared, const PendingQueryParameters &parameters)
unique_ptr< PendingQueryResult > PendingQueryPreparedInternal (ClientContextLock &lock, const string &query, shared_ptr< PreparedStatementData > &prepared, const PendingQueryParameters &parameters)
unique_ptr< PendingQueryResult > PendingQueryInternal (ClientContextLock &, const shared_ptr< Relation > &relation, QueryParameters query_parameters)
void RebindPreparedStatement (ClientContextLock &lock, const string &query, shared_ptr< PreparedStatementData > &prepared, const PendingQueryParameters &parameters)
template<class T>
unique_ptr< T > ErrorResult (ErrorData error, const string &query=string())
shared_ptr< PreparedStatementData > CreatePreparedStatementInternal (ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, PendingQueryParameters parameters)
bool ErrorInvalidatesTransaction (ExceptionType type)

Private Attributes

mutex context_lock
 Lock on using the ClientContext in parallel.
unique_ptr< ActiveQueryContext > active_query
 The currently active query context.
QueryProgress query_progress
 The current query progress.
connection_t connection_id
 The connection corresponding to this client context.

Friends

class PendingQueryResult
class BufferedData
class SimpleBufferedData
class BatchedBufferedData
class StreamQueryResult
class ConnectionManager

Additional Inherited Members

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

Detailed Description

The ClientContext holds information relevant to the current client session during execution.

Constructor & Destructor Documentation

◆ ClientContext()

duckdb::ClientContext::ClientContext ( shared_ptr< DatabaseInstance > db)
explicit
272631 : db(std::move(database)), interrupted(false), transaction(*this), connection_id(DConstants::INVALID_INDEX) {
272632 registered_state = make_uniq<RegisteredStateManager>();
272633#ifdef DEBUG
272634 registered_state->GetOrCreate<DebugClientContextState>("debug_client_context_state");
272635#endif
272636 LoggingContext context(LogContextScope::CONNECTION);
272637 logger = db->GetLogManager().CreateLogger(context, true);
272638 client_data = make_uniq<ClientData>(*this);
272639
272640#ifdef __APPLE__
272641 if (OsxRosettaIsActive()) {
272642 DUCKDB_LOG_WARNING(*this, "OSX binary translation ('Rosetta') detected. Running DuckDB through Rosetta will "
272643 "cause a significant performance degradation. DuckDB is available natively on Apple "
272644 "silicon, please download an appropriate binary here: https://duckdb.org/install/");
272645 }
272646#endif
272647}
unique_ptr< ClientData > client_data
The set of client-specific data.
Definition duckdb.hpp:41578
atomic< bool > interrupted
Whether or not the query is interrupted.
Definition duckdb.hpp:41570
shared_ptr< DatabaseInstance > db
The database that this client is connected to.
Definition duckdb.hpp:41568
connection_t connection_id
The connection corresponding to this client context.
Definition duckdb.hpp:41813
TransactionContext transaction
Data for the currently running transaction.
Definition duckdb.hpp:41580
unique_ptr< RegisteredStateManager > registered_state
Set of optional states (e.g. Caches) that can be held by the ClientContext.
Definition duckdb.hpp:41572
shared_ptr< Logger > logger
The logger to be used by this ClientContext.
Definition duckdb.hpp:41574
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117

◆ ~ClientContext()

duckdb::ClientContext::~ClientContext ( )
272649 {
272650 if (Exception::UncaughtException()) {
272651 return;
272652 }
272653 // destroy the client context and rollback if there is an active transaction
272654 // but only if we are not destroying this client context as part of an exception stack unwind
272655 Destroy();
272656}
DUCKDB_API void Destroy()
Destroy the client context.
Definition duckdb.cpp:272662

Member Function Documentation

◆ ActiveTransaction()

MetaTransaction & duckdb::ClientContext::ActiveTransaction ( )
inline
41583 {
41584 return transaction.ActiveTransaction();
41585 }

◆ Interrupt()

void duckdb::ClientContext::Interrupt ( )

Interrupt execution of a query.

273650 {
273651 interrupted = true;
273652}

◆ IsInterrupted()

bool duckdb::ClientContext::IsInterrupted ( ) const
273654 {
273655 return interrupted;
273656}

◆ ClearInterrupt()

void duckdb::ClientContext::ClearInterrupt ( )
273658 {
273659 interrupted = false;
273660}

◆ CancelTransaction()

void duckdb::ClientContext::CancelTransaction ( )
273662 {
273663 auto lock = LockContext();
273664 InitialCleanup(*lock);
273665}
void InitialCleanup(ClientContextLock &lock)
Definition duckdb.cpp:273153

◆ EnableProfiling()

void duckdb::ClientContext::EnableProfiling ( )

Enable query profiling.

273667 {
273668 auto lock = LockContext();
273669 auto &client_config = ClientConfig::GetConfig(*this);
273670 client_config.enable_profiler = true;
273671 client_config.emit_profiler_output = true;
273672}

◆ DisableProfiling()

void duckdb::ClientContext::DisableProfiling ( )

Disable query profiling.

273674 {
273675 auto lock = LockContext();
273676 auto &client_config = ClientConfig::GetConfig(*this);
273677 client_config.enable_profiler = false;
273678}

◆ Query() [1/2]

unique_ptr< QueryResult > duckdb::ClientContext::Query ( const string & query,
QueryParameters query_parameters )

Issue a query, returning a QueryResult. The QueryResult can be either a StreamQueryResult or a MaterializedQueryResult. The StreamQueryResult will only be returned in the case of a successful SELECT statement.

273503 {
273504 auto lock = LockContext();
273505 vector<unique_ptr<SQLStatement>> statements;
273506 try {
273507 statements = ParseStatements(*lock, query);
273508 } catch (const std::exception &ex) {
273509 return ErrorResult<MaterializedQueryResult>(ErrorData(ex), query);
273510 }
273511 if (statements.empty()) {
273512 // no statements, return empty successful result
273513 StatementProperties properties;
273514 vector<string> names;
273515 auto collection = make_uniq<ColumnDataCollection>(Allocator::DefaultAllocator());
273516 return make_uniq<MaterializedQueryResult>(StatementType::INVALID_STATEMENT, properties, std::move(names),
273517 std::move(collection), GetClientProperties());
273518 }
273519
273520 unique_ptr<QueryResult> result;
273521 optional_ptr<QueryResult> last_result;
273522 bool last_had_result = false;
273523 for (idx_t i = 0; i < statements.size(); i++) {
273524 auto &statement = statements[i];
273525 bool is_last_statement = i + 1 == statements.size();
273526 PendingQueryParameters parameters;
273527 parameters.query_parameters = query_parameters;
273528 if (!is_last_statement) {
273529 parameters.query_parameters.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
273530 }
273531 auto pending_query = PendingQueryInternal(*lock, std::move(statement), parameters);
273532 auto has_result = pending_query->properties.return_type == StatementReturnType::QUERY_RESULT;
273533 unique_ptr<QueryResult> current_result;
273534 if (pending_query->HasError()) {
273535 current_result = ErrorResult<MaterializedQueryResult>(pending_query->GetErrorObject());
273536 } else {
273537 current_result = ExecutePendingQueryInternal(*lock, *pending_query);
273538 }
273539 if (current_result->HasError()) {
273540 if (transaction.HasActiveTransaction() && transaction.GetAutoRollback()) {
273541 transaction.Rollback(current_result->GetErrorObject());
273542 }
273543 // Reset the interrupted flag, this was set by the task that found the error
273544 // Next statements should not be bothered by that interruption
273545 interrupted = false;
273546 return current_result;
273547 }
273548 // now append the result to the list of results
273549 if (!last_result || !last_had_result) {
273550 // first result of the query
273551 result = std::move(current_result);
273552 last_result = result.get();
273553 last_had_result = has_result;
273554 } else {
273555 // later results; attach to the result chain
273556 // but only if there is a result
273557 if (!has_result) {
273558 continue;
273559 }
273560 last_result->next = std::move(current_result);
273561 last_result = last_result->next.get();
273562 }
273563 D_ASSERT(last_result);
273564 }
273565 return result;
273566}
DUCKDB_API vector< unique_ptr< SQLStatement > > ParseStatements(const string &query)
Parse statements from a query.
Definition duckdb.cpp:273159
unique_ptr< PendingQueryResult > PendingQueryInternal(ClientContextLock &lock, unique_ptr< SQLStatement > statement, const PendingQueryParameters &parameters, bool verify=true)
Issues a query to the database and returns a Pending Query Result.
Definition duckdb.cpp:273633
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:

◆ Query() [2/2]

unique_ptr< QueryResult > duckdb::ClientContext::Query ( unique_ptr< SQLStatement > statement,
QueryParameters query_parameters )
273495 {
273496 auto pending_query = PendingQuery(std::move(statement), parameters);
273497 if (pending_query->HasError()) {
273498 return ErrorResult<MaterializedQueryResult>(pending_query->GetErrorObject());
273499 }
273500 return pending_query->Execute();
273501}
DUCKDB_API unique_ptr< PendingQueryResult > PendingQuery(const string &query, QueryParameters query_parameters)
Issues a query to the database and returns a Pending Query Result. Note that "query" may only contain...
Definition duckdb.cpp:273574

◆ PendingQuery() [1/7]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQuery ( const string & query,
QueryParameters query_parameters )

Issues a query to the database and returns a Pending Query Result. Note that "query" may only contain a single statement.

273574 {
273575 case_insensitive_map_t<BoundParameterData> empty_param_list;
273576 return PendingQuery(query, empty_param_list, parameters);
273577}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PendingQuery() [2/7]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQuery ( unique_ptr< SQLStatement > statement,
QueryParameters query_parameters )

Issues a query to the database and returns a Pending Query Result.

273580 {
273581 case_insensitive_map_t<BoundParameterData> empty_param_list;
273582 return PendingQuery(std::move(statement), empty_param_list, parameters);
273583}
Here is the call graph for this function:

◆ PendingQuery() [3/7]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQuery ( unique_ptr< SQLStatement > statement,
case_insensitive_map_t< BoundParameterData > & values,
QueryParameters query_parameters )

Create a pending query with a list of parameters.

273617 {
273618 auto lock = LockContext();
273619 auto query = statement->query;
273620 try {
273621 InitialCleanup(*lock);
273622
273623 PendingQueryParameters params;
273624 params.query_parameters = parameters;
273625 params.parameters = values;
273626
273627 return PendingQueryInternal(*lock, std::move(statement), params, true);
273628 } catch (std::exception &ex) {
273629 return make_uniq<PendingQueryResult>(ErrorData(ex));
273630 }
273631}
PyParams params(const std::string &tag, const std::string &model, const std::string &weights, const std::string &device)
Here is the call graph for this function:

◆ PendingQuery() [4/7]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQuery ( const string & query,
case_insensitive_map_t< BoundParameterData > & values,
QueryParameters query_parameters )
273587 {
273588 PendingQueryParameters params;
273589 params.parameters = values;
273590 params.query_parameters = parameters;
273591 return PendingQuery(query, params);
273592}

◆ PendingQuery() [5/7]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQuery ( const string & query,
PendingQueryParameters parameters )
273594 {
273595 auto lock = LockContext();
273596 try {
273597 InitialCleanup(*lock);
273598
273599 auto statements = ParseStatementsInternal(*lock, query);
273600 if (statements.empty()) {
273601 throw InvalidInputException("No statement to prepare!");
273602 }
273603 if (statements.size() > 1) {
273604 throw InvalidInputException("Cannot prepare multiple statements at once!");
273605 }
273606
273607 return PendingQueryInternal(*lock, std::move(statements[0]), parameters, true);
273608 } catch (std::exception &ex) {
273609 ErrorData error(ex);
273610 ProcessError(error, query);
273611 return make_uniq<PendingQueryResult>(std::move(error));
273612 }
273613}
vector< unique_ptr< SQLStatement > > ParseStatementsInternal(ClientContextLock &lock, const string &query)
Parse statements from a query.
Definition duckdb.cpp:273164
DUCKDB_API void ProcessError(ErrorData &error, const string &query) const
Process an error for display to the user.
Definition duckdb.cpp:272673

◆ Destroy()

void duckdb::ClientContext::Destroy ( )

Destroy the client context.

272662 {
272663 auto lock = LockContext();
272664 if (transaction.HasActiveTransaction()) {
272665 transaction.ResetActiveQuery();
272666 if (!transaction.IsAutoCommit()) {
272667 transaction.Rollback(nullptr);
272668 }
272669 }
272670 CleanupInternal(*lock);
272671}
void CleanupInternal(ClientContextLock &lock, BaseQueryResult *result=nullptr, bool invalidate_transaction=false)
Internal clean up, does not lock. Caller must hold the context_lock.
Definition duckdb.cpp:272775
Here is the call graph for this function:

◆ TableInfo() [1/2]

unique_ptr< TableDescription > duckdb::ClientContext::TableInfo ( const string & database_name,
const string & schema_name,
const string & table_name )

Get the table info of a specific table, or nullptr if it cannot be found.

273741 {
273742 unique_ptr<TableDescription> result;
273744 // Obtain the table from the catalog.
273745 auto table = Catalog::GetEntry<TableCatalogEntry>(*this, database_name, schema_name, table_name,
273746 OnEntryNotFound::RETURN_NULL);
273747 if (!table) {
273748 return;
273749 }
273750 // Create the table description.
273751 result = make_uniq<TableDescription>(database_name, schema_name, table_name);
273752 auto &catalog = Catalog::GetCatalog(*this, database_name);
273753 result->readonly = catalog.GetAttached().IsReadOnly();
273754 for (auto &column : table->GetColumns().Logical()) {
273755 result->columns.emplace_back(column.Copy());
273756 }
273757 });
273758 return result;
273759}
static DUCKDB_API Catalog & GetCatalog(ClientContext &context, const string &catalog_name)
Get the specified Catalog from the ClientContext.
Definition duckdb.cpp:7211
DUCKDB_API optional_ptr< CatalogEntry > GetEntry(ClientContext &context, const string &schema, const EntryLookupInfo &lookup_info, OnEntryNotFound if_not_found)
Gets the "schema.name" entry of the specified type, if entry does not exist behavior depends on OnEnt...
Definition duckdb.cpp:8156
DUCKDB_API void RunFunctionInTransaction(const std::function< void(void)> &fun, bool requires_valid_transaction=true)
Runs a function with a valid transaction context, potentially starting a transaction if the context i...
Definition duckdb.cpp:273735
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TableInfo() [2/2]

unique_ptr< TableDescription > duckdb::ClientContext::TableInfo ( const string & schema_name,
const string & table_name )

Get the table info of a specific table, or nullptr if it cannot be found. Uses INVALID_CATALOG.

273761 {
273762 return TableInfo(INVALID_CATALOG, schema_name, table_name);
273763}
DUCKDB_API unique_ptr< TableDescription > TableInfo(const string &database_name, const string &schema_name, const string &table_name)
Get the table info of a specific table, or nullptr if it cannot be found.
Definition duckdb.cpp:273740
Here is the call graph for this function:

◆ Append() [1/2]

void duckdb::ClientContext::Append ( unique_ptr< SQLStatement > stmt)

Executes a query with the given collection "attached" to the query using a CTE.

273765 {
273766 auto result = Query(std::move(stmt), false);
273767 if (result->HasError()) {
273768 result->GetErrorObject().Throw("Failed to append: ");
273769 }
273770}
DUCKDB_API unique_ptr< QueryResult > Query(const string &query, QueryParameters query_parameters)
Issue a query, returning a QueryResult. The QueryResult can be either a StreamQueryResult or a Materi...
Definition duckdb.cpp:273503
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Append() [2/2]

void duckdb::ClientContext::Append ( TableDescription & description,
ColumnDataCollection & collection )

Appends a ColumnDataCollection to the described table.

273772 {
273773 string table_name = "__duckdb_internal_appended_data";
273774 vector<string> expected_names;
273775 auto query = Appender::ConstructQuery(description, table_name, expected_names);
273776 auto table_ref = BaseAppender::GetColumnDataTableRef(collection, table_name, expected_names);
273777 auto stmt = BaseAppender::ParseStatement(std::move(table_ref), query, table_name);
273778 Append(std::move(stmt));
273779}
static string ConstructQuery(TableDescription &description_p, const string &table_name, const vector< string > &expected_names)
Construct a query that appends data from, typically, a column data collection.
Definition duckdb.cpp:261858
static unique_ptr< TableRef > GetColumnDataTableRef(ColumnDataCollection &collection, const string &table_name, const vector< string > &expected_names)
Returns a table reference to the appended data.
Definition duckdb.cpp:261713
static unique_ptr< SQLStatement > ParseStatement(unique_ptr< TableRef > table_ref, const string &query, const string &table_name)
Parses the statement to append data.
Definition duckdb.cpp:261738
DUCKDB_API void Append(unique_ptr< SQLStatement > stmt)
Executes a query with the given collection "attached" to the query using a CTE.
Definition duckdb.cpp:273765
Here is the call graph for this function:

◆ TryBindRelation()

void duckdb::ClientContext::TryBindRelation ( Relation & relation,
vector< ColumnDefinition > & result_columns )

Try to bind a relation in the current client context; either throws an exception or fills the result_columns list with the set of returned columns.

273793 {
273794#ifdef DEBUG
273795 D_ASSERT(!relation.GetAlias().empty());
273796 D_ASSERT(!relation.ToString().empty());
273797#endif
273798 RunFunctionInTransaction([&]() { InternalTryBindRelation(relation, result_columns); });
273799}
DUCKDB_API void InternalTryBindRelation(Relation &relation, vector< ColumnDefinition > &result_columns)
Internal function for try bind relation. It does not require a client-context lock.
Definition duckdb.cpp:273781
Here is the call graph for this function:

◆ InternalTryBindRelation()

void duckdb::ClientContext::InternalTryBindRelation ( Relation & relation,
vector< ColumnDefinition > & result_columns )

Internal function for try bind relation. It does not require a client-context lock.

273781 {
273782 // bind the expressions
273783 auto binder = Binder::CreateBinder(*this);
273784 auto result = relation.Bind(*binder);
273785 D_ASSERT(result.names.size() == result.types.size());
273786
273787 result_columns.reserve(result_columns.size() + result.names.size());
273788 for (idx_t i = 0; i < result.names.size(); i++) {
273789 result_columns.emplace_back(result.names[i], result.types[i]);
273790 }
273791}
Here is the caller graph for this function:

◆ PendingQuery() [6/7]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQuery ( const shared_ptr< Relation > & relation,
QueryParameters query_parameters )

Execute a relation.

273849 {
273850 auto lock = LockContext();
273851 return PendingQueryInternal(*lock, relation, query_parameters);
273852}
Here is the call graph for this function:

◆ Execute() [1/3]

unique_ptr< QueryResult > duckdb::ClientContext::Execute ( const shared_ptr< Relation > & relation)
273854 {
273855 auto lock = LockContext();
273856 auto &expected_columns = relation->Columns();
273857 auto pending = PendingQueryInternal(*lock, relation, false);
273858 if (!pending->success) {
273859 return ErrorResult<MaterializedQueryResult>(pending->GetErrorObject());
273860 }
273861
273862 unique_ptr<QueryResult> result;
273863 result = ExecutePendingQueryInternal(*lock, *pending);
273864 if (result->HasError()) {
273865 return result;
273866 }
273867 // verify that the result types and result names of the query match the expected result types/names
273868 if (result->types.size() == expected_columns.size()) {
273869 bool mismatch = false;
273870 for (idx_t i = 0; i < result->types.size(); i++) {
273871 if (result->types[i] != expected_columns[i].Type() || result->names[i] != expected_columns[i].Name()) {
273872 mismatch = true;
273873 break;
273874 }
273875 }
273876 if (!mismatch) {
273877 // all is as expected: return the result
273878 return result;
273879 }
273880 }
273881 // result mismatch
273882 string err_str = "Result mismatch in query!\nExpected the following columns: [";
273883 for (idx_t i = 0; i < expected_columns.size(); i++) {
273884 if (i > 0) {
273885 err_str += ", ";
273886 }
273887 err_str += expected_columns[i].Name() + " " + expected_columns[i].Type().ToString();
273888 }
273889 err_str += "]\nBut result contained the following: ";
273890 for (idx_t i = 0; i < result->types.size(); i++) {
273891 err_str += i == 0 ? "[" : ", ";
273892 err_str += result->names[i] + " " + result->types[i].ToString();
273893 }
273894 err_str += "]";
273895 return ErrorResult<MaterializedQueryResult>(ErrorData(err_str));
273896}

◆ Prepare() [1/2]

unique_ptr< PreparedStatement > duckdb::ClientContext::Prepare ( const string & query)

Prepare a query.

273252 {
273253 auto lock = LockContext();
273254 // prepare the query
273255 try {
273256 InitialCleanup(*lock);
273257
273258 // first parse the query
273259 auto statements = ParseStatementsInternal(*lock, query);
273260 if (statements.empty()) {
273261 throw InvalidInputException("No statement to prepare!");
273262 }
273263 if (statements.size() > 1) {
273264 throw InvalidInputException("Cannot prepare multiple statements at once!");
273265 }
273266 return PrepareInternal(*lock, std::move(statements[0]));
273267 } catch (std::exception &ex) {
273268 return ErrorResult<PreparedStatement>(ErrorData(ex), query);
273269 }
273270}
Here is the call graph for this function:

◆ Prepare() [2/2]

unique_ptr< PreparedStatement > duckdb::ClientContext::Prepare ( unique_ptr< SQLStatement > statement)

Directly prepare a SQL statement.

273238 {
273239 auto lock = LockContext();
273240 // Store the query in case of an error.
273241 auto query = statement->query;
273242
273243 // Try to prepare.
273244 try {
273245 InitialCleanup(*lock);
273246 return PrepareInternal(*lock, std::move(statement));
273247 } catch (std::exception &ex) {
273248 return ErrorResult<PreparedStatement>(ErrorData(ex), query);
273249 }
273250}
Here is the call graph for this function:

◆ PendingQuery() [7/7]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQuery ( const string & query,
shared_ptr< PreparedStatementData > & prepared,
const PendingQueryParameters & parameters )

Create a pending query result from a prepared statement with the given name and set of parameters It is possible that the prepared statement will be re-bound. This will generally happen if the catalog is modified in between the prepared statement being bound and the prepared statement being run.

273285 {
273286 auto lock = LockContext();
273287 return PendingQueryPreparedInternal(*lock, query, prepared, parameters);
273288}

◆ Execute() [2/3]

unique_ptr< QueryResult > duckdb::ClientContext::Execute ( const string & query,
shared_ptr< PreparedStatementData > & prepared,
case_insensitive_map_t< BoundParameterData > & values,
QueryParameters query_parameters = QueryResultOutputType::ALLOW_STREAMING )

Execute a prepared statement with the given name and set of parameters It is possible that the prepared statement will be re-bound. This will generally happen if the catalog is modified in between the prepared statement being bound and the prepared statement being run.

273302 {
273303 PendingQueryParameters parameters;
273304 parameters.parameters = &values;
273305 parameters.query_parameters = query_parameters;
273306 return Execute(query, prepared, parameters);
273307}

◆ Execute() [3/3]

unique_ptr< QueryResult > duckdb::ClientContext::Execute ( const string & query,
shared_ptr< PreparedStatementData > & prepared,
const PendingQueryParameters & parameters )
273291 {
273292 auto lock = LockContext();
273293 auto pending = PendingQueryPreparedInternal(*lock, query, prepared, parameters);
273294 if (pending->HasError()) {
273295 return ErrorResult<MaterializedQueryResult>(pending->GetErrorObject());
273296 }
273297 return pending->ExecuteInternal(*lock);
273298}

◆ GetQueryProgress()

QueryProgress duckdb::ClientContext::GetQueryProgress ( )

Gets current percentage of the query's progress, returns 0 in case the progress bar is disabled.

272966 {
272967 return query_progress;
272968}
QueryProgress query_progress
The current query progress.
Definition duckdb.hpp:41811

◆ RegisterFunction()

void duckdb::ClientContext::RegisterFunction ( CreateFunctionInfo & info)

Register function in the temporary schema.

273680 {
273682 auto existing_function = Catalog::GetEntry<ScalarFunctionCatalogEntry>(*this, INVALID_CATALOG, info.schema,
273683 info.name, OnEntryNotFound::RETURN_NULL);
273684 if (existing_function) {
273685 auto &new_info = info.Cast<CreateScalarFunctionInfo>();
273686 if (new_info.functions.MergeFunctionSet(existing_function->functions)) {
273687 // function info was updated from catalog entry, rewrite is needed
273688 info.on_conflict = OnCreateConflict::REPLACE_ON_CONFLICT;
273689 }
273690 }
273691 // create function
273692 auto &catalog = Catalog::GetSystemCatalog(*this);
273693 catalog.CreateFunction(*this, info);
273694 });
273695}
static DUCKDB_API Catalog & GetSystemCatalog(ClientContext &context)
Get the SystemCatalog from the ClientContext.
Definition duckdb.cpp:7173
Here is the call graph for this function:

◆ ParseStatements() [1/2]

vector< unique_ptr< SQLStatement > > duckdb::ClientContext::ParseStatements ( const string & query)

Parse statements from a query.

273159 {
273160 auto lock = LockContext();
273161 return ParseStatementsInternal(*lock, query);
273162}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ExtractPlan()

unique_ptr< LogicalOperator > duckdb::ClientContext::ExtractPlan ( const string & query)

Extract the logical plan of a query.

273192 {
273193 auto lock = LockContext();
273194
273195 auto statements = ParseStatementsInternal(*lock, query);
273196 if (statements.size() != 1) {
273197 throw InvalidInputException("ExtractPlan can only prepare a single statement");
273198 }
273199
273200 unique_ptr<LogicalOperator> plan;
273201 RunFunctionInTransactionInternal(*lock, [&]() {
273202 Planner planner(*this);
273203 planner.CreatePlan(std::move(statements[0]));
273204 D_ASSERT(planner.plan);
273205
273206 plan = std::move(planner.plan);
273207
273208 if (config.enable_optimizer) {
273209 Optimizer optimizer(*planner.binder, *this);
273210 plan = optimizer.Optimize(std::move(plan));
273211 }
273212
273213 ColumnBindingResolver resolver;
273214 resolver.Verify(*plan);
273215 resolver.VisitOperator(*plan);
273216
273217 plan->ResolveOperatorTypes();
273218 });
273219 return plan;
273220}
DUCKDB_API void RunFunctionInTransactionInternal(ClientContextLock &lock, const std::function< void(void)> &fun, bool requires_valid_transaction=true)
Same as RunFunctionInTransaction, but does not obtain a lock on the client context or check for valid...
Definition duckdb.cpp:273697
ClientConfig config
The client configuration.
Definition duckdb.hpp:41576
Here is the call graph for this function:

◆ PreprocessStatements()

void duckdb::ClientContext::PreprocessStatements ( vector< unique_ptr< SQLStatement > > & statements)
273183 {
273184 auto lock = LockContext();
273185
273186 StatementPreprocessor preprocessor(*this);
273187 const CurrentTransactionState transaction_context_state =
273188 transaction.HasActiveTransaction() ? IN_ACTIVE_TRANSACTION : NOT_IN_ACTIVE_TRANSACTION;
273189 preprocessor.Preprocess(*lock, statements, transaction_context_state);
273190}

◆ RunFunctionInTransaction()

void duckdb::ClientContext::RunFunctionInTransaction ( const std::function< void(void)> & fun,
bool requires_valid_transaction = true )

Runs a function with a valid transaction context, potentially starting a transaction if the context is in auto commit mode.

273735 {
273736 auto lock = LockContext();
273737 RunFunctionInTransactionInternal(*lock, fun, requires_valid_transaction);
273738}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RunFunctionInTransactionInternal()

void duckdb::ClientContext::RunFunctionInTransactionInternal ( ClientContextLock & lock,
const std::function< void(void)> & fun,
bool requires_valid_transaction = true )

Same as RunFunctionInTransaction, but does not obtain a lock on the client context or check for validation.

273698 {
273699 if (requires_valid_transaction && transaction.HasActiveTransaction() &&
273700 ValidChecker::IsInvalidated(ActiveTransaction())) {
273701 throw TransactionException(ErrorManager::FormatException(*this, ErrorType::INVALIDATED_TRANSACTION));
273702 }
273703
273704 // check if we are on AutoCommit. In this case we should start a transaction
273705 bool require_new_transaction = transaction.IsAutoCommit() && !transaction.HasActiveTransaction();
273706 if (require_new_transaction) {
273707 D_ASSERT(!active_query);
273708 transaction.BeginTransaction();
273709 interrupted = false;
273710 }
273711 try {
273712 fun();
273713 } catch (std::exception &ex) {
273714 ErrorData error(ex);
273715 bool invalidates_transaction = true;
273716 if (!ErrorInvalidatesTransaction(error.Type())) {
273717 // standard exceptions don't invalidate the transaction
273718 invalidates_transaction = false;
273719 } else if (Exception::InvalidatesDatabase(error.Type())) {
273720 auto &db_instance = DatabaseInstance::GetDatabase(*this);
273721 ValidChecker::Invalidate(db_instance, error.RawMessage());
273722 }
273723 if (require_new_transaction) {
273724 transaction.Rollback(error);
273725 } else if (invalidates_transaction) {
273726 ValidChecker::Invalidate(ActiveTransaction(), error.RawMessage());
273727 }
273728 throw;
273729 }
273730 if (require_new_transaction) {
273731 transaction.Commit();
273732 }
273733}
unique_ptr< ActiveQueryContext > active_query
The currently active query context.
Definition duckdb.hpp:41809
Here is the caller graph for this function:

◆ TryGetCurrentSetting()

SettingLookupResult duckdb::ClientContext::TryGetCurrentSetting ( const string & key,
Value & result ) const

Equivalent to CURRENT_SETTING(key) SQL function.

273898 {
273899 optional_ptr<const ConfigurationOption> option;
273900 // try to get the setting index
273901 auto &db_config = DBConfig::GetConfig(*this);
273902 auto setting_index = db_config.TryGetSettingIndex(key, option);
273903 if (setting_index.IsValid()) {
273904 // generic setting - try to fetch it
273905 auto lookup_result =
273906 config.user_settings.TryGetSetting(db_config.user_settings, setting_index.GetIndex(), result);
273907 if (lookup_result) {
273908 return lookup_result;
273909 }
273910 }
273911 if (option && option->get_setting) {
273912 // legacy callback
273913 result = option->get_setting(*this);
273914 return SettingLookupResult(SettingScope::LOCAL);
273915 }
273916 // setting is not set - get the default value
273917 return DBConfig::TryGetDefaultValue(option, result);
273918}
@ LOCAL
Setting is from the local Setting scope.
Definition duckdb.hpp:37012
static SettingLookupResult TryGetDefaultValue(optional_ptr< const ConfigurationOption > option, Value &result)
Returns the default value of an option.
Definition duckdb.cpp:275253
Here is the call graph for this function:

◆ TryGetCurrentUserSetting()

SettingLookupResult duckdb::ClientContext::TryGetCurrentUserSetting ( idx_t setting_index,
Value & result ) const

Returns the value of the current setting set by the user - if the user has set it.

273920 {
273921 auto &db_config = DBConfig::GetConfig(*this);
273922 return config.user_settings.TryGetSetting(db_config.user_settings, setting_index, result);
273923}

◆ GetParserOptions()

ParserOptions duckdb::ClientContext::GetParserOptions ( ) const

Returns the parser options for this client context.

273925 {
273926 ParserOptions options;
273927 options.preserve_identifier_case = Settings::Get<PreserveIdentifierCaseSetting>(*this);
273928 options.integer_division = Settings::Get<IntegerDivisionSetting>(*this);
273929 options.max_expression_depth = Settings::Get<MaxExpressionDepthSetting>(*this);
273930 options.extensions = DBConfig::GetConfig(*this).GetCallbackManager();
273931 options.parser_override_setting = Settings::Get<AllowParserOverrideExtensionSetting>(*this);
273932 return options;
273933}
Here is the caller graph for this function:

◆ IsActiveResult()

bool duckdb::ClientContext::IsActiveResult ( ClientContextLock & lock,
BaseQueryResult & result )

Whether or not the given result object (streaming query result or pending query result) is active.

273344 {
273345 if (!active_query) {
273346 return false;
273347 }
273348 return active_query->IsOpenResult(result);
273349}

◆ GetExecutor()

Executor & duckdb::ClientContext::GetExecutor ( )

Returns the current executor.

272801 {
272802 D_ASSERT(active_query);
272803 D_ASSERT(active_query->executor);
272804 return *active_query->executor;
272805}

◆ GetLogger()

Logger & duckdb::ClientContext::GetLogger ( ) const

Return the current logger.

272807 {
272808 return *logger;
272809}

◆ GetCurrentQuery()

const string & duckdb::ClientContext::GetCurrentQuery ( )

Returns the current query string (if any).

272811 {
272812 D_ASSERT(active_query);
272813 return active_query->query;
272814}

◆ GetConnectionId()

connection_t duckdb::ClientContext::GetConnectionId ( ) const
272816 {
272817 return connection_id;
272818}

◆ GetTableNames()

unordered_set< string > duckdb::ClientContext::GetTableNames ( const string & query,
const bool qualified = false )

Fetch the set of tables names of the query. Returns the fully qualified, escaped table names, if qualified is set to true, else returns the not qualified, not escaped table names.

273801 {
273802 auto lock = LockContext();
273803
273804 auto statements = ParseStatementsInternal(*lock, query);
273805 if (statements.size() != 1) {
273806 throw InvalidInputException("Expected a single statement");
273807 }
273808
273809 unordered_set<string> result;
273810 RunFunctionInTransactionInternal(*lock, [&]() {
273811 // bind the expressions
273812 auto binder = Binder::CreateBinder(*this);
273813 auto mode = qualified ? BindingMode::EXTRACT_QUALIFIED_NAMES : BindingMode::EXTRACT_NAMES;
273814 binder->SetBindingMode(mode);
273815 binder->Bind(*statements[0]);
273816 result = binder->GetTableNames();
273817 });
273818 return result;
273819}
Here is the call graph for this function:

◆ GetClientProperties()

ClientProperties duckdb::ClientContext::GetClientProperties ( )
273935 {
273936 string timezone = "UTC";
273937 Value result;
273938
273939 if (TryGetCurrentSetting("TimeZone", result)) {
273940 timezone = result.ToString();
273941 }
273942 ArrowOffsetSize arrow_offset_size = ArrowOffsetSize::REGULAR;
273943 if (Settings::Get<ArrowLargeBufferSizeSetting>(*this)) {
273944 arrow_offset_size = ArrowOffsetSize::LARGE;
273945 }
273946 bool arrow_use_list_view = Settings::Get<ArrowOutputListViewSetting>(*this);
273947 bool arrow_lossless_conversion = Settings::Get<ArrowLosslessConversionSetting>(*this);
273948 bool arrow_use_string_view = Settings::Get<ProduceArrowStringViewSetting>(*this);
273949 auto arrow_format_version = Settings::Get<ArrowOutputVersionSetting>(*this);
273950 return {timezone,
273951 arrow_offset_size,
273952 arrow_use_list_view,
273953 arrow_use_string_view,
273954 arrow_lossless_conversion,
273955 arrow_format_version,
273956 this};
273957}
DUCKDB_API SettingLookupResult TryGetCurrentSetting(const string &key, Value &result) const
Equivalent to CURRENT_SETTING(key) SQL function.
Definition duckdb.cpp:273898

◆ ExecutionIsFinished()

bool duckdb::ClientContext::ExecutionIsFinished ( )

Returns true if execution of the current query is finished.

273959 {
273960 if (!active_query || !active_query->executor) {
273961 return false;
273962 }
273963 return active_query->executor->ExecutionIsFinished();
273964}

◆ ProcessError()

void duckdb::ClientContext::ProcessError ( ErrorData & error,
const string & query ) const

Process an error for display to the user.

272673 {
272674 error.FinalizeError();
272675 if (Settings::Get<ErrorsAsJSONSetting>(*this)) {
272676 error.ConvertErrorToJSON();
272677 } else {
272678 error.AddErrorLocation(query);
272679 }
272680}
Here is the caller graph for this function:

◆ ParseLogicalType()

LogicalType duckdb::ClientContext::ParseLogicalType ( const string & type)
273966 {
273967 auto lock = LockContext();
273968 LogicalType logical_type;
273970 [&]() { logical_type = TypeManager::Get(*db).ParseLogicalType(type, *this); });
273971 return logical_type;
273972}
static TypeManager & Get(DatabaseInstance &db)
Get the TypeManager from the DatabaseInstance.
Definition duckdb.cpp:130106
LogicalType ParseLogicalType(const string &type_str, ClientContext &context) const
Try to parse and bind a logical type from a string. Throws an exception if the type could not be pars...
Definition duckdb.cpp:130102

◆ ParseStatements() [2/2]

vector< unique_ptr< SQLStatement > > duckdb::ClientContext::ParseStatements ( ClientContextLock & lock,
const string & query )
private

Parse statements and resolve pragmas from a query.

273568 {
273569 InitialCleanup(lock);
273570 // parse the query and transform it into a set of statements
273571 return ParseStatementsInternal(lock, query);
273572}
Here is the call graph for this function:

◆ PendingQueryInternal() [1/2]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQueryInternal ( ClientContextLock & lock,
unique_ptr< SQLStatement > statement,
const PendingQueryParameters & parameters,
bool verify = true )
private

Issues a query to the database and returns a Pending Query Result.

273636 {
273637 auto query = statement->query;
273638 shared_ptr<PreparedStatementData> prepared;
273639 if (verify) {
273640 return PendingStatementOrPreparedStatementInternal(lock, query, std::move(statement), prepared, parameters);
273641 } else {
273642 return PendingStatementOrPreparedStatement(lock, query, std::move(statement), prepared, parameters);
273643 }
273644}
Here is the caller graph for this function:

◆ ExecutePendingQueryInternal()

unique_ptr< QueryResult > duckdb::ClientContext::ExecutePendingQueryInternal ( ClientContextLock & lock,
PendingQueryResult & query )
private
273646 {
273647 return query.ExecuteInternal(lock);
273648}

◆ ParseStatementsInternal()

vector< unique_ptr< SQLStatement > > duckdb::ClientContext::ParseStatementsInternal ( ClientContextLock & lock,
const string & query )
private

Parse statements from a query.

273164 {
273165 try {
273166 Parser parser(GetParserOptions());
273167 parser.ParseQuery(query);
273168
273169 StatementPreprocessor preprocessor(*this);
273170
273171 const CurrentTransactionState transaction_context_state =
273172 transaction.HasActiveTransaction() ? IN_ACTIVE_TRANSACTION : NOT_IN_ACTIVE_TRANSACTION;
273173 preprocessor.Preprocess(lock, parser.statements, transaction_context_state);
273174
273175 return std::move(parser.statements);
273176 } catch (std::exception &ex) {
273177 auto error = ErrorData(ex);
273178 ProcessError(error, query);
273179 error.Throw();
273180 }
273181}
DUCKDB_API ParserOptions GetParserOptions() const
Returns the parser options for this client context.
Definition duckdb.cpp:273925
Here is the call graph for this function:
Here is the caller graph for this function:

◆ VerifyQuery()

ErrorData duckdb::ClientContext::VerifyQuery ( ClientContextLock & lock,
const string & query,
unique_ptr< SQLStatement > statement,
PendingQueryParameters parameters )
private

Perform aggressive query verification of a SELECT statement. Only called when query_verification_enabled is true.

274366 {
274367 D_ASSERT(statement->type == StatementType::SELECT_STATEMENT);
274368 // Aggressive query verification
274369
274370#ifdef DUCKDB_RUN_SLOW_VERIFIERS
274371 bool run_slow_verifiers = true;
274372#else
274373 bool run_slow_verifiers = false;
274374#endif
274375
274376 auto parameters = query_parameters.parameters;
274377 query_parameters.query_parameters.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
274378 query_parameters.query_parameters.memory_type = QueryResultMemoryType::IN_MEMORY;
274379
274380 // The purpose of this function is to test correctness of otherwise hard to test features:
274381 // Copy() of statements and expressions
274382 // Serialize()/Deserialize() of expressions
274383 // Hash() of expressions
274384 // Equality() of statements and expressions
274385 // ToString() of statements and expressions
274386 // Correctness of plans both with and without optimizers
274387
274388 const auto &stmt = *statement;
274389 vector<unique_ptr<StatementVerifier>> statement_verifiers;
274390 unique_ptr<StatementVerifier> prepared_statement_verifier;
274391
274392 // Base Statement verifiers: these are the verifiers we enable for regular builds
274393 if (config.query_verification_enabled) {
274394 statement_verifiers.emplace_back(StatementVerifier::Create(VerificationType::COPIED, stmt, parameters));
274395 statement_verifiers.emplace_back(StatementVerifier::Create(VerificationType::DESERIALIZED, stmt, parameters));
274396 statement_verifiers.emplace_back(StatementVerifier::Create(VerificationType::UNOPTIMIZED, stmt, parameters));
274397 statement_verifiers.emplace_back(
274398 StatementVerifier::Create(VerificationType::NO_OPERATOR_CACHING, stmt, parameters));
274399
274400 // FIXME: Prepared parameter verifier is broken for queries with parameters
274401 if (!parameters || parameters->empty()) {
274402 prepared_statement_verifier = StatementVerifier::Create(VerificationType::PREPARED, stmt, parameters);
274403 }
274404 }
274405
274406 // This verifier is enabled explicitly OR by enabling run_slow_verifiers
274407 if (config.verify_fetch_row || (run_slow_verifiers && config.query_verification_enabled)) {
274408 statement_verifiers.emplace_back(
274409 StatementVerifier::Create(VerificationType::FETCH_ROW_AS_SCAN, stmt, parameters));
274410 }
274411
274412 // Verify external always needs to be explicitly enabled and is never part of default verifier set
274413 if (config.verify_external) {
274414 statement_verifiers.emplace_back(StatementVerifier::Create(VerificationType::EXTERNAL, stmt, parameters));
274415 }
274416
274417 auto original = make_uniq<StatementVerifier>(std::move(statement), parameters);
274418 for (auto &verifier : statement_verifiers) {
274419 original->CheckExpressions(*verifier);
274420 }
274421 original->CheckExpressions();
274422
274423 // See below
274424 auto statement_copy_for_explain = stmt.Copy();
274425
274426 // Save settings
274427 bool optimizer_enabled = config.enable_optimizer;
274428 bool profiling_is_enabled = config.enable_profiler;
274429 bool force_external = config.force_external;
274430
274431 // Disable profiling if it is enabled
274432 if (profiling_is_enabled) {
274433 config.enable_profiler = false;
274434 }
274435
274436 // Execute the original statement
274437 bool any_failed = original->Run(*this, query,
274438 [&](const string &q, unique_ptr<SQLStatement> s,
274439 optional_ptr<case_insensitive_map_t<BoundParameterData>> params) {
274440 return RunStatementInternal(lock, q, std::move(s), query_parameters, false);
274441 });
274442 if (!any_failed) {
274443 statement_verifiers.emplace_back(
274444 StatementVerifier::Create(VerificationType::PARSED, *statement_copy_for_explain, parameters));
274445 }
274446 // Execute the verifiers
274447 for (auto &verifier : statement_verifiers) {
274448 bool failed = verifier->Run(*this, query,
274449 [&](const string &q, unique_ptr<SQLStatement> s,
274450 optional_ptr<case_insensitive_map_t<BoundParameterData>> params) {
274451 return RunStatementInternal(lock, q, std::move(s), query_parameters, false);
274452 });
274453 any_failed = any_failed || failed;
274454 }
274455
274456 if (!any_failed && prepared_statement_verifier) {
274457 // If none failed, we execute the prepared statement verifier
274458 bool failed = prepared_statement_verifier->Run(
274459 *this, query,
274460 [&](const string &q, unique_ptr<SQLStatement> s,
274461 optional_ptr<case_insensitive_map_t<BoundParameterData>> params) {
274462 return RunStatementInternal(lock, q, std::move(s), query_parameters, false);
274463 });
274464 if (!failed) {
274465 // PreparedStatementVerifier fails if it runs into a ParameterNotAllowedException, which is OK
274466 statement_verifiers.push_back(std::move(prepared_statement_verifier));
274467 } else {
274468 // If it does fail, let's make sure it's not an internal exception
274469 ThrowIfExceptionIsInternal(*prepared_statement_verifier);
274470 }
274471 } else {
274472 if (ValidChecker::IsInvalidated(*db)) {
274473 return original->materialized_result->GetErrorObject();
274474 }
274475 if (transaction.HasActiveTransaction() && ValidChecker::IsInvalidated(ActiveTransaction())) {
274476 return original->materialized_result->GetErrorObject();
274477 }
274478 }
274479
274480 // Restore config setting
274481 config.enable_optimizer = optimizer_enabled;
274482 config.force_external = force_external;
274483
274484 // Check explain, only if q does not already contain EXPLAIN
274485 if (original->materialized_result->success) {
274486 auto explain_q = "EXPLAIN " + query;
274487 auto original_named_param_map = statement_copy_for_explain->named_param_map;
274488 auto explain_stmt = make_uniq<ExplainStatement>(std::move(statement_copy_for_explain));
274489 explain_stmt->named_param_map = original_named_param_map;
274490
274491 auto explain_statement_verifier =
274492 StatementVerifier::Create(VerificationType::EXPLAIN, *explain_stmt, parameters);
274493 const auto explain_failed = explain_statement_verifier->Run(
274494 *this, explain_q,
274495 [&](const string &q, unique_ptr<SQLStatement> s,
274496 optional_ptr<case_insensitive_map_t<BoundParameterData>> params) {
274497 return RunStatementInternal(lock, q, std::move(s), query_parameters, false);
274498 });
274499
274500 if (explain_failed) { // LCOV_EXCL_START
274501 const auto &explain_error = explain_statement_verifier->materialized_result->error;
274502 return ErrorData(explain_error.Type(), StringUtil::Format("Query succeeded but EXPLAIN failed with: %s",
274503 explain_error.RawMessage()));
274504 } // LCOV_EXCL_STOP
274505
274506#ifdef DUCKDB_VERIFY_BOX_RENDERER
274507 // this is pretty slow, so disabled by default
274508 // test the box renderer on the result
274509 // we mostly care that this does not crash
274510 RandomEngine random;
274511 BoxRendererConfig config;
274512 // test with a random width
274513 config.max_width = random.NextRandomInteger() % 500;
274514 BoxRenderer renderer(config);
274515 auto pinned_result_set = original->materialized_result->Pin();
274516 renderer.ToString(*this, original->materialized_result->names, pinned_result_set->collection);
274517#endif
274518 }
274519
274520 // Restore profiler setting
274521 if (profiling_is_enabled) {
274522 config.enable_profiler = true;
274523 }
274524
274525 // Now compare the results
274526 // The results of all runs should be identical
274527 for (auto &verifier : statement_verifiers) {
274528 auto result = original->CompareResults(*verifier);
274529 if (!result.empty()) {
274530 return ErrorData(result);
274531 }
274532 }
274533
274534 return ErrorData();
274535}
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:

◆ InitialCleanup()

void duckdb::ClientContext::InitialCleanup ( ClientContextLock & lock)
private

Cleanup any open results and reset the interrupted flag

273153 {
273155 CleanupInternal(lock);
273156 interrupted = false;
273157}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CleanupInternal()

void duckdb::ClientContext::CleanupInternal ( ClientContextLock & lock,
BaseQueryResult * result = nullptr,
bool invalidate_transaction = false )
private

Internal clean up, does not lock. Caller must hold the context_lock.

272775 {
272776 if (!active_query) {
272777 // no query currently active
272778 return;
272779 }
272780 if (active_query->executor) {
272781 active_query->executor->CancelTasks();
272782 }
272783 active_query->progress_bar.reset();
272784
272785 // Relaunch the threads if a SET THREADS command was issued
272786 auto &scheduler = TaskScheduler::GetScheduler(*this);
272787 scheduler.RelaunchThreads();
272788
272789 optional_ptr<ErrorData> passed_error = nullptr;
272790 if (result && result->HasError()) {
272791 passed_error = result->GetErrorObject();
272792 }
272793 auto error = EndQueryInternal(lock, result ? !result->HasError() : false, invalidate_transaction, passed_error);
272794 if (result && !result->HasError()) {
272795 // if an error occurred while committing report it in the result
272796 result->SetError(error);
272797 }
272798 D_ASSERT(!active_query);
272799}
Here is the caller graph for this function:

◆ PendingStatementOrPreparedStatement()

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingStatementOrPreparedStatement ( ClientContextLock & lock,
const string & query,
unique_ptr< SQLStatement > statement,
shared_ptr< PreparedStatementData > & prepared,
const PendingQueryParameters & parameters )
private
273424 {
273425 unique_ptr<PendingQueryResult> pending;
273426
273427 // Start the profiler.
273428 auto &profiler = QueryProfiler::Get(*this);
273429 profiler.StartQuery(query, IsExplainAnalyze(statement ? statement.get() : prepared->unbound_statement.get()));
273430
273431 try {
273432 BeginQueryInternal(lock, query);
273433 } catch (std::exception &ex) {
273434 ErrorData error(ex);
273435 if (Exception::InvalidatesDatabase(error.Type())) {
273436 // fatal exceptions invalidate the entire database
273437 auto &db_instance = DatabaseInstance::GetDatabase(*this);
273438 ValidChecker::Invalidate(db_instance, error.RawMessage());
273439 }
273440 return ErrorResult<PendingQueryResult>(std::move(error), query);
273441 }
273442
273443 bool invalidate_query = true;
273444 try {
273445 if (statement) {
273446 pending = PendingStatementInternal(lock, query, std::move(statement), parameters);
273447 } else {
273448 pending = PendingPreparedStatement(lock, query, prepared, parameters);
273449 }
273450 } catch (std::exception &ex) {
273451 ErrorData error(ex);
273452 if (!ErrorInvalidatesTransaction(error.Type())) {
273453 // standard exceptions do not invalidate the current transaction
273454 invalidate_query = false;
273455 } else if (Exception::InvalidatesDatabase(error.Type())) {
273456 // fatal exceptions invalidate the entire database
273457 if (!config.query_verification_enabled) {
273458 auto &db_instance = DatabaseInstance::GetDatabase(*this);
273459 ValidChecker::Invalidate(db_instance, error.RawMessage());
273460 }
273461 }
273462 // other types of exceptions do invalidate the current transaction
273463 pending = ErrorResult<PendingQueryResult>(std::move(error), query);
273464 }
273465 if (pending->HasError()) {
273466 // query failed: abort now
273467 EndQueryInternal(lock, false, invalidate_query, pending->GetErrorObject());
273468 return pending;
273469 }
273470 D_ASSERT(active_query->IsOpenResult(*pending));
273471 return pending;
273472}

◆ PendingPreparedStatement()

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingPreparedStatement ( ClientContextLock & lock,
const string & query,
shared_ptr< PreparedStatementData > statement_p,
const PendingQueryParameters & parameters )
private
273075 {
273076 CheckIfPreparedStatementIsExecutable(*prepared);
273077
273078 RebindQueryInfo rebind = RebindQueryInfo::DO_NOT_REBIND;
273079 if (prepared->RequireRebind(*this, parameters.parameters)) {
273080 rebind = RebindQueryInfo::ATTEMPT_TO_REBIND;
273081 }
273082
273083 for (auto &state : registered_state->States()) {
273084 PreparedStatementCallbackInfo info(*prepared, parameters);
273085 auto new_rebind = state->OnExecutePrepared(*this, info, rebind);
273086 if (new_rebind == RebindQueryInfo::ATTEMPT_TO_REBIND) {
273087 rebind = RebindQueryInfo::ATTEMPT_TO_REBIND;
273088 }
273089 }
273090 if (rebind == RebindQueryInfo::ATTEMPT_TO_REBIND) {
273091 RebindPreparedStatement(lock, query, prepared, parameters);
273092 CheckIfPreparedStatementIsExecutable(*prepared); // rerun this too as modified_databases might have changed
273093 }
273094 return PendingPreparedStatementInternal(lock, prepared, parameters);
273095}

◆ PendingPreparedStatementInternal()

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingPreparedStatementInternal ( ClientContextLock & lock,
shared_ptr< PreparedStatementData > statement_data_p,
const PendingQueryParameters & parameters )
private
273022 {
273023 D_ASSERT(active_query);
273024 auto &statement_data = *statement_data_p;
273025 BindPreparedStatementParameters(statement_data, parameters);
273026
273027 // Create the query executor.
273028 active_query->executor = make_uniq<Executor>(*this);
273029 auto &executor = *active_query->executor;
273030
273031 if (config.enable_progress_bar) {
273032 progress_bar_display_create_func_t display_create_func = nullptr;
273033 if (config.print_progress_bar) {
273034 // Use either a custom display function, or the default.
273035 display_create_func =
273036 config.display_create_func ? config.display_create_func : ProgressBar::DefaultProgressBarDisplay;
273037 }
273038 active_query->progress_bar =
273039 make_uniq<ProgressBar>(executor, NumericCast<idx_t>(config.wait_time), display_create_func);
273040 active_query->progress_bar->Start();
273041 query_progress.Restart();
273042 }
273043
273044 const auto stream_result = parameters.query_parameters.output_type == QueryResultOutputType::ALLOW_STREAMING &&
273045 statement_data.properties.output_type == QueryResultOutputType::ALLOW_STREAMING;
273046
273047 // Decide how to get the result collector.
273048 get_result_collector_t get_collector = PhysicalResultCollector::GetResultCollector;
273049 auto &client_config = ClientConfig::GetConfig(*this);
273050 if (!stream_result && client_config.get_result_collector) {
273051 get_collector = client_config.get_result_collector;
273052 }
273053 statement_data.output_type =
273054 stream_result ? QueryResultOutputType::ALLOW_STREAMING : QueryResultOutputType::FORCE_MATERIALIZED;
273055 statement_data.memory_type = parameters.query_parameters.memory_type;
273056
273057 // Get the result collector and initialize the executor.
273058 auto collector = get_collector(*this, statement_data);
273059 D_ASSERT(collector->type == PhysicalOperatorType::RESULT_COLLECTOR);
273060 executor.Initialize(std::move(collector));
273061
273062 auto types = executor.GetTypes();
273063 D_ASSERT(types == statement_data.types);
273064 D_ASSERT(!active_query->HasOpenResult());
273065
273066 auto pending_result =
273067 make_uniq<PendingQueryResult>(shared_from_this(), *statement_data_p, std::move(types), stream_result);
273068 active_query->prepared = std::move(statement_data_p);
273069 active_query->SetOpenResult(*pending_result);
273070 return pending_result;
273071}

◆ CheckIfPreparedStatementIsExecutable()

void duckdb::ClientContext::CheckIfPreparedStatementIsExecutable ( PreparedStatementData & statement)
private
272996 {
272997 if (ValidChecker::IsInvalidated(ActiveTransaction()) && statement.properties.requires_valid_transaction) {
272998 throw ErrorManager::InvalidatedTransaction(*this);
272999 }
273000
273001 auto &meta_transaction = MetaTransaction::Get(*this);
273002 auto &manager = DatabaseManager::Get(*this);
273003 for (auto &it : statement.properties.modified_databases) {
273004 auto &modified_database = it.first;
273005 auto entry = manager.GetDatabase(*this, modified_database);
273006 if (!entry) {
273007 // database has been detached
273008 throw InvalidInputException("Database \"%s\" not found", modified_database);
273009 }
273010 if (entry->IsReadOnly()) {
273011 throw InvalidInputException(StringUtil::Format(
273012 "Cannot execute statement of type \"%s\" on database \"%s\" which is attached in read-only mode!",
273013 StatementTypeToString(statement.statement_type), modified_database));
273014 }
273015 meta_transaction.ModifyDatabase(*entry, it.second.modifications);
273016 }
273017}

◆ CreatePreparedStatement()

shared_ptr< PreparedStatementData > duckdb::ClientContext::CreatePreparedStatement ( ClientContextLock & lock,
const string & query,
unique_ptr< SQLStatement > statement,
PendingQueryParameters parameters,
PreparedStatementMode mode = PreparedStatementMode::PREPARE_ONLY )
private

Internally prepare a SQL statement. Caller must hold the context_lock.

272921 {
272922 // check if any client context state could request a rebind
272923 bool can_request_rebind = false;
272924 for (auto &state : registered_state->States()) {
272925 if (state->CanRequestRebind()) {
272926 can_request_rebind = true;
272927 }
272928 }
272929 if (can_request_rebind) {
272930 bool rebind = false;
272931 // if any registered state can request a rebind we do the binding on a copy first
272932 shared_ptr<PreparedStatementData> result;
272933 try {
272934 result = CreatePreparedStatementInternal(lock, query, statement->Copy(), parameters);
272935 } catch (std::exception &ex) {
272936 ErrorData error(ex);
272937 // check if any registered client context state wants to try a rebind
272938 for (auto &state : registered_state->States()) {
272939 auto info = state->OnPlanningError(*this, *statement, error);
272940 if (info == RebindQueryInfo::ATTEMPT_TO_REBIND) {
272941 rebind = true;
272942 }
272943 }
272944 if (!rebind) {
272945 throw;
272946 }
272947 }
272948 if (result) {
272949 D_ASSERT(!rebind);
272950 for (auto &state : registered_state->States()) {
272951 auto info = state->OnFinalizePrepare(*this, *result, mode);
272952 if (info == RebindQueryInfo::ATTEMPT_TO_REBIND) {
272953 rebind = true;
272954 }
272955 }
272956 }
272957 if (!rebind) {
272958 return result;
272959 }
272960 // an extension wants to do a rebind - do it once
272961 }
272962
272963 return CreatePreparedStatementInternal(lock, query, std::move(statement), parameters);
272964}

◆ PendingStatementInternal()

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingStatementInternal ( ClientContextLock & lock,
const string & query,
unique_ptr< SQLStatement > statement,
const PendingQueryParameters & parameters )
private
273311 {
273312 // prepare the query for execution
273313 if (parameters.parameters) {
273314 PreparedStatement::VerifyParameters(*parameters.parameters, statement->named_param_map);
273315 }
273316
273317 auto prepared = CreatePreparedStatement(lock, query, std::move(statement), parameters,
273318 PreparedStatementMode::PREPARE_AND_EXECUTE);
273319
273320 idx_t parameter_count = !parameters.parameters ? 0 : parameters.parameters->size();
273321 if (prepared->properties.parameter_count > 0 && parameter_count == 0) {
273322 string error_message = StringUtil::Format("Expected %lld parameters, but none were supplied",
273323 prepared->properties.parameter_count);
273324 return ErrorResult<PendingQueryResult>(InvalidInputException(error_message), query);
273325 }
273326 if (!prepared->properties.bound_all_parameters) {
273327 return ErrorResult<PendingQueryResult>(InvalidInputException("Not all parameters were bound"), query);
273328 }
273329 // execute the prepared statement
273330 CheckIfPreparedStatementIsExecutable(*prepared);
273331 return PendingPreparedStatementInternal(lock, std::move(prepared), parameters);
273332}
shared_ptr< PreparedStatementData > CreatePreparedStatement(ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, PendingQueryParameters parameters, PreparedStatementMode mode=PreparedStatementMode::PREPARE_ONLY)
Internally prepare a SQL statement. Caller must hold the context_lock.
Definition duckdb.cpp:272918

◆ RunStatementInternal()

unique_ptr< QueryResult > duckdb::ClientContext::RunStatementInternal ( ClientContextLock & lock,
const string & query,
unique_ptr< SQLStatement > statement,
const PendingQueryParameters & parameters,
bool verify = true )
private
273336 {
273337 auto pending = PendingQueryInternal(lock, std::move(statement), parameters, verify);
273338 if (pending->HasError()) {
273339 return ErrorResult<MaterializedQueryResult>(pending->GetErrorObject());
273340 }
273341 return ExecutePendingQueryInternal(lock, *pending);
273342}

◆ PrepareInternal()

unique_ptr< PreparedStatement > duckdb::ClientContext::PrepareInternal ( ClientContextLock & lock,
unique_ptr< SQLStatement > statement )
private
273223 {
273224 auto named_param_map = statement->named_param_map;
273225 auto statement_query = statement->query;
273226 shared_ptr<PreparedStatementData> prepared_data;
273227 auto unbound_statement = statement->Copy();
273228 PendingQueryParameters parameters;
273230 lock,
273231 [&]() { prepared_data = CreatePreparedStatement(lock, statement_query, std::move(statement), parameters); },
273232 false);
273233 prepared_data->unbound_statement = std::move(unbound_statement);
273234 return make_uniq<PreparedStatement>(shared_from_this(), std::move(prepared_data), std::move(statement_query),
273235 std::move(named_param_map));
273236}

◆ LogQueryInternal()

void duckdb::ClientContext::LogQueryInternal ( ClientContextLock & lock,
const string & query )
private
273474 {
273475 if (!client_data->log_query_writer) {
273476#ifdef DUCKDB_FORCE_QUERY_LOG
273477 try {
273478 string log_path(DUCKDB_FORCE_QUERY_LOG);
273479 client_data->log_query_writer = make_uniq<BufferedFileWriter>(FileSystem::GetFileSystem(*this), log_path,
273480 BufferedFileWriter::DEFAULT_OPEN_FLAGS);
273481 } catch (...) {
273482 return;
273483 }
273484#else
273485 return;
273486#endif
273487 }
273488 // log query path is set: log the query
273489 client_data->log_query_writer->WriteData(const_data_ptr_cast(query.c_str()), query.size());
273490 client_data->log_query_writer->WriteData(const_data_ptr_cast("\n"), 1);
273491 client_data->log_query_writer->Flush();
273492 client_data->log_query_writer->Sync();
273493}

◆ FetchResultInternal()

unique_ptr< QueryResult > duckdb::ClientContext::FetchResultInternal ( ClientContextLock & lock,
PendingQueryResult & pending )
private
272820 {
272821 D_ASSERT(active_query);
272822 D_ASSERT(active_query->IsOpenResult(pending));
272823 D_ASSERT(active_query->prepared);
272824 auto &executor = GetExecutor();
272825 auto &prepared = *active_query->prepared;
272826 bool create_stream_result =
272827 prepared.properties.output_type == QueryResultOutputType::ALLOW_STREAMING && pending.allow_stream_result;
272828 unique_ptr<QueryResult> result;
272829 D_ASSERT(executor.HasResultCollector());
272830 // we have a result collector - fetch the result directly from the result collector
272831 result = executor.GetResult();
272832 if (!create_stream_result) {
272833 CleanupInternal(lock, result.get(), false);
272834 } else {
272835 active_query->SetOpenResult(*result);
272836 }
272837 return result;
272838}
Executor & GetExecutor()
Returns the current executor.
Definition duckdb.cpp:272801

◆ LockContext()

unique_ptr< ClientContextLock > duckdb::ClientContext::LockContext ( )
private
272658 {
272659 return make_uniq<ClientContextLock>(context_lock);
272660}
mutex context_lock
Lock on using the ClientContext in parallel.
Definition duckdb.hpp:41807

◆ BeginQueryInternal()

void duckdb::ClientContext::BeginQueryInternal ( ClientContextLock & lock,
const string & query )
private
272688 {
272689 // check if we are on AutoCommit. In this case we should start a transaction
272690 D_ASSERT(!active_query);
272691 auto &db_inst = DatabaseInstance::GetDatabase(*this);
272692 if (ValidChecker::IsInvalidated(db_inst)) {
272693 throw ErrorManager::InvalidatedDatabase(*this, ValidChecker::InvalidatedMessage(db_inst));
272694 }
272695 active_query = make_uniq<ActiveQueryContext>();
272696 if (transaction.IsAutoCommit()) {
272697 transaction.BeginTransaction();
272698 }
272699
272700 transaction.SetActiveQuery(db->GetDatabaseManager().GetNewQueryNumber());
272701 LogQueryInternal(lock, query);
272702 active_query->query = query;
272703
272704 query_progress.Initialize();
272705 // Notify any registered state of query begin
272706 for (auto &state : registered_state->States()) {
272707 state->QueryBegin(*this);
272708 }
272709
272710 // Flush the old logger.
272711 logger->Flush();
272712
272713 // Refresh the logger to ensure we are in sync with the global log settings.
272714 LoggingContext logging_context(LogContextScope::CONNECTION);
272715 logging_context.connection_id = connection_id;
272716 logging_context.transaction_id = transaction.ActiveTransaction().global_transaction_id;
272717 logging_context.query_id = transaction.GetActiveQuery();
272718 logger = db->GetLogManager().CreateLogger(logging_context, true);
272719 DUCKDB_LOG(*this, QueryLogType, query);
272720}

◆ EndQueryInternal()

ErrorData duckdb::ClientContext::EndQueryInternal ( ClientContextLock & lock,
bool success,
bool invalidate_transaction,
optional_ptr< ErrorData > previous_error )
private
272723 {
272724 if (active_query->executor) {
272725 active_query->executor->CancelTasks();
272726 }
272727 active_query->progress_bar.reset();
272728 D_ASSERT(active_query.get());
272729 active_query.reset();
272730 query_progress.Initialize();
272731 ErrorData error;
272732 try {
272733 if (transaction.HasActiveTransaction()) {
272734 transaction.ResetActiveQuery();
272735 if (transaction.IsAutoCommit()) {
272736 if (success) {
272737 transaction.Commit();
272738 } else {
272739 transaction.Rollback(previous_error);
272740 }
272741 } else if (invalidate_transaction) {
272742 D_ASSERT(!success);
272743 ValidChecker::Invalidate(ActiveTransaction(), "Failed to commit");
272744 }
272745 }
272746 } catch (std::exception &ex) {
272747 error = ErrorData(ex);
272748 if (Exception::InvalidatesDatabase(error.Type()) || error.Type() == ExceptionType::INTERNAL) {
272749 auto &db_inst = DatabaseInstance::GetDatabase(*this);
272750 ValidChecker::Invalidate(db_inst, error.RawMessage());
272751 }
272752 } catch (...) { // LCOV_EXCL_START
272753 error = ErrorData("Unhandled exception!");
272754 } // LCOV_EXCL_STOP
272755
272756 client_data->profiler->EndQuery();
272757
272758 // Refresh the logger
272759 logger->Flush();
272760 LoggingContext context(LogContextScope::CONNECTION);
272761 context.connection_id = reinterpret_cast<idx_t>(this);
272762 logger = db->GetLogManager().CreateLogger(context, true);
272763
272764 // Notify any registered state of query end
272765 for (auto const &s : registered_state->States()) {
272766 if (error.HasError()) {
272767 s->QueryEnd(*this, &error);
272768 } else {
272769 s->QueryEnd(*this, previous_error);
272770 }
272771 }
272772 return error;
272773}

◆ WaitForTask()

void duckdb::ClientContext::WaitForTask ( ClientContextLock & lock,
BaseQueryResult & result )
private

Wait until a task is available to execute.

273097 {
273098 active_query->executor->WaitForTask();
273099}

◆ ExecuteTaskInternal()

PendingExecutionResult duckdb::ClientContext::ExecuteTaskInternal ( ClientContextLock & lock,
BaseQueryResult & result,
bool dry_run = false )
private
273111 {
273112 D_ASSERT(active_query);
273113 D_ASSERT(active_query->IsOpenResult(result));
273114 bool invalidate_transaction = true;
273115 try {
273116 auto query_result = active_query->executor->ExecuteTask(dry_run);
273117 if (active_query->progress_bar) {
273118 auto is_finished = PendingQueryResult::IsResultReady(query_result);
273119 active_query->progress_bar->Update(is_finished);
273120 query_progress = active_query->progress_bar->GetDetailedQueryProgress();
273121 }
273122 return query_result;
273123 } catch (std::exception &ex) {
273124 auto error = ErrorData(ex);
273125 if (error.Type() == ExceptionType::INTERRUPT) {
273126 auto &executor = *active_query->executor;
273127 if (!executor.HasError()) {
273128 // Interrupted by the user
273129 result.SetError(ex);
273130 invalidate_transaction = true;
273131 } else {
273132 // Interrupted by an exception caused in a worker thread
273133 error = executor.GetError();
273134 invalidate_transaction = ErrorInvalidatesTransaction(error.Type());
273135 result.SetError(error);
273136 }
273137 } else if (!ErrorInvalidatesTransaction(error.Type())) {
273138 invalidate_transaction = false;
273139 } else if (Exception::InvalidatesDatabase(error.Type()) || error.Type() == ExceptionType::INTERNAL) {
273140 // fatal exceptions invalidate the entire database
273141 auto &db_instance = DatabaseInstance::GetDatabase(*this);
273142 ValidChecker::Invalidate(db_instance, error.RawMessage());
273143 }
273144 ProcessError(error, active_query->query);
273145 result.SetError(std::move(error));
273146 } catch (...) { // LCOV_EXCL_START
273147 result.SetError(ErrorData("Unhandled exception in ExecuteTaskInternal"));
273148 } // LCOV_EXCL_STOP
273149 EndQueryInternal(lock, false, invalidate_transaction, result.GetErrorObject());
273150 return PendingExecutionResult::EXECUTION_ERROR;
273151}
static DUCKDB_API bool IsResultReady(PendingExecutionResult result)
Function to determine whether execution is considered finished.
Definition duckdb.cpp:294344

◆ PendingStatementOrPreparedStatementInternal()

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingStatementOrPreparedStatementInternal ( ClientContextLock & lock,
const string & query,
unique_ptr< SQLStatement > statement,
shared_ptr< PreparedStatementData > & prepared,
const PendingQueryParameters & parameters )
private
273353 {
273354#ifdef DUCKDB_ALTERNATIVE_VERIFY
273355 if (statement && statement->type != StatementType::LOGICAL_PLAN_STATEMENT) {
273356 statement = statement->Copy();
273357 }
273358#endif
273359 if (statement && config.query_verification_enabled) {
273360 // query verification is enabled
273361 // create a copy of the statement, and use the copy
273362 // this way we verify that the copy correctly copies all properties
273363 auto copied_statement = statement->Copy();
273364 switch (statement->type) {
273365 case StatementType::SELECT_STATEMENT: {
273366 // in case this is a select query, we verify the original statement
273367 ErrorData error;
273368 try {
273369 error = VerifyQuery(lock, query, std::move(statement), parameters);
273370 } catch (std::exception &ex) {
273371 error = ErrorData(ex);
273372 }
273373 if (error.HasError()) {
273374 // error in verifying query
273375 return ErrorResult<PendingQueryResult>(std::move(error), query);
273376 }
273377 statement = std::move(copied_statement);
273378 break;
273379 }
273380 default: {
273381#ifndef DUCKDB_ALTERNATIVE_VERIFY
273382 bool reparse_statement = true;
273383#else
273384 bool reparse_statement = false;
273385#endif
273386 statement = std::move(copied_statement);
273387 if (statement->type == StatementType::RELATION_STATEMENT) {
273388 reparse_statement = false;
273389 }
273390 if (reparse_statement) {
273391 try {
273392 Parser parser(GetParserOptions());
273393 ErrorData error;
273394 parser.ParseQuery(statement->ToString());
273395 // FIXME: these properties don't round-trip in ToString(), so we overwrite them manually
273396 if (statement->type == StatementType::UPDATE_STATEMENT) {
273397 // re-apply `prioritize_table_when_binding` (which is normally set during transform)
273398 parser.statements[0]->Cast<UpdateStatement>().prioritize_table_when_binding =
273399 statement->Cast<UpdateStatement>().prioritize_table_when_binding;
273400 } else if (statement->type == StatementType::TRANSACTION_STATEMENT) {
273401 // re-apply invalidation policy
273402 auto &reparsed_transaction_stmt = parser.statements[0]->Cast<TransactionStatement>();
273403 auto &previous_transaction_stmt = statement->Cast<TransactionStatement>();
273404 reparsed_transaction_stmt.info->invalidation_policy =
273405 previous_transaction_stmt.info->invalidation_policy;
273406 // re-apply auto rollback
273407 parser.statements[0]->Cast<TransactionStatement>().info->auto_rollback =
273408 statement->Cast<TransactionStatement>().info->auto_rollback;
273409 }
273410 statement = std::move(parser.statements[0]);
273411 } catch (const NotImplementedException &) {
273412 // ToString was not implemented, just use the copied statement
273413 }
273414 }
273415 break;
273416 }
273417 }
273418 }
273419 return PendingStatementOrPreparedStatement(lock, query, std::move(statement), prepared, parameters);
273420}
ErrorData VerifyQuery(ClientContextLock &lock, const string &query, unique_ptr< SQLStatement > statement, PendingQueryParameters parameters)
Perform aggressive query verification of a SELECT statement. Only called when query_verification_enab...
Definition duckdb.cpp:274365

◆ PendingQueryPreparedInternal()

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQueryPreparedInternal ( ClientContextLock & lock,
const string & query,
shared_ptr< PreparedStatementData > & prepared,
const PendingQueryParameters & parameters )
private
273274 {
273275 try {
273276 InitialCleanup(lock);
273277 } catch (std::exception &ex) {
273278 return ErrorResult<PendingQueryResult>(ErrorData(ex), query);
273279 }
273280 return PendingStatementOrPreparedStatementInternal(lock, query, nullptr, prepared, parameters);
273281}

◆ PendingQueryInternal() [2/2]

unique_ptr< PendingQueryResult > duckdb::ClientContext::PendingQueryInternal ( ClientContextLock & lock,
const shared_ptr< Relation > & relation,
QueryParameters query_parameters )
private
273823 {
273824 InitialCleanup(lock);
273825
273826 string query;
273827 if (config.query_verification_enabled) {
273828 // run the ToString method of any relation we run, mostly to ensure it doesn't crash
273829 relation->ToString();
273830 relation->GetAlias();
273831 if (relation->IsReadOnly()) {
273832 // verify read only statements by running a select statement
273833 auto select = make_uniq<SelectStatement>();
273834 select->node = relation->GetQueryNode();
273835 PendingQueryParameters parameters;
273836 parameters.query_parameters = query_parameters;
273837 parameters.query_parameters.output_type = QueryResultOutputType::FORCE_MATERIALIZED;
273838 RunStatementInternal(lock, query, std::move(select), parameters);
273839 }
273840 }
273841
273842 auto relation_stmt = make_uniq<RelationStatement>(relation);
273843 PendingQueryParameters parameters;
273844 parameters.query_parameters = query_parameters;
273845 return PendingQueryInternal(lock, std::move(relation_stmt), parameters);
273846}
GMat select(const GMat &src1, const GMat &src2, const GMat &mask)

◆ RebindPreparedStatement()

void duckdb::ClientContext::RebindPreparedStatement ( ClientContextLock & lock,
const string & query,
shared_ptr< PreparedStatementData > & prepared,
const PendingQueryParameters & parameters )
private
272983 {
272984 if (!prepared->unbound_statement) {
272985 throw InternalException("ClientContext::RebindPreparedStatement called but PreparedStatementData did not have "
272986 "an unbound statement so rebinding cannot be done");
272987 }
272988 // catalog was modified: rebind the statement before execution
272989 auto new_prepared = CreatePreparedStatement(lock, query, prepared->unbound_statement->Copy(), parameters);
272990 D_ASSERT(new_prepared->properties.bound_all_parameters);
272991 new_prepared->properties.parameter_count = prepared->properties.parameter_count;
272992 prepared = std::move(new_prepared);
272993 prepared->properties.bound_all_parameters = false;
272994}

◆ ErrorResult()

template<class T>
unique_ptr< T > duckdb::ClientContext::ErrorResult ( ErrorData error,
const string & query = string() )
private
272683 {
272684 ProcessError(error, query);
272685 return make_uniq<T>(std::move(error));
272686}

◆ CreatePreparedStatementInternal()

shared_ptr< PreparedStatementData > duckdb::ClientContext::CreatePreparedStatementInternal ( ClientContextLock & lock,
const string & query,
unique_ptr< SQLStatement > statement,
PendingQueryParameters parameters )
private
272854 {
272855 StatementType statement_type = statement->type;
272856 auto result = make_shared_ptr<PreparedStatementData>(statement_type);
272857
272858 auto &profiler = QueryProfiler::Get(*this);
272859 profiler.StartQuery(query, IsExplainAnalyze(statement.get()), true);
272860 profiler.StartPhase(MetricType::PLANNER);
272861 Planner logical_planner(*this);
272862 if (parameters.parameters) {
272863 auto &parameter_values = *parameters.parameters;
272864 for (auto &value : parameter_values) {
272865 logical_planner.parameter_data.emplace(value.first, BoundParameterData(value.second));
272866 }
272867 }
272868
272869 logical_planner.CreatePlan(std::move(statement));
272870 D_ASSERT(logical_planner.plan || !logical_planner.properties.bound_all_parameters);
272871 profiler.EndPhase();
272872
272873 auto logical_plan = std::move(logical_planner.plan);
272874 // extract the result column names from the plan
272875 result->properties = logical_planner.properties;
272876 result->names = logical_planner.names;
272877 result->types = logical_planner.types;
272878 result->value_map = std::move(logical_planner.value_map);
272879 if (!logical_planner.properties.bound_all_parameters) {
272880 // not all parameters were bound - return
272881 return result;
272882 }
272883#ifdef DEBUG
272884 logical_plan->Verify(*this);
272885#endif
272886 if (result->properties.parameter_count > 0 && !parameters.parameters) {
272887 // if this is a prepared statement we can choose not to fully plan
272888 // if we have parameters, we might want to re-bind when they are available as we can then do more optimizations
272889 // in this situation we check if we want to cache the plan at all
272890 if (!PreparedStatement::CanCachePlan(*logical_plan)) {
272891 // we don't - early-out
272892 result->properties.always_require_rebind = true;
272893 return result;
272894 }
272895 }
272896
272897 if (config.enable_optimizer && logical_plan->RequireOptimizer()) {
272898 profiler.StartPhase(MetricType::ALL_OPTIMIZERS);
272899 Optimizer optimizer(*logical_planner.binder, *this);
272900 logical_plan = optimizer.Optimize(std::move(logical_plan));
272901 D_ASSERT(logical_plan);
272902 profiler.EndPhase();
272903
272904#ifdef DEBUG
272905 logical_plan->Verify(*this);
272906#endif
272907 }
272908
272909 // Convert the logical query plan into a physical query plan.
272910 profiler.StartPhase(MetricType::PHYSICAL_PLANNER);
272911 PhysicalPlanGenerator physical_planner(*this);
272912 result->physical_plan = physical_planner.Plan(std::move(logical_plan));
272913 profiler.EndPhase();
272914 D_ASSERT(result->physical_plan);
272915 return result;
272916}
static bool CanCachePlan(const LogicalOperator &op)
Returns whether or not we can / want to cache a logical plan.
Definition duckdb.cpp:294489

◆ ErrorInvalidatesTransaction()

bool duckdb::ClientContext::ErrorInvalidatesTransaction ( ExceptionType type)
private
273101 {
273102 switch (transaction.GetInvalidationPolicy()) {
273103 case TransactionInvalidationPolicy::ALL_ERRORS_INVALIDATE_TRANSACTION:
273104 return true;
273105 default:
273106 return Exception::InvalidatesTransaction(type);
273107 }
273108}

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