Interface QueryExecutor
-
- All Superinterfaces:
TypeTransferModeRegistry
- All Known Implementing Classes:
QueryExecutorBase
,QueryExecutorImpl
public interface QueryExecutor extends TypeTransferModeRegistry
Abstracts the protocol-specific details of executing a query.
Every connection has a single QueryExecutor implementation associated with it. This object provides:
- factory methods for Query objects (
createSimpleQuery(String)
andcreateQuery(String, boolean, boolean, String...)
) - execution methods for created Query objects (
execute(Query, ParameterList, ResultHandler, int, int, int)
for single queries andexecute(Query[], ParameterList[], BatchResultHandler, int, int, int)
for batches of queries) - a fastpath call interface (
createFastpathParameters(int)
andfastpathCall(int, org.postgresql.core.ParameterList, boolean)
).
Query objects may represent a query that has parameter placeholders. To provide actual values for these parameters, a
ParameterList
object is created via a factory method (Query.createParameterList()
). The parameters are filled in by the caller and passed along with the query to the query execution methods. Several ParameterLists for a given query might exist at one time (or over time); this allows the underlying Query to be reused for several executions, or for batch execution of the same Query.In general, a Query created by a particular QueryExecutor may only be executed by that QueryExecutor, and a ParameterList created by a particular Query may only be used as parameters to that Query. Unpredictable things will happen if this isn't done.
- Author:
- Oliver Jowett (oliver@opencloud.com)
-
-
Field Summary
Fields Modifier and Type Field Description static int
MAX_SAVE_POINTS
static int
QUERY_BOTH_ROWS_AND_STATUS
Flag for query execution used by generated keys where we want to receive both the ResultSet and associated update count from the command status.static int
QUERY_DESCRIBE_ONLY
Flag for query execution when we don't really want to execute, we just want to get the parameter metadata for the statement.static int
QUERY_DISALLOW_BATCHING
Deprecated.in PgJDBC 9.4 as we now auto-size batches.static int
QUERY_EXECUTE_AS_SIMPLE
Execute the query via simple 'Q' command (not parse, bind, exec, but simple execute).static int
QUERY_FORCE_DESCRIBE_PORTAL
Force this query to be described at each execution.static int
QUERY_FORWARD_CURSOR
Flag for query execution that indicates a forward-fetch-capable cursor should be used if possible.static int
QUERY_NO_BINARY_TRANSFER
Flag for query execution to avoid using binary transfer.static int
QUERY_NO_METADATA
Flag for query execution that indicates that resultset metadata isn't needed and can be safely omitted.static int
QUERY_NO_RESULTS
Flag for query execution that indicates that a resultset isn't expected and the query executor can safely discard any rows (although the resultset should still appear to be from a resultset-returning query).static int
QUERY_ONESHOT
Flag for query execution that indicates the given Query object is unlikely to be reused.static int
QUERY_READ_ONLY_HINT
Flag indicating that when beginning a transaction, it should be read only.static int
QUERY_SUPPRESS_BEGIN
Flag for query execution that indicates the automatic BEGIN on the first statement when outside a transaction should not be done.
-
Method Summary
All Methods Instance Methods Abstract Methods Deprecated Methods Modifier and Type Method Description void
abort()
Abort at network level without sending the Terminate message to the backend.CachedQuery
borrowCallableQuery(java.lang.String sql)
CachedQuery
borrowQuery(java.lang.String sql)
CachedQuery
borrowQueryByKey(java.lang.Object key)
CachedQuery
borrowReturningQuery(java.lang.String sql, java.lang.String[] columnNames)
void
close()
Close this connection cleanly.ParameterList
createFastpathParameters(int count)
Deprecated.This API is somewhat obsolete, as one may achieve similar performance and greater functionality by setting up a prepared statement to define the function call.CachedQuery
createQuery(java.lang.String sql, boolean escapeProcessing, boolean isParameterized, java.lang.String... columnNames)
CachedQuery
createQueryByKey(java.lang.Object key)
java.lang.Object
createQueryKey(java.lang.String sql, boolean escapeProcessing, boolean isParameterized, java.lang.String... columnNames)
Query
createSimpleQuery(java.lang.String sql)
Create an unparameterized Query object suitable for execution by this QueryExecutor.void
execute(Query[] queries, ParameterList[] parameterLists, BatchResultHandler handler, int maxRows, int fetchSize, int flags)
Execute several Query, passing results to a provided ResultHandler.void
execute(Query query, ParameterList parameters, ResultHandler handler, int maxRows, int fetchSize, int flags)
Execute a Query, passing results to a provided ResultHandler.byte[]
fastpathCall(int fnid, ParameterList params, boolean suppressBegin)
Deprecated.This API is somewhat obsolete, as one may achieve similar performance and greater functionality by setting up a prepared statement to define the function call.void
fetch(ResultCursor cursor, ResultHandler handler, int fetchSize)
Fetch additional rows from a cursor.java.lang.String
getApplicationName()
Returns application_name connection property.AutoSave
getAutoSave()
int
getBackendPID()
Return the process ID (PID) of the backend server process handling this connection.java.lang.String
getDatabase()
Encoding
getEncoding()
EscapeSyntaxCallMode
getEscapeSyntaxCallMode()
HostSpec
getHostSpec()
boolean
getIntegerDateTimes()
Returns true if server uses integer instead of double for binary date and time encodings.int
getNetworkTimeout()
PGNotification[]
getNotifications()
Retrieve and clear the set of asynchronous notifications pending on this connection.java.lang.String
getParameterStatus(java.lang.String parameterName)
java.util.Map<java.lang.String,java.lang.String>
getParameterStatuses()
PreferQueryMode
getPreferQueryMode()
int
getProtocolVersion()
ReplicationProtocol
getReplicationProtocol()
java.lang.String
getServerVersion()
Return the server version from the server_version GUC.int
getServerVersionNum()
Get a machine-readable server version.boolean
getStandardConformingStrings()
Returns whether the server treats string-literals according to the SQL standard or if it uses traditional PostgreSQL escaping rules.java.util.TimeZone
getTimeZone()
Returns backend timezone in java format.TransactionState
getTransactionState()
Get the current transaction state of this connection.java.lang.String
getUser()
java.sql.SQLWarning
getWarnings()
Retrieve and clear the chain of warnings accumulated on this connection.boolean
isClosed()
Check if this connection is closed.boolean
isColumnSanitiserDisabled()
boolean
isReWriteBatchedInsertsEnabled()
void
processNotifies()
Prior to attempting to retrieve notifications, we need to pull any recently received notifications off of the network buffers.void
processNotifies(int timeoutMillis)
Prior to attempting to retrieve notifications, we need to pull any recently received notifications off of the network buffers.void
releaseQuery(CachedQuery cachedQuery)
void
sendQueryCancel()
Sends a query cancellation for this connection.void
setAutoSave(AutoSave autoSave)
void
setBinaryReceiveOids(java.util.Set<java.lang.Integer> useBinaryForOids)
Sets the oids that should be received using binary encoding.void
setBinarySendOids(java.util.Set<java.lang.Integer> useBinaryForOids)
Sets the oids that should be sent using binary encoding.void
setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate)
By default, the connection resets statement cache in case deallocate all/discard all message is observed.void
setNetworkTimeout(int milliseconds)
CopyOperation
startCopy(java.lang.String sql, boolean suppressBegin)
Issues a COPY FROM STDIN / COPY TO STDOUT statement and returns handler for associated operation.boolean
willHealOnRetry(java.sql.SQLException e)
Query
wrap(java.util.List<NativeQuery> queries)
Wrap given native query into a ready for execution format.-
Methods inherited from interface org.postgresql.core.v3.TypeTransferModeRegistry
useBinaryForReceive, useBinaryForSend
-
-
-
-
Field Detail
-
QUERY_ONESHOT
static final int QUERY_ONESHOT
Flag for query execution that indicates the given Query object is unlikely to be reused.- See Also:
- Constant Field Values
-
QUERY_NO_METADATA
static final int QUERY_NO_METADATA
Flag for query execution that indicates that resultset metadata isn't needed and can be safely omitted.- See Also:
- Constant Field Values
-
QUERY_NO_RESULTS
static final int QUERY_NO_RESULTS
Flag for query execution that indicates that a resultset isn't expected and the query executor can safely discard any rows (although the resultset should still appear to be from a resultset-returning query).- See Also:
- Constant Field Values
-
QUERY_FORWARD_CURSOR
static final int QUERY_FORWARD_CURSOR
Flag for query execution that indicates a forward-fetch-capable cursor should be used if possible.- See Also:
- Constant Field Values
-
QUERY_SUPPRESS_BEGIN
static final int QUERY_SUPPRESS_BEGIN
Flag for query execution that indicates the automatic BEGIN on the first statement when outside a transaction should not be done.- See Also:
- Constant Field Values
-
QUERY_DESCRIBE_ONLY
static final int QUERY_DESCRIBE_ONLY
Flag for query execution when we don't really want to execute, we just want to get the parameter metadata for the statement.- See Also:
- Constant Field Values
-
QUERY_BOTH_ROWS_AND_STATUS
static final int QUERY_BOTH_ROWS_AND_STATUS
Flag for query execution used by generated keys where we want to receive both the ResultSet and associated update count from the command status.- See Also:
- Constant Field Values
-
QUERY_FORCE_DESCRIBE_PORTAL
static final int QUERY_FORCE_DESCRIBE_PORTAL
Force this query to be described at each execution. This is done in pipelined batches where we might need to detect mismatched result types.- See Also:
- Constant Field Values
-
QUERY_DISALLOW_BATCHING
@Deprecated static final int QUERY_DISALLOW_BATCHING
Deprecated.in PgJDBC 9.4 as we now auto-size batches.Flag to disable batch execution when we expect results (generated keys) from a statement.- See Also:
- Constant Field Values
-
QUERY_NO_BINARY_TRANSFER
static final int QUERY_NO_BINARY_TRANSFER
Flag for query execution to avoid using binary transfer.- See Also:
- Constant Field Values
-
QUERY_EXECUTE_AS_SIMPLE
static final int QUERY_EXECUTE_AS_SIMPLE
Execute the query via simple 'Q' command (not parse, bind, exec, but simple execute). This sends query text on each execution, however it supports sending multiple queries separated with ';' as a single command.- See Also:
- Constant Field Values
-
MAX_SAVE_POINTS
static final int MAX_SAVE_POINTS
- See Also:
- Constant Field Values
-
QUERY_READ_ONLY_HINT
static final int QUERY_READ_ONLY_HINT
Flag indicating that when beginning a transaction, it should be read only.- See Also:
- Constant Field Values
-
-
Method Detail
-
execute
void execute(Query query, ParameterList parameters, ResultHandler handler, int maxRows, int fetchSize, int flags) throws java.sql.SQLException
Execute a Query, passing results to a provided ResultHandler.- Parameters:
query
- the query to execute; must be a query returned from callingwrap(List)
on this QueryExecutor object.parameters
- the parameters for the query. Must be non-null
if the query takes parameters. Must be a parameter object returned byQuery.createParameterList()
.handler
- a ResultHandler responsible for handling results generated by this querymaxRows
- the maximum number of rows to retrievefetchSize
- if QUERY_FORWARD_CURSOR is set, the preferred number of rows to retrieve before suspendingflags
- a combination of QUERY_* flags indicating how to handle the query.- Throws:
java.sql.SQLException
- if query execution fails
-
execute
void execute(Query[] queries, ParameterList[] parameterLists, BatchResultHandler handler, int maxRows, int fetchSize, int flags) throws java.sql.SQLException
Execute several Query, passing results to a provided ResultHandler.- Parameters:
queries
- the queries to execute; each must be a query returned from callingwrap(List)
on this QueryExecutor object.parameterLists
- the parameter lists for the queries. The parameter lists correspond 1:1 to the queries passed in thequeries
array. Each must be non-null
if the corresponding query takes parameters, and must be a parameter object returned byQuery.createParameterList()
created by the corresponding query.handler
- a ResultHandler responsible for handling results generated by this querymaxRows
- the maximum number of rows to retrievefetchSize
- if QUERY_FORWARD_CURSOR is set, the preferred number of rows to retrieve before suspendingflags
- a combination of QUERY_* flags indicating how to handle the query.- Throws:
java.sql.SQLException
- if query execution fails
-
fetch
void fetch(ResultCursor cursor, ResultHandler handler, int fetchSize) throws java.sql.SQLException
Fetch additional rows from a cursor.- Parameters:
cursor
- the cursor to fetch fromhandler
- the handler to feed results tofetchSize
- the preferred number of rows to retrieve before suspending- Throws:
java.sql.SQLException
- if query execution fails
-
createSimpleQuery
Query createSimpleQuery(java.lang.String sql) throws java.sql.SQLException
Create an unparameterized Query object suitable for execution by this QueryExecutor. The provided query string is not parsed for parameter placeholders ('?' characters), and theQuery.createParameterList()
of the returned object will always return an empty ParameterList.- Parameters:
sql
- the SQL for the query to create- Returns:
- a new Query object
- Throws:
java.sql.SQLException
- if something goes wrong
-
isReWriteBatchedInsertsEnabled
boolean isReWriteBatchedInsertsEnabled()
-
createQuery
CachedQuery createQuery(java.lang.String sql, boolean escapeProcessing, boolean isParameterized, java.lang.String... columnNames) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
createQueryKey
java.lang.Object createQueryKey(java.lang.String sql, boolean escapeProcessing, boolean isParameterized, java.lang.String... columnNames)
-
createQueryByKey
CachedQuery createQueryByKey(java.lang.Object key) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
borrowQueryByKey
CachedQuery borrowQueryByKey(java.lang.Object key) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
borrowQuery
CachedQuery borrowQuery(java.lang.String sql) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
borrowCallableQuery
CachedQuery borrowCallableQuery(java.lang.String sql) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
borrowReturningQuery
CachedQuery borrowReturningQuery(java.lang.String sql, java.lang.String[] columnNames) throws java.sql.SQLException
- Throws:
java.sql.SQLException
-
releaseQuery
void releaseQuery(CachedQuery cachedQuery)
-
wrap
Query wrap(java.util.List<NativeQuery> queries)
Wrap given native query into a ready for execution format.- Parameters:
queries
- list of queries in native to database syntax- Returns:
- query object ready for execution by this query executor
-
processNotifies
void processNotifies() throws java.sql.SQLException
Prior to attempting to retrieve notifications, we need to pull any recently received notifications off of the network buffers. The notification retrieval in ProtocolConnection cannot do this as it is prone to deadlock, so the higher level caller must be responsible which requires exposing this method.- Throws:
java.sql.SQLException
- if and error occurs while fetching notifications
-
processNotifies
void processNotifies(int timeoutMillis) throws java.sql.SQLException
Prior to attempting to retrieve notifications, we need to pull any recently received notifications off of the network buffers. The notification retrieval in ProtocolConnection cannot do this as it is prone to deadlock, so the higher level caller must be responsible which requires exposing this method. This variant supports blocking for the given time in millis.- Parameters:
timeoutMillis
- number of milliseconds to block for- Throws:
java.sql.SQLException
- if and error occurs while fetching notifications
-
createFastpathParameters
@Deprecated ParameterList createFastpathParameters(int count)
Deprecated.This API is somewhat obsolete, as one may achieve similar performance and greater functionality by setting up a prepared statement to define the function call. Then, executing the statement with binary transmission of parameters and results substitutes for a fast-path function call.Create a new ParameterList implementation suitable for invoking a fastpath function viafastpathCall(int, org.postgresql.core.ParameterList, boolean)
.- Parameters:
count
- the number of parameters the fastpath call will take- Returns:
- a ParameterList suitable for passing to
fastpathCall(int, org.postgresql.core.ParameterList, boolean)
.
-
fastpathCall
@Deprecated byte[] fastpathCall(int fnid, ParameterList params, boolean suppressBegin) throws java.sql.SQLException
Deprecated.This API is somewhat obsolete, as one may achieve similar performance and greater functionality by setting up a prepared statement to define the function call. Then, executing the statement with binary transmission of parameters and results substitutes for a fast-path function call.Invoke a backend function via the fastpath interface.- Parameters:
fnid
- the OID of the backend function to invokeparams
- a ParameterList returned fromcreateFastpathParameters(int)
containing the parameters to pass to the backend functionsuppressBegin
- if begin should be suppressed- Returns:
- the binary-format result of the fastpath call, or
null
if a void result was returned - Throws:
java.sql.SQLException
- if an error occurs while executing the fastpath call
-
startCopy
CopyOperation startCopy(java.lang.String sql, boolean suppressBegin) throws java.sql.SQLException
Issues a COPY FROM STDIN / COPY TO STDOUT statement and returns handler for associated operation. Until the copy operation completes, no other database operation may be performed. Implemented for protocol version 3 only.- Parameters:
sql
- input sqlsuppressBegin
- if begin should be suppressed- Returns:
- handler for associated operation
- Throws:
java.sql.SQLException
- when initializing the given query fails
-
getProtocolVersion
int getProtocolVersion()
- Returns:
- the version of the implementation
-
setBinaryReceiveOids
void setBinaryReceiveOids(java.util.Set<java.lang.Integer> useBinaryForOids)
Sets the oids that should be received using binary encoding.- Parameters:
useBinaryForOids
- The oids to request with binary encoding.
-
setBinarySendOids
void setBinarySendOids(java.util.Set<java.lang.Integer> useBinaryForOids)
Sets the oids that should be sent using binary encoding.- Parameters:
useBinaryForOids
- The oids to send with binary encoding.
-
getIntegerDateTimes
boolean getIntegerDateTimes()
Returns true if server uses integer instead of double for binary date and time encodings.- Returns:
- the server integer_datetime setting.
-
getHostSpec
HostSpec getHostSpec()
- Returns:
- the host and port this connection is connected to.
-
getUser
java.lang.String getUser()
- Returns:
- the user this connection authenticated as.
-
getDatabase
java.lang.String getDatabase()
- Returns:
- the database this connection is connected to.
-
sendQueryCancel
void sendQueryCancel() throws java.sql.SQLException
Sends a query cancellation for this connection.- Throws:
java.sql.SQLException
- if something goes wrong.
-
getBackendPID
int getBackendPID()
Return the process ID (PID) of the backend server process handling this connection.- Returns:
- process ID (PID) of the backend server process handling this connection
-
abort
void abort()
Abort at network level without sending the Terminate message to the backend.
-
close
void close()
Close this connection cleanly.
-
isClosed
boolean isClosed()
Check if this connection is closed.- Returns:
- true iff the connection is closed.
-
getServerVersion
java.lang.String getServerVersion()
Return the server version from the server_version GUC.
Note that there's no requirement for this to be numeric or of the form x.y.z. PostgreSQL development releases usually have the format x.ydevel e.g. 9.4devel; betas usually x.ybetan e.g. 9.4beta1. The --with-extra-version configure option may add an arbitrary string to this.
Don't use this string for logic, only use it when displaying the server version to the user. Prefer getServerVersionNum() for all logic purposes.
- Returns:
- the server version string from the server_version guc
-
getNotifications
PGNotification[] getNotifications() throws java.sql.SQLException
Retrieve and clear the set of asynchronous notifications pending on this connection.- Returns:
- an array of notifications; if there are no notifications, an empty array is returned.
- Throws:
java.sql.SQLException
- if and error occurs while fetching notifications
-
getWarnings
java.sql.SQLWarning getWarnings()
Retrieve and clear the chain of warnings accumulated on this connection.- Returns:
- the first SQLWarning in the chain; subsequent warnings can be found via SQLWarning.getNextWarning().
-
getServerVersionNum
int getServerVersionNum()
Get a machine-readable server version.
This returns the value of the server_version_num GUC. If no such GUC exists, it falls back on attempting to parse the text server version for the major version. If there's no minor version (e.g. a devel or beta release) then the minor version is set to zero. If the version could not be parsed, zero is returned.
- Returns:
- the server version in numeric XXYYZZ form, eg 090401, from server_version_num
-
getTransactionState
TransactionState getTransactionState()
Get the current transaction state of this connection.- Returns:
- a ProtocolConnection.TRANSACTION_* constant.
-
getStandardConformingStrings
boolean getStandardConformingStrings()
Returns whether the server treats string-literals according to the SQL standard or if it uses traditional PostgreSQL escaping rules. Versions up to 8.1 always treated backslashes as escape characters in string-literals. Since 8.2, this depends on the value of thestandard_conforming_strings
server variable.- Returns:
- true if the server treats string literals according to the SQL standard
-
getTimeZone
java.util.TimeZone getTimeZone()
Returns backend timezone in java format.- Returns:
- backend timezone in java format.
-
getEncoding
Encoding getEncoding()
- Returns:
- the current encoding in use by this connection
-
getApplicationName
java.lang.String getApplicationName()
Returns application_name connection property.- Returns:
- application_name connection property
-
isColumnSanitiserDisabled
boolean isColumnSanitiserDisabled()
-
getEscapeSyntaxCallMode
EscapeSyntaxCallMode getEscapeSyntaxCallMode()
-
getPreferQueryMode
PreferQueryMode getPreferQueryMode()
-
getAutoSave
AutoSave getAutoSave()
-
setAutoSave
void setAutoSave(AutoSave autoSave)
-
willHealOnRetry
boolean willHealOnRetry(java.sql.SQLException e)
-
setFlushCacheOnDeallocate
void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate)
By default, the connection resets statement cache in case deallocate all/discard all message is observed. This API allows to disable that feature for testing purposes.- Parameters:
flushCacheOnDeallocate
- true if statement cache should be reset when "deallocate/discard" message observed
-
getReplicationProtocol
ReplicationProtocol getReplicationProtocol()
- Returns:
- the ReplicationProtocol instance for this connection.
-
setNetworkTimeout
void setNetworkTimeout(int milliseconds) throws java.io.IOException
- Throws:
java.io.IOException
-
getNetworkTimeout
int getNetworkTimeout() throws java.io.IOException
- Throws:
java.io.IOException
-
getParameterStatuses
java.util.Map<java.lang.String,java.lang.String> getParameterStatuses()
-
getParameterStatus
java.lang.String getParameterStatus(java.lang.String parameterName)
-
-