# Poco::Data

# class Statement

Library: Data
Package: DataCore
Header: Poco/Data/Statement.h

## Description

A Statement is used to execute SQL statements. It does not contain code of its own. Its main purpose is to forward calls to the concrete StatementImpl stored inside. Statement execution can be synchronous or asynchronous. Synchronous ececution is achieved through execute() call, while asynchronous is achieved through executeAsync() method call. An asynchronously executing statement should not be copied during the execution.

Note:

Once set as asynchronous through 'async' manipulator, statement remains asynchronous for all subsequent execution calls, both execute() and executeAsync(). However, calling executAsync() on a synchronous statement shall execute asynchronously but without altering the underlying statement's synchronous nature.

Once asynchronous, a statement can be reverted back to synchronous state in two ways:

    1) By calling setAsync(false)
    2) By means of 'sync' or 'reset' manipulators

See individual functions documentation for more details.

Statement owns the RowFormatter, which can be provided externaly through setFormatter() member function. If no formatter is externally supplied to the statement, the SimpleRowFormatter is lazy created and used.

If compiled with SQLParser support, Statement knows the number and type of the SQL statement(s) it contains, to the extent that the SQL string is a standard SQL and the staement type is supported. No proprietary SQL extensions are supported.

Supported statement types are:

- SELECT
- INSERT
- UPDATE
- DELETE

## Inheritance

Known Derived Classes: RecordSet

## Member Summary

Member Functions: addBind, addBinding, addExtract, addExtraction, addExtractions, affectedRowCount, bind, canModifyStorage, clear, columnsExtracted, dataSetCount, done, execute, executeAsync, executeDirect, extractionCount, extractions, getRowFormatter, getStorage, hasDelete, hasInsert, hasMoreDataSets, hasSelect, hasUpdate, impl, initialized, isAsync, isBulkExtraction, isDelete, isInsert, isNull, isSelect, isUpdate, metaColumn, nextDataSet, operator <<, operator =, operator,, parse, parseError, paused, previousDataSet, removeBind, reset, rowsExtracted, session, setAsync, setRowFormatter, setStorage, state, statementsCount, storage, subTotalRowCount, swap, toString, wait

## Types

### Manipulator

typedef void (* Manipulator)(Statement &);

## Types Aliases

### AsyncExecMethod

using AsyncExecMethod = ActiveMethod < std::size_t, bool, StatementImpl >;

### AsyncExecMethodPtr

using AsyncExecMethodPtr = SharedPtr < AsyncExecMethod >;

### ImplPtr

using ImplPtr = StatementImpl::Ptr;

### Result

using Result = ActiveResult < std::size_t >;

### ResultPtr

using ResultPtr = SharedPtr < Result >;

### State

using State = StatementImpl::State;

## Enumerations

### Storage

STORAGE_DEQUE = StatementImpl::STORAGE_DEQUE_IMPL

STORAGE_VECTOR = StatementImpl::STORAGE_VECTOR_IMPL

STORAGE_LIST = StatementImpl::STORAGE_LIST_IMPL

STORAGE_UNKNOWN = StatementImpl::STORAGE_UNKNOWN_IMPL

## Constructors

### Statement

Statement(
StatementImpl::Ptr pImpl
);

Creates the Statement.

### Statement

explicit Statement(
Session & session
);

Creates the Statement for the given Session.

The following:

    Statement stmt(sess);
    stmt << "SELECT * FROM Table", ...

is equivalent to:

    Statement stmt(sess << "SELECT * FROM Table", ...);

but in some cases better readable.

### Statement

Statement(
const Statement & stmt
);

Copy constructor. If the statement has been executed asynchronously and has not been synchronized prior to copy operation (i.e. is copied while executing), this constructor shall synchronize it.

### Statement

Statement(
Statement && other
) noexcept;

Move constructor.

## Destructor

### ~Statement

~Statement();

Destroys the Statement.

## Member Functions

### addBind

Statement & addBind(
AbstractBinding::Ptr pBind
);

Registers a single binding with the statement.

### addBinding

template < typename C > Statement & addBinding(
C & bindingCont,
bool reset
);

Registers binding container with the Statement.

### addExtract

Statement & addExtract(
AbstractExtraction::Ptr pExtract
);

Registers a single extraction with the statement.

### addExtraction

template < typename C > Statement & addExtraction(
C & val,
bool reset
);

Registers extraction container with the Statement.

### addExtractions

template < typename C > Statement & addExtractions(
C & val
);

Registers container of extraction containers with the Statement.

### affectedRowCount

std::size_t affectedRowCount() const;

Returns the number of affected rows. Used to find out the number of rows affected by insert, delete or update.

### bind

template < typename C > Statement & bind(
const C & value
);

Adds a binding to the Statement. This can be used to implement generic binding mechanisms and is a nicer syntax for:

    statement , bind(value);

### canModifyStorage

bool canModifyStorage();

Returns true if statement is in a state that allows the internal storage to be modified.

### columnsExtracted

std::size_t columnsExtracted(
int dataSet = StatementImpl::USE_CURRENT_DATA_SET
) const;

Returns the number of columns returned for current data set. Default value indicates current data set (if any).

### dataSetCount

std::size_t dataSetCount() const;

Returns the number of data sets associated with the statement.

### done

bool done();

Returns true if the statement was completely executed or false if a range limit stopped it and there is more work to do. When no limit is set, it will always return true after calling execute().

### execute

std::size_t execute(
bool reset = true
);

Executes the statement synchronously or asynchronously. Stops when either a limit is hit or the whole statement was executed. Returns the number of rows extracted from the database (for statements returning data) or number of rows affected (for all other statements). If reset is true (default), associated storage is reset and reused. Otherwise, the results from this execution step are appended. The reset argument has no meaning for unlimited statements that return all rows. If isAsync() returns true, the statement is executed asynchronously and the return value from this function is zero. The result of execution (i.e. number of returned or affected rows) can be obtained by calling wait() on the statement at a later point in time.

When Poco::Data is compiled with SQL parsing support, if session is not already in a transaction and not in autocommit mode, an attempt to parse the SQL is made before statement execution, and if (1) successful, and (2) the statement does not consist only of SELECT statements, a transaction is started.

Note that parsing is not guaranteed to succeed, as some backends have proprietary keywords not supported by the parser. Parsing failures are silent in terms of throwing exceptions or logging, but it is possible to get error information by calling Statement::parseError(). When parsing does not succeed, transaction is not started, and Poco::Data::Session will not reflect its state accurately. The underlying database session, however, will be in transaction state. In such state, in order to complete the transaction and unlock the resources, commit() or rollback() must be called on the Poco::Data::Session; this is true even for a single SELECT statement in non-autocommit mode when parsing does not succeed.

For Poco::Data builds without SQLParser support, the behavior is the same as for unsuccesful parsing.

### executeAsync

const Result & executeAsync(
bool reset = true
);

Executes the statement asynchronously. Stops when either a limit is hit or the whole statement was executed. Returns immediately. Calling wait() (on either the result returned from this call or the statement itself) returns the number of rows extracted or number of rows affected by the statement execution. When executed on a synchronous statement, this method does not alter the statement's synchronous nature. For transactional behavior, see execute() documentation.

### executeDirect

void executeDirect(
const std::string & query
);

Executes the query synchronously and directly. Even when isAsync() returns true, the statement is still executed synchronously. For transactional behavior, see execute() documentation.

### extractionCount

std::size_t extractionCount() const;

Returns the number of extraction storage buffers associated with the current data set.

### getStorage

const std::string & getStorage() const;

Returns the internal storage type for the statement.

### hasDelete

Optional < bool > hasDelete() const;

Returns true if the statement contains a DELETE statement. For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### hasInsert

Optional < bool > hasInsert() const;

Returns true if the statement contains an INSERT statement. For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### hasMoreDataSets

bool hasMoreDataSets() const;

Returns false if the current data set index points to the last data set. Otherwise, it returns true.

### hasSelect

Optional < bool > hasSelect() const;

Returns true if the statement contains a SELECT statement. For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### hasUpdate

Optional < bool > hasUpdate() const;

Returns true if the statement contains an UPDATE statement. For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### initialized

bool initialized();

Returns true if the statement was initialized (i.e. not executed yet).

### isAsync

bool isAsync() const;

Returns true if statement was marked for asynchronous execution.

### isDelete

Optional < bool > isDelete() const;

Returns true if the statement consists only of DELETE statement(s). For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### isInsert

Optional < bool > isInsert() const;

Returns true if the statement consists only of INSERT statement(s). For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### isSelect

Optional < bool > isSelect() const;

Returns true if the statement consists only of SELECT statement(s). For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### isUpdate

Optional < bool > isUpdate() const;

Returns true if the statement consists only of UPDATE statement(s). For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### nextDataSet

std::size_t nextDataSet();

Returns the index of the next data set.

### operator <<

template < typename T > Statement & operator << (
const T & t
);

Concatenates data with the SQL statement string.

### operator =

Statement & operator = (
const Statement & stmt
);

Assignment operator.

### operator =

Statement & operator = (
Statement && stmt
) noexcept;

Move assignment.

### operator,

Statement & operator, (
Manipulator manip
);

Handles manipulators, such as now, async, etc.

### operator,

Statement & operator, (
AbstractBinding::Ptr pBind
);

Registers the Binding with the Statement by calling addBind().

### operator,

Statement & operator, (
AbstractBindingVec & bindVec
);

Registers the Binding vector with the Statement.

### operator,

Statement & operator, (
AbstractExtraction::Ptr extract
);

Registers objects used for extracting data with the Statement by calling addExtract().

### operator,

Statement & operator, (
AbstractExtractionVec & extVec
);

Registers the extraction vector with the Statement. The vector is registered at position 0 (i.e. for the first returned data set).

### operator,

Statement & operator, (
AbstractExtractionVecVec & extVecVec
);

Registers the vector of extraction vectors with the Statement.

### operator,

Statement & operator, (
const Bulk & bulk
);

Sets the bulk execution mode (both binding and extraction) for this statement.Statement must not have any extractors or binders set at the time when this operator is applied. Failure to adhere to the above constraint shall result in InvalidAccessException.

### operator,

Statement & operator, (
BulkFnType
);

Sets the bulk execution mode (both binding and extraction) for this statement.Statement must not have any extractors or binders set at the time when this operator is applied. Additionally, this function requires limit to be set in order to determine the bulk size. Failure to adhere to the above constraints shall result in InvalidAccessException.

### operator,

Statement & operator, (
const Limit & extrLimit
);

Sets a limit on the maximum number of rows a select is allowed to return.

Set per default to zero to Limit::LIMIT_UNLIMITED, which disables the limit.

### operator,

Statement & operator, (
RowFormatter::Ptr pRowFformatter
);

Sets the row formatter for the statement.

### operator,

Statement & operator, (
const Range & extrRange
);

Sets a an extraction range for the maximum number of rows a select is allowed to return.

Set per default to Limit::LIMIT_UNLIMITED which disables the range.

### operator,

Statement & operator, (
char value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::UInt8 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::Int8 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::UInt16 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::Int16 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::UInt32 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::Int32 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::UInt64 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
Poco::Int64 value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
double value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
float value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
bool value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
const std::string & value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### operator,

Statement & operator, (
const char * value
);

Adds the value to the list of values to be supplied to the SQL string formatting function.

### parse

Optional < bool > parse();

Parses the SQL statement and returns true if successful.

Note that parsing is not guaranteed to succeed, as some backends have proprietary keywords not supported by the parser. Parsing failures are silent in terms of throwing exceptions or logging, but it is possible to get error information by calling parseError().

For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### parseError

const std::string & parseError();

Returns the SQL statement parse error message, if any. For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns an empty string.

### paused

bool paused();

Returns true if the statement was paused (a range limit stopped it and there is more work to do).

### previousDataSet

std::size_t previousDataSet();

Returns the index of the previous data set.

### removeBind

void removeBind(
const std::string & name
);

Removes the all the bindings with specified name from the statement.

### reset

Statement & reset(
Session & session
);

Resets the Statement and assigns it a new session, so that it can be filled with a new SQL query.

### reset

Statement & reset();

Resets the Statement so that it can be filled with a new SQL query.

### rowsExtracted

std::size_t rowsExtracted(
int dataSet = StatementImpl::USE_CURRENT_DATA_SET
) const;

Returns the number of rows returned for current data set during last statement execution. Default value indicates current data set (if any).

### setAsync

void setAsync(
bool async = true
);

Sets the asynchronous flag. If this flag is true, executeAsync() is called from the now() manipulator. This setting does not affect the statement's capability to be executed synchronously by directly calling execute().

### setRowFormatter

void setRowFormatter(
RowFormatter::Ptr pRowFormatter
);

Sets the row formatter for this statement. Statement takes the ownership of the formatter.

### setStorage

void setStorage(
const std::string & storage
);

Sets the internal storage type for the statement.

### state

State state() const;

Returns the statement state.

### statementsCount

Optional < std::size_t > statementsCount() const;

Returns the total number of SQL statements held in the accummulated SQL statement.

For Poco::Data builds with POCO_DATA_NO_SQL_PARSER, it always returns unspecified.

### storage

Storage storage() const;

Returns the internal storage type for the statement.

### subTotalRowCount

std::size_t subTotalRowCount(
int dataSet = StatementImpl::USE_CURRENT_DATA_SET
) const;

Returns the number of rows extracted so far for the data set. Default value indicates current data set (if any).

### swap

void swap(
Statement & other
) noexcept;

Swaps the statement with another one.

### toString

const std::string & toString() const;

Creates a string from the accumulated SQL statement.

### wait

std::size_t wait(
long milliseconds = WAIT_FOREVER
);

Waits for the execution completion for asynchronous statements or returns immediately for synchronous ones. The return value for asynchronous statement is the execution result (i.e. number of rows retrieved). For synchronous statements, the return value is zero.

### clear

void clear() noexcept;

Clears the statement.

### extractions

const AbstractExtractionVec & extractions() const;

Returns the extractions vector.

### getRowFormatter

const RowFormatter::Ptr & getRowFormatter();

Returns the row formatter for this statement.

### impl

ImplPtr impl() const;

Returns pointer to statement implementation.

### isBulkExtraction

bool isBulkExtraction() const;

Returns true if this statement extracts data in bulk.

### isNull

bool isNull(
std::size_t col,
std::size_t row
) const;

Returns true if the current row value at column pos is null.

### metaColumn

const MetaColumn & metaColumn(
std::size_t pos
) const;

Returns the type for the column at specified position.

### metaColumn

const MetaColumn & metaColumn(
const std::string & name
) const;

Returns the type for the column with specified name.

### session

Session session();

Returns the underlying session.

## Variables

### WAIT_FOREVER

static const int WAIT_FOREVER = - 1;