All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.firebirdsql.jdbc.FBStatement Maven / Gradle / Ivy

There is a newer version: 4.0.10.java8
Show newest version
/*
 * Firebird Open Source JavaEE Connector - JDBC Driver
 *
 * Distributable under LGPL license.
 * You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * LGPL License for more details.
 *
 * This file was created by members of the firebird development team.
 * All individual contributions remain the Copyright (C) of those
 * individuals.  Contributors to this file are either listed here or
 * can be obtained from a source control history command.
 *
 * All rights reserved.
 */
package org.firebirdsql.jdbc;

import org.firebirdsql.gds.DatabaseParameterBuffer;
import org.firebirdsql.gds.JaybirdErrorCodes;
import org.firebirdsql.gds.impl.DatabaseParameterBufferExtension;
import org.firebirdsql.gds.impl.GDSHelper;
import org.firebirdsql.gds.ng.*;
import org.firebirdsql.gds.ng.fields.RowValue;
import org.firebirdsql.gds.ng.listeners.StatementListener;
import org.firebirdsql.jdbc.escape.FBEscapedParser;
import org.firebirdsql.jdbc.escape.FBEscapedParser.EscapeParserMode;
import org.firebirdsql.logging.LoggerFactory;

import java.sql.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

import static org.firebirdsql.util.FirebirdSupportInfo.supportInfoFor;

/**
 * The object used for executing a static SQL statement and obtaining the results produced by it.
 * 

* Only one ResultSet object per Statement object * can be open at any point in * time. Therefore, if the reading of one ResultSet object is interleaved * with the reading of another, each must have been generated by * different Statement objects. All statement execute * methods implicitly close a statement's current ResultSet object * if an open one exists. *

* * @see Connection#createStatement * @see ResultSet * * @author David Jencks * @author Mark Rotteveel */ public class FBStatement implements FirebirdStatement, Synchronizable { private static final org.firebirdsql.logging.Logger log = LoggerFactory.getLogger(FBStatement.class); protected static final JdbcVersionSupport jdbcVersionSupport = JdbcVersionSupportHolder.INSTANCE.getJdbcVersionSupport(); private static final AtomicInteger STATEMENT_ID_GENERATOR = new AtomicInteger(); private final int localStatementId = STATEMENT_ID_GENERATOR.incrementAndGet(); protected final GDSHelper gdsHelper; private final Object syncObject; protected final FBObjectListener.StatementListener statementListener; protected FbStatement fbStatement; //The normally retrieved result set. (no autocommit, not a cached rs). private FBResultSet currentRs; private SqlCountHolder sqlCountHolder; private boolean closed; protected boolean completed = true; private boolean escapedProcessing = true; private volatile boolean closeOnCompletion; private boolean currentStatementGeneratedKeys; protected SQLWarning firstWarning; protected StatementResult currentStatementResult = StatementResult.NO_MORE_RESULTS; // Singleton result indicates it is a stored procedure or [INSERT | UPDATE | DELETE] ... RETURNING ... protected boolean isSingletonResult; // Used for singleton or batch results for getGeneratedKeys, and singleton results of stored procedures protected final List specialResult = new LinkedList<>(); protected int maxRows; protected int fetchSize; private int maxFieldSize; private int queryTimeout; private String cursorName; private final int rsConcurrency; private final int rsType; private final int rsHoldability; private int fetchDirection = ResultSet.FETCH_FORWARD; private final FBObjectListener.ResultSetListener resultSetListener = new RSListener(); protected final FBConnection connection; /** * Listener for the result sets. */ private class RSListener implements FBObjectListener.ResultSetListener { /** * Notify that result set was closed. This method cleans the result * set reference, so that call to {@link #close()} method will not cause * exception. * * @param rs result set that was closed. */ @Override public void resultSetClosed(ResultSet rs) throws SQLException { currentRs = null; // notify listener that statement is completed. notifyStatementCompleted(); if (closeOnCompletion) { close(); } } @Override public void allRowsFetched(ResultSet rs) throws SQLException { /* * According to the JDBC 3.0 specification (p.62) the result set * is closed in the autocommit mode if one of the following occurs: * * - all of the rows have been retrieved * - the associated Statement object is re-executed * - another Statement object is executed on the same connection */ // according to the specification we close the result set and // generate the "resultSetClosed" event, that in turn generates // the "statementCompleted" event if (connection != null && connection.getAutoCommit()) rs.close(); } @Override public void executionCompleted(FirebirdRowUpdater updater, boolean success) throws SQLException { notifyStatementCompleted(success); } @Override public void executionStarted(FirebirdRowUpdater updater) throws SQLException { notifyStatementStarted(false); } } protected FBStatement(GDSHelper c, int rsType, int rsConcurrency, int rsHoldability, FBObjectListener.StatementListener statementListener) throws SQLException { this.gdsHelper = c; syncObject = c.getSynchronizationObject(); this.rsConcurrency = rsConcurrency; this.rsType = rsType; this.rsHoldability = rsHoldability; this.statementListener = statementListener; // TODO Find out if connection is actually ever null, because some parts of the code expect it not to be null this.connection = statementListener != null ? statementListener.getConnection() : null; closed = false; } String getCursorName() { return cursorName; } private static Set INVALID_STATEMENT_STATES = EnumSet.of( StatementState.ERROR, StatementState.CLOSING, StatementState.CLOSED); public boolean isValid() { return !closed && !INVALID_STATEMENT_STATES.contains(fbStatement.getState()); } public final Object getSynchronizationObject() { return syncObject; } @Override protected void finalize() throws Throwable { try { if (!closed) close(); } finally { super.finalize(); } } public void completeStatement() throws SQLException { completeStatement(CompletionReason.OTHER); } public void completeStatement(CompletionReason reason) throws SQLException { if (currentRs != null && (reason != CompletionReason.COMMIT || currentRs.getHoldability() == ResultSet.CLOSE_CURSORS_AT_COMMIT)) { closeResultSet(false, reason); } if (!completed) notifyStatementCompleted(); } /** * Executes an SQL statement that returns a single ResultSet object. * * @param sql typically this is a static SQL SELECT statement * @return a ResultSet object that contains the data produced by the * given query; never null * @exception SQLException if a database access error occurs */ public ResultSet executeQuery(String sql) throws SQLException { checkValidity(); currentStatementGeneratedKeys = false; synchronized(getSynchronizationObject()) { notifyStatementStarted(); if (!internalExecute(sql)) { throw new FBSQLException("Query did not return a result set.", SQLStateConstants.SQL_STATE_NO_RESULT_SET); } return getResultSet(); } } protected void notifyStatementStarted() throws SQLException { notifyStatementStarted(true); } protected void notifyStatementStarted(boolean closeResultSet) throws SQLException { if (closeResultSet) closeResultSet(false); // notify listener that statement execution is about to start statementListener.executionStarted(this); if (fbStatement != null) { fbStatement.setTransaction(gdsHelper.getCurrentTransaction()); } completed = false; } protected void notifyStatementCompleted() throws SQLException { notifyStatementCompleted(true); } protected void notifyStatementCompleted(boolean success) throws SQLException { completed = true; statementListener.statementCompleted(this, success); } /** * Executes an SQL INSERT, UPDATE or * DELETE statement. In addition, * SQL statements that return nothing, such as SQL DDL statements, * can be executed. * * @param sql an SQL INSERT, UPDATE or * DELETE statement or an SQL statement that returns nothing * @return either the row count for INSERT, UPDATE * or DELETE statements, or 0 for SQL statements that return nothing * @exception SQLException if a database access error occurs */ public int executeUpdate(String sql) throws SQLException { checkValidity(); currentStatementGeneratedKeys = false; synchronized (getSynchronizationObject()) { notifyStatementStarted(); try { if (internalExecute(sql)) { throw new FBSQLException( "Update statement returned results."); } return getUpdateCount(); } finally { notifyStatementCompleted(); } } } /** * Executes the given SQL statement and signals the driver with the * given flag about whether the * auto-generated keys produced by this Statement object * should be made available for retrieval. The driver will ignore the * flag if the SQL statement * is not an INSERT statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or * DELETE; or an SQL statement that returns nothing, * such as a DDL statement. * * @param autoGeneratedKeys a flag indicating whether auto-generated keys * should be made available for retrieval; * one of the following constants: * Statement.RETURN_GENERATED_KEYS * Statement.NO_GENERATED_KEYS * @return either (1) the row count for SQL Data Manipulation Language (DML) statements * or (2) 0 for SQL statements that return nothing * * @exception SQLException if a database access error occurs, * this method is called on a closed Statement, the given * SQL statement returns a ResultSet object, or * the given constant is not one of those allowed * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method with a constant of Statement.RETURN_GENERATED_KEYS * @since 1.4 */ public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { execute(sql, autoGeneratedKeys); return getUpdateCount(); } /** * Executes the given SQL statement and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. This array contains the indexes of the columns in the * target table that contain the auto-generated keys that should be made * available. The driver will ignore the array if the SQL statement * is not an INSERT statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or * DELETE; or an SQL statement that returns nothing, * such as a DDL statement. * * @param columnIndexes an array of column indexes indicating the columns * that should be returned from the inserted row * @return either (1) the row count for SQL Data Manipulation Language (DML) statements * or (2) 0 for SQL statements that return nothing * * @exception SQLException if a database access error occurs, * this method is called on a closed Statement, the SQL * statement returns a ResultSet object, or the * second argument supplied to this method is not an int array * whose elements are valid column indexes * @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method * @since 1.4 */ public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { execute(sql, columnIndexes); return getUpdateCount(); } /** * Executes the given SQL statement and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. This array contains the names of the columns in the * target table that contain the auto-generated keys that should be made * available. The driver will ignore the array if the SQL statement * is not an INSERT statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). * * @param sql an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or * DELETE; or an SQL statement that returns nothing, * such as a DDL statement. * @param columnNames an array of the names of the columns that should be * returned from the inserted row * @return either the row count for INSERT, UPDATE, * or DELETE statements, or 0 for SQL statements * that return nothing * @exception SQLException if a database access error occurs, * this method is called on a closed Statement, the SQL * statement returns a ResultSet object, or the * second argument supplied to this method is not a String array * whose elements are valid column names * * @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method * @since 1.4 */ public int executeUpdate(String sql, String[] columnNames) throws SQLException { execute(sql, columnNames); return getUpdateCount(); } /** * Executes the given SQL statement, which may return multiple results, * and signals the driver that any * auto-generated keys should be made available * for retrieval. The driver will ignore this signal if the SQL statement * is not an INSERT statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). *

* In some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. *

* The execute method executes an SQL statement and indicates the * form of the first result. You must then use the methods * getResultSet or getUpdateCount * to retrieve the result, and getMoreResults to * move to any subsequent result(s). * * @param sql any SQL statement * @param autoGeneratedKeys a constant indicating whether auto-generated * keys should be made available for retrieval using the method * getGeneratedKeys; one of the following constants: * Statement.RETURN_GENERATED_KEYS or * Statement.NO_GENERATED_KEYS * @return true if the first result is a ResultSet * object; false if it is an update count or there are * no results * @exception SQLException if a database access error occurs, * this method is called on a closed Statement or the second * parameter supplied to this method is not * Statement.RETURN_GENERATED_KEYS or * Statement.NO_GENERATED_KEYS. * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method with a constant of Statement.RETURN_GENERATED_KEYS * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * * @since 1.4 */ public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { checkValidity(); if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) { connection.checkAutoGeneratedKeysSupport(); } AbstractGeneratedKeysQuery query = connection.new GeneratedKeysQuery(sql, autoGeneratedKeys); return executeImpl(query); } /** * Executes the given SQL statement, which may return multiple results, * and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. This array contains the indexes of the columns in the * target table that contain the auto-generated keys that should be made * available. The driver will ignore the array if the SQL statement * is not an INSERT statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). *

* Under some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. *

* The execute method executes an SQL statement and indicates the * form of the first result. You must then use the methods * getResultSet or getUpdateCount * to retrieve the result, and getMoreResults to * move to any subsequent result(s). * * @param sql any SQL statement * @param columnIndexes an array of the indexes of the columns in the * inserted row that should be made available for retrieval by a * call to the method getGeneratedKeys * @return true if the first result is a ResultSet * object; false if it is an update count or there * are no results * @exception SQLException if a database access error occurs, * this method is called on a closed Statement or the * elements in the int array passed to this method * are not valid column indexes * @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * * @since 1.4 */ public boolean execute(String sql, int[] columnIndexes) throws SQLException { checkValidity(); connection.checkAutoGeneratedKeysSupport(); AbstractGeneratedKeysQuery query = connection.new GeneratedKeysQuery(sql, columnIndexes); return executeImpl(query); } /** * Executes the given SQL statement, which may return multiple results, * and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. This array contains the names of the columns in the * target table that contain the auto-generated keys that should be made * available. The driver will ignore the array if the SQL statement * is not an INSERT statement, or an SQL statement able to return * auto-generated keys (the list of such statements is vendor-specific). *

* In some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. *

* The execute method executes an SQL statement and indicates the * form of the first result. You must then use the methods * getResultSet or getUpdateCount * to retrieve the result, and getMoreResults to * move to any subsequent result(s). * * @param sql any SQL statement * @param columnNames an array of the names of the columns in the inserted * row that should be made available for retrieval by a call to the * method getGeneratedKeys * @return true if the next result is a ResultSet * object; false if it is an update count or there * are no more results * @exception SQLException if a database access error occurs, * this method is called on a closed Statement or the * elements of the String array passed to this * method are not valid column names * @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * * @since 1.4 */ public boolean execute(String sql, String[] columnNames) throws SQLException { checkValidity(); connection.checkAutoGeneratedKeysSupport(); AbstractGeneratedKeysQuery query = connection.new GeneratedKeysQuery(sql, columnNames); return executeImpl(query); } /** * Retrieves any auto-generated keys created as a result of executing this * Statement object. If this Statement object did * not generate any keys, an empty ResultSet * object is returned. * *

Note:If the columns which represent the auto-generated keys were not specified, * the JDBC driver implementation will determine the columns which best represent the auto-generated keys. * * @return a ResultSet object containing the auto-generated key(s) * generated by the execution of this Statement object * @exception SQLException if a database access error occurs or * this method is called on a closed Statement * @throws SQLFeatureNotSupportedException if the JDBC driver does not support this method * @since 1.4 */ public ResultSet getGeneratedKeys() throws SQLException { checkValidity(); if (isGeneratedKeyQuery() && isSingletonResult) { return new FBResultSet(fbStatement.getFieldDescriptor(), new ArrayList<>(specialResult), resultSetListener); } return new FBResultSet(fbStatement.emptyRowDescriptor(), Collections.emptyList()); } /** * Releases this Statement object's database * and JDBC resources immediately instead of waiting for * this to happen when it is automatically closed. * It is generally good practice to release resources as soon as * you are finished with them to avoid tying up database * resources. *

* Calling the method close on a Statement * object that is already closed has no effect. *

Note: A Statement object is automatically closed when it is * garbage collected. When a Statement object is closed, its current * ResultSet object, if one exists, is also closed. * * @exception SQLException if a database access error occurs */ public void close() throws SQLException { close(true); } void close(boolean ignoreAlreadyClosed) throws SQLException { if (isClosed()) { if (ignoreAlreadyClosed) return; throw new FBSQLException("This statement is already closed."); } synchronized(getSynchronizationObject()) { if (fbStatement != null) { try { try { closeResultSet(false); } finally { //may need ensureTransaction? fbStatement.close(); } } finally { fbStatement = null; } } } closed = true; statementListener.statementClosed(this); } /** * Check if this statement was closed. This is quick workaround to avoid * additional {@link #close()} in our cleanup code. * * @return true if this statement was already closed. */ public boolean isClosed() { return closed; } /** * Returns the maximum number of bytes allowed * for any column value. * This limit is the maximum number of bytes that can be * returned for any column value. * The limit applies only to BINARY, * VARBINARY, LONGVARBINARY, CHAR, VARCHAR, and LONGVARCHAR * columns. If the limit is exceeded, the excess data is silently * discarded. * * @return the current max column size limit; zero means unlimited * @exception SQLException if a database access error occurs */ public int getMaxFieldSize() throws SQLException { return maxFieldSize; } /** * Sets the limit for the maximum number of bytes in a column to * the given number of bytes. This is the maximum number of bytes * that can be returned for any column value. This limit applies * only to BINARY, VARBINARY, * LONGVARBINARY, CHAR, VARCHAR, and * LONGVARCHAR fields. If the limit is exceeded, the excess data * is silently discarded. For maximum portability, use values * greater than 256. * * @param max the new max column size limit; zero means unlimited * @exception SQLException if a database access error occurs */ public void setMaxFieldSize(int max) throws SQLException { if (max < 0) throw new FBSQLException("Can't set max field size negative", SQLStateConstants.SQL_STATE_INVALID_ARG_VALUE); else maxFieldSize = max; } /** * Retrieves the maximum number of rows that a * ResultSet object can contain. If the limit is exceeded, the excess * rows are silently dropped. * * @return the current max row limit; zero means unlimited * @exception SQLException if a database access error occurs */ public int getMaxRows() throws SQLException { return maxRows; } /** * Sets the limit for the maximum number of rows that any * ResultSet object can contain to the given number. * If the limit is exceeded, the excess * rows are silently dropped. * * @param max the new max rows limit; zero means unlimited * @exception SQLException if a database access error occurs */ public void setMaxRows(int max) throws SQLException { if (max < 0) throw new FBSQLException("Max rows can't be less than 0", SQLStateConstants.SQL_STATE_INVALID_ARG_VALUE); else maxRows = max; } /** * Sets escape processing on or off. * If escape scanning is on (the default), the driver will do * escape substitution before sending the SQL to the database. * * Note: Since prepared statements have usually been parsed prior * to making this call, disabling escape processing for prepared * statements will have no effect. * * @param enable true to enable; false to disable * @exception SQLException if a database access error occurs */ public void setEscapeProcessing(boolean enable) throws SQLException { escapedProcessing = enable; } /** * Retrieves the number of seconds the driver will * wait for a Statement object to execute. If the limit is exceeded, a * SQLException is thrown. * * @return the current query timeout limit in seconds; zero means unlimited * @exception SQLException if a database access error occurs */ public int getQueryTimeout() throws SQLException { return queryTimeout; } /** * Sets the number of seconds the driver will * wait for a Statement object to execute to the given number of seconds. * If the limit is exceeded, an SQLException is thrown. * * @param seconds the new query timeout limit in seconds; zero means * unlimited * @exception SQLException if a database access error occurs */ public void setQueryTimeout(int seconds) throws SQLException { if (seconds < 0) { throw new FBSQLException("Can't set query timeout negative", SQLStateConstants.SQL_STATE_INVALID_ARG_VALUE); } queryTimeout = seconds; } public void cancel() throws SQLException { checkValidity(); if (!supportInfoFor(connection).supportsCancelOperation()) { throw new SQLFeatureNotSupportedException("Cancel not supported"); } // TODO This may be problematic, as it could also cancel something other than this statement gdsHelper.cancelOperation(); } /** * Retrieves the first warning reported by calls on this Statement object. * Subsequent Statement object warnings will be chained to this * SQLWarning object. * *

The warning chain is automatically cleared each time * a statement is (re)executed. * *

Note: If you are processing a ResultSet object, any * warnings associated with reads on that ResultSet object * will be chained on it. * * @return the first SQLWarning object or null * @exception SQLException if a database access error occurs */ public SQLWarning getWarnings() throws SQLException { return firstWarning; } /** * Clears all the warnings reported on this Statement * object. After a call to this method, * the method getWarnings will return * null until a new warning is reported for this * Statement object. * * @exception SQLException if a database access error occurs */ public void clearWarnings() throws SQLException { firstWarning = null; } /** * Defines the SQL cursor name that will be used by * subsequent Statement object execute methods. * This name can then be * used in SQL positioned update/delete statements to identify the * current row in the ResultSet object generated by this statement. If * the database doesn't support positioned update/delete, this * method is a noop. To insure that a cursor has the proper isolation * level to support updates, the cursor's SELECT statement should be * of the form 'select for update ...'. If the 'for update' phrase is * omitted, positioned updates may fail. * *

Note: By definition, positioned update/delete * execution must be done by a different Statement object than the one * which generated the ResultSet object being used for positioning. Also, * cursor names must be unique within a connection. * * @param name the new cursor name, which must be unique within * a connection * @exception SQLException if a database access error occurs */ public void setCursorName(String name) throws SQLException { this.cursorName = name; } boolean isUpdatableCursor() { return cursorName != null; } //----------------------- Multiple Results -------------------------- /** * Executes an SQL statement that may return multiple results. * Under some (uncommon) situations a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore * this unless you are (1) executing a stored procedure that you know may * return multiple results or (2) you are dynamically executing an * unknown SQL string. The methods execute, * getMoreResults, getResultSet, * and getUpdateCount let you navigate through multiple results. * * The execute method executes an SQL statement and indicates the * form of the first result. You can then use the methods * getResultSet or getUpdateCount * to retrieve the result, and getMoreResults to * move to any subsequent result(s). * * @param sql any SQL statement * @return true if the next result is a ResultSet object; * false if it is an update count or there are no more results * @exception SQLException if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults */ public boolean execute(String sql) throws SQLException { checkValidity(); currentStatementGeneratedKeys = false; return executeImpl(sql); } /** * Internal implementation of {@link #execute(String)}, so it can be used for normal queries * and for queries returning generated keys. * * @see #execute(String) */ protected boolean executeImpl(String sql) throws SQLException { synchronized (getSynchronizationObject()) { notifyStatementStarted(); boolean hasResultSet = false; try { hasResultSet = internalExecute(sql); } finally { if (!hasResultSet) { notifyStatementCompleted(); } } return hasResultSet; } } private boolean executeImpl(AbstractGeneratedKeysQuery query) throws SQLException { currentStatementGeneratedKeys = query.generatesKeys(); return executeImpl(query.getQueryString()); } /** * Returns the current result as a ResultSet object. * This method should be called only once per result. * Calling this method twice with autocommit on and used will probably * throw an inappropriate or uninformative exception. * * @return the current result as a ResultSet object; * null if the result is an update count or there are no more results * @exception SQLException if a database access error occurs * @see #execute */ public ResultSet getResultSet() throws SQLException { checkValidity(); return getResultSet(false); } public ResultSet getResultSet(boolean metaDataQuery) throws SQLException { if (fbStatement == null) { throw new FBSQLException("No statement was executed."); } if (cursorName != null) { fbStatement.setCursorName(cursorName); } if (currentRs != null) { throw new FBSQLException("Only one result set at a time/statement."); } // A generated keys query does not produce a normal result set (but EXECUTE PROCEDURE or INSERT ... RETURNING without Statement.RETURN_GENERATED_KEYS do) // TODO Behavior might not be correct for callable statement implementation if (!isGeneratedKeyQuery() && currentStatementResult == StatementResult.RESULT_SET) { if (!isSingletonResult) { currentRs = new FBResultSet(connection, this, fbStatement, resultSetListener, metaDataQuery, rsType, rsConcurrency, rsHoldability, false); } else if (!specialResult.isEmpty()) { currentRs = new FBResultSet(fbStatement.getFieldDescriptor(), new ArrayList<>(specialResult), resultSetListener); } return currentRs; } return null; } public boolean hasOpenResultSet() { return currentRs != null; } /** * Returns the current result as an update count; * if the result is a ResultSet object or there are no more results, -1 * is returned. This method should be called only once per result. * * @return the current result as an update count; -1 if the current result is a * ResultSet object or there are no more results * @exception SQLException if a database access error occurs * @see #execute */ public int getUpdateCount() throws SQLException { checkValidity(); if (currentStatementResult != StatementResult.UPDATE_COUNT) { return -1; } populateSqlCounts(); int insCount = sqlCountHolder.getIntegerInsertCount(); int updCount = sqlCountHolder.getIntegerUpdateCount(); int delCount = sqlCountHolder.getIntegerDeleteCount(); return Math.max(Math.max(updCount, delCount), insCount); } private void populateSqlCounts() throws SQLException { if (sqlCountHolder == null) { sqlCountHolder = fbStatement.getSqlCounts(); } } private static final int INSERTED_ROWS_COUNT = 1; private static final int UPDATED_ROWS_COUNT = 2; private static final int DELETED_ROWS_COUNT = 3; private int getChangedRowsCount(int type) throws SQLException { if (currentStatementResult != StatementResult.UPDATE_COUNT) { return -1; } populateSqlCounts(); switch (type) { case INSERTED_ROWS_COUNT: return sqlCountHolder.getIntegerInsertCount(); case UPDATED_ROWS_COUNT: return sqlCountHolder.getIntegerUpdateCount(); case DELETED_ROWS_COUNT: return sqlCountHolder.getIntegerDeleteCount(); default: throw new IllegalArgumentException(String.format("Specified type %d is unknown.", type)); } } public int getDeletedRowsCount() throws SQLException { return getChangedRowsCount(DELETED_ROWS_COUNT); } public int getInsertedRowsCount() throws SQLException { return getChangedRowsCount(INSERTED_ROWS_COUNT); } public int getUpdatedRowsCount() throws SQLException { return getChangedRowsCount(UPDATED_ROWS_COUNT); } /** * Moves to a Statement object's next result. It returns * true if this result is a ResultSet object. * This method also implicitly closes any current ResultSet * object obtained with the method getResultSet. * *

There are no more results when the following is true: *

     *      (!getMoreResults() && (getUpdateCount() == -1)
     * 
* * @return true if the next result is a ResultSet object; * false if it is an update count or there are no more results * @exception SQLException if a database access error occurs * @see #execute */ public boolean getMoreResults() throws SQLException { return getMoreResults(Statement.CLOSE_ALL_RESULTS); } public boolean getMoreResults(int mode) throws SQLException { checkValidity(); boolean closeResultSet = mode == Statement.CLOSE_ALL_RESULTS || mode == Statement.CLOSE_CURRENT_RESULT; if (currentStatementResult == StatementResult.RESULT_SET && closeResultSet) { closeResultSet(true); } currentStatementResult = currentStatementResult.nextResult(); // Technically the statement below is always false, as only the first result is ever a ResultSet return currentStatementResult == StatementResult.RESULT_SET; } @Override public void setFetchDirection(int direction) throws SQLException { checkValidity(); switch (direction) { case ResultSet.FETCH_FORWARD: case ResultSet.FETCH_REVERSE: case ResultSet.FETCH_UNKNOWN: fetchDirection = direction; break; default: throw FbExceptionBuilder.forException(JaybirdErrorCodes.jb_invalidFetchDirection) .messageParameter(direction) .toFlatSQLException(); } } @Override public int getFetchDirection() throws SQLException { checkValidity(); return fetchDirection; } /** * Gives the JDBC driver a hint as to the number of rows that should * be fetched from the database when more rows are needed for * ResultSet objects genrated by this Statement. * If the value specified is zero, then the hint is ignored. * The default value is zero. * * @param rows the number of rows to fetch * @exception SQLException if a database access error occurs, * this method is called on a closed Statement or the * condition rows >= 0 is not satisfied. * @since 1.2 * @see #getFetchSize */ public void setFetchSize(int rows) throws SQLException { checkValidity(); if (rows < 0) throw new FBSQLException("Can't set negative fetch size", SQLStateConstants.SQL_STATE_INVALID_ARG_VALUE); else fetchSize = rows; } /** * Retrieves the number of result set rows that is the default * fetch size for ResultSet objects * generated from this Statement object. * If this Statement object has not set * a fetch size by calling the method setFetchSize, * the return value is implementation-specific. * * @return the default fetch size for result sets generated * from this Statement object * @exception SQLException if a database access error occurs or * this method is called on a closed Statement * @since 1.2 * @see #setFetchSize */ public int getFetchSize() throws SQLException { checkValidity(); return fetchSize; } /** * Retrieves the result set concurrency for ResultSet objects * generated by this Statement object. * * @return either ResultSet.CONCUR_READ_ONLY or * ResultSet.CONCUR_UPDATABLE * @since 1.2 * @see What Is in the JDBC * 2.0 API */ public int getResultSetConcurrency() throws SQLException { return rsConcurrency; } /** * Retrieves the result set type for ResultSet objects * generated by this Statement object. * * @return one of ResultSet.TYPE_FORWARD_ONLY, * ResultSet.TYPE_SCROLL_INSENSITIVE, or * ResultSet.TYPE_SCROLL_SENSITIVE * @since 1.2 * @see What Is in the JDBC * 2.0 API */ public int getResultSetType() throws SQLException { return rsType; } public int getResultSetHoldability() throws SQLException { return rsHoldability; } private List batchList = new ArrayList<>(); /** * Adds an SQL command to the current batch of commmands for this * Statement object. This method is optional. * * @param sql typically this is a static SQL INSERT or * UPDATE statement * @exception SQLException if a database access error occurs, or the * driver does not support batch statements * @since 1.2 * @see What Is in the JDBC * 2.0 API */ public void addBatch( String sql ) throws SQLException { batchList.add(sql); } /** * Makes the set of commands in the current batch empty. * This method is optional. * * @exception SQLException if a database access error occurs or the * driver does not support batch statements * @since 1.2 * @see What Is in the JDBC * 2.0 API */ public void clearBatch() throws SQLException { batchList.clear(); } /** * Submits a batch of commands to the database for execution and * if all commands execute successfully, returns an array of update counts. * The int elements of the array that is returned are ordered * to correspond to the commands in the batch, which are ordered * according to the order in which they were added to the batch. * The elements in the array returned by the method executeBatch * may be one of the following: *
    *
  1. A number greater than or equal to zero -- indicates that the * command was processed successfully and is an update count giving the * number of rows in the database that were affected by the command's * execution *
  2. A value of -2 -- indicates that the command was * processed successfully but that the number of rows affected is * unknown *

    * If one of the commands in a batch update fails to execute properly, * this method throws a BatchUpdateException, and a JDBC * driver may or may not continue to process the remaining commands in * the batch. However, the driver's behavior must be consistent with a * particular DBMS, either always continuing to process commands or never * continuing to process commands. If the driver continues processing * after a failure, the array returned by the method * BatchUpdateException.getUpdateCounts * will contain as many elements as there are commands in the batch, and * at least one of the elements will be the following: *

    *

  3. A value of -3 -- indicates that the command failed * to execute successfully and occurs only if a driver continues to * process commands after a command fails *
*

* A driver is not required to implement this method. * The possible implementations and return values have been modified in * the Java 2 SDK, Standard Edition, version 1.3 to * accommodate the option of continuing to proccess commands in a batch * update after a BatchUpdateException obejct has been thrown. * * @return an array of update counts containing one element for each * command in the batch. The elements of the array are ordered according * to the order in which commands were added to the batch. * @exception SQLException if a database access error occurs or the * driver does not support batch statements. Throws {@link java.sql.BatchUpdateException} * (a subclass of SQLException) if one of the commands sent to the * database fails to execute properly or attempts to return a result set. * @since 1.3 * @see What Is in the JDBC * 2.0 API */ public final int[] executeBatch() throws SQLException { if (connection.getAutoCommit()) { addWarning(new SQLWarning("Batch updates should be run with auto-commit disabled.", "01000")); } return toArray(executeBatchInternal()); } protected List executeBatchInternal() throws SQLException { checkValidity(); currentStatementGeneratedKeys = false; notifyStatementStarted(); synchronized (getSynchronizationObject()) { boolean success = false; try { List responses = new ArrayList<>(batchList.size()); try { for (String sql : batchList) { executeSingleForBatch(responses, sql); } success = true; return responses; } catch (SQLException e) { throw jdbcVersionSupport.createBatchUpdateException(e.getMessage(), e.getSQLState(), e.getErrorCode(), toLargeArray(responses), e); } finally { clearBatch(); } } finally { notifyStatementCompleted(success); } } } private void executeSingleForBatch(List responses, String sql) throws SQLException { if (internalExecute(sql)) { // TODO SQL state? throw jdbcVersionSupport.createBatchUpdateException( "Statements executed as batch should not produce a result set", SQLStateConstants.SQL_STATE_GENERAL_ERROR, 0, toLargeArray(responses), null); } else { responses.add(getLargeUpdateCount()); } } /** * Convert collection of {@link Long} update counts into array of int. * * @param updateCounts * collection of integer elements. * * @return array of int. */ protected int[] toArray(Collection updateCounts) { int[] result = new int[updateCounts.size()]; int counter = 0; for (long value : updateCounts) { result[counter++] = (int) value; } return result; } /** * Convert collection of {@link Integer} update counts into array of int. * * @param updateCounts * collection of integer elements. * * @return array of int. */ protected long[] toLargeArray(Collection updateCounts) { long[] result = new long[updateCounts.size()]; int counter = 0; for (long value : updateCounts) { result[counter++] = value; } return result; } /** * Returns the Connection object that produced this * Statement object. * * @return the connection that produced this statement */ public Connection getConnection() throws SQLException { checkValidity(); return connection; } //package level void closeResultSet(boolean notifyListener) throws SQLException { closeResultSet(notifyListener, CompletionReason.OTHER); } void closeResultSet(boolean notifyListener, CompletionReason completionReason) throws SQLException { boolean wasCompleted = completed; try { if (currentRs != null) { try { currentRs.close(notifyListener, completionReason); } finally { currentRs = null; } } else if (fbStatement != null) { fbStatement.ensureClosedCursor(completionReason.isTransactionEnd()); } } finally { if (notifyListener && !wasCompleted) statementListener.statementCompleted(this); } } public void forgetResultSet() { //yuck should be package // TODO Use case unclear, find out if this needs to be added to fbStatement somehow currentRs = null; } public ResultSet getCurrentResultSet() throws SQLException { return currentRs; } public boolean isPoolable() throws SQLException { checkValidity(); return false; } public void setPoolable(boolean poolable) throws SQLException { checkValidity(); // ignore the hint } public boolean isWrapperFor(Class iface) throws SQLException { return iface != null && iface.isAssignableFrom(getClass()); } public T unwrap(Class iface) throws SQLException { if (!isWrapperFor(iface)) throw new SQLException("Unable to unwrap to class " + iface.getName()); return iface.cast(this); } // JDBC 4.1 public void closeOnCompletion() { closeOnCompletion = true; } public boolean isCloseOnCompletion() { return closeOnCompletion; } /** * This method checks if supplied statement is executing procedure or * it is generic statement. This check is needed to handle correctly * parameters that are returned from non-selectable procedures. * * @param sql SQL statement to check * * @return true if supplied statement is EXECUTE PROCEDURE * type of statement. * * @throws SQLException if translating statement into native code failed. */ protected boolean isExecuteProcedureStatement(String sql) throws SQLException { final String trimmedSql = nativeSQL(sql).trim(); return trimmedSql.startsWith("EXECUTE"); } protected boolean internalExecute(String sql) throws SQLException { checkValidity(); prepareFixedStatement(sql); fbStatement.execute(RowValue.EMPTY_ROW_VALUE); return currentStatementResult == StatementResult.RESULT_SET; } protected void prepareFixedStatement(String sql) throws SQLException { // TODO: Statement should be created and allocated at FBStatement creation only. if (fbStatement == null) { fbStatement = gdsHelper.allocateStatement(); fbStatement.addStatementListener(createStatementListener()); } else { fbStatement.setTransaction(gdsHelper.getCurrentTransaction()); } fbStatement.prepare(escapedProcessing ? nativeSQL(sql) : sql); } protected void addWarning(SQLWarning warning) { if (firstWarning == null) { firstWarning = warning; } else { firstWarning.setNextWarning(warning); } } protected String nativeSQL(String sql) throws SQLException { if (connection != null) { return connection.nativeSQL(sql); } else { DatabaseParameterBuffer dpb = gdsHelper.getDatabaseParameterBuffer(); EscapeParserMode mode = dpb.hasArgument(DatabaseParameterBufferExtension.USE_STANDARD_UDF) ? EscapeParserMode.USE_STANDARD_UDF : EscapeParserMode.USE_BUILT_IN; return new FBEscapedParser(mode).parse(sql); } } /** * @return true when the current statement is expected to return generated keys, false otherwise. */ protected boolean isGeneratedKeyQuery() { return currentStatementGeneratedKeys; } /** * Get the execution plan of this PreparedStatement * * @return The execution plan of the statement */ String getExecutionPlan() throws SQLException { return fbStatement.getExecutionPlan(); } public String getLastExecutionPlan() throws SQLException { checkValidity(); if (fbStatement == null) { throw new FBSQLException("No statement was executed, plan cannot be obtained."); } return getExecutionPlan(); } /** * Get the statement type of this PreparedStatement. * The returned value will be one of the TYPE_* constant * values. * * @return The identifier for the given statement's type */ int getStatementType() throws SQLException { if (fbStatement == null) { return StatementType.NONE.getStatementTypeCode(); } return fbStatement.getType().getStatementTypeCode(); } /** * Check if this statement is valid. This method should be invoked before * executing any action which requires a valid connection. * * @throws SQLException if this Statement has been closed and cannot be used anymore. */ protected void checkValidity() throws SQLException { if (isClosed()) { throw new FBSQLException("Statement is already closed.", SQLStateConstants.SQL_STATE_INVALID_STATEMENT_ID); } } public long getLargeUpdateCount() throws SQLException { checkValidity(); if (currentStatementResult != StatementResult.UPDATE_COUNT) { return -1; } populateSqlCounts(); final long insCount = sqlCountHolder.getLongInsertCount(); final long updCount = sqlCountHolder.getLongUpdateCount(); final long delCount = sqlCountHolder.getLongDeleteCount(); return Math.max(Math.max(insCount, updCount), delCount); } /** * {@inheritDoc} *

* Jaybird does not support maxRows exceeding {@link Integer#MAX_VALUE}, if a larger value is set, Jaybird will * add a warning to the statement and reset the maximum to 0. *

*/ public void setLargeMaxRows(long max) throws SQLException { if (max > Integer.MAX_VALUE) { addWarning(new SQLWarning( String.format("Implementation limit: maxRows cannot exceed Integer.MAX_VALUE, value was %d, reset to 0", max), SQLStateConstants.SQL_STATE_INVALID_ARG_VALUE)); max = 0; } setMaxRows((int) max); } /** * {@inheritDoc} *

* Jaybird does not support maxRows exceeding {@link Integer#MAX_VALUE}, the return value of this method is the * same as {@link #getMaxRows()}. *

*/ public long getLargeMaxRows() throws SQLException { return getMaxRows(); } public final long[] executeLargeBatch() throws SQLException { if (connection.getAutoCommit()) { addWarning(new SQLWarning("Batch updates should be run with auto-commit disabled.", "01000")); } return toLargeArray(executeBatchInternal()); } public final long executeLargeUpdate(String sql) throws SQLException { executeUpdate(sql); return getLargeUpdateCount(); } public final long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException { executeUpdate(sql, autoGeneratedKeys); return getLargeUpdateCount(); } public final long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException { executeUpdate(sql, columnIndexes); return getLargeUpdateCount(); } public final long executeLargeUpdate(String sql, String[] columnNames) throws SQLException { executeUpdate(sql, columnNames); return getLargeUpdateCount(); } /** * Returns a {@code String} enclosed in single quotes. Any occurrence of a single quote within the string will be * replaced by two single quotes. *

* For a dialect 3 database, this will behave exactly like the JDBC 4.3 default implementation. For a * dialect 1 database this will quote literals with double quotes and escape double quotes by doubling. *

* * @param val a character string * @return A string enclosed by single quotes with every single quote * converted to two single quotes * @throws NullPointerException if val is {@code null} * @throws SQLException if a database access error occurs */ public String enquoteLiteral(String val) throws SQLException { if (gdsHelper.getCurrentDatabase().getDatabaseDialect() == 1) { return '"' + val.replace("\"", "\"\"") + '"'; } return "'" + val.replace("'", "''") + "'"; } /** * @see #enquoteLiteral(String) */ public String enquoteNCharLiteral(String val) throws SQLException { return enquoteLiteral(val); } private static final Pattern SIMPLE_IDENTIFIER_PATTERN = Pattern.compile("[\\p{Alpha}][\\p{Alnum}_$]*"); /** * Returns a SQL identifier. If {@code identifier} is a simple SQL identifier: *
    *
  • Return the original value if {@code alwaysQuote} is * {@code false}
  • *
  • Return a delimited identifier if {@code alwaysQuote} is * {@code true}
  • *
* * @param identifier a SQL identifier * @param alwaysQuote indicates if a simple SQL identifier should be * returned as a quoted identifier * @return A simple SQL identifier or a delimited identifier * @throws SQLException if identifier is not a valid identifier * @throws SQLFeatureNotSupportedException if the datasource does not support * delimited identifiers (ie: a dialect 1 database) * @throws NullPointerException if identifier is {@code null} */ public String enquoteIdentifier(String identifier, boolean alwaysQuote) throws SQLException { int len = identifier.length(); if (len < 1 || len > getConnection().getMetaData().getMaxColumnNameLength()) { throw new SQLException("Invalid name"); } if (!alwaysQuote && SIMPLE_IDENTIFIER_PATTERN.matcher(identifier).matches()) { return identifier; } if (gdsHelper.getCurrentDatabase().getDatabaseDialect() == 1) { throw new SQLFeatureNotSupportedException("Quoted identifiers not supported in dialect 1"); } if (identifier.matches("^\".+\"$")) { // We assume double quotes are already properly escaped within return identifier; } return "\"" + identifier.replace("\"", "\"\"") + "\""; } /** * Retrieves whether {@code identifier} is a simple SQL identifier. * * @param identifier a SQL identifier * @return true if a simple SQL identifier, false otherwise * @throws NullPointerException if identifier is {@code null} * @throws SQLException if a database access error occurs */ public boolean isSimpleIdentifier(String identifier) throws SQLException { int len = identifier.length(); return len >= 1 && len <= getConnection().getMetaData().getMaxColumnNameLength() && SIMPLE_IDENTIFIER_PATTERN.matcher(identifier).matches(); } @Override public final int getLocalStatementId() { return localStatementId; } @Override public final int hashCode() { return localStatementId; } @Override public final boolean equals(Object other) { if (!(other instanceof FirebirdStatement)) { return false; } FirebirdStatement otherStmt = (FirebirdStatement) other; return this.localStatementId == otherStmt.getLocalStatementId(); } /** * The current result of a statement. */ protected enum StatementResult { RESULT_SET { @Override public StatementResult nextResult() { return UPDATE_COUNT; } }, UPDATE_COUNT { @Override public StatementResult nextResult() { return NO_MORE_RESULTS; } }, NO_MORE_RESULTS { @Override public StatementResult nextResult() { return NO_MORE_RESULTS; } }; /** * @return Next result */ public abstract StatementResult nextResult(); } /** * Creates the {@link org.firebirdsql.gds.ng.listeners.StatementListener} to be associated with the instance of * {@link org.firebirdsql.gds.ng.FbStatement} created for this {@link FBStatement} or subclasses. * * @return instance of {@link org.firebirdsql.gds.ng.listeners.StatementListener} */ protected StatementListener createStatementListener() { return new FBStatementListener(); } private final class FBStatementListener implements StatementListener { @Override public void receivedRow(FbStatement sender, RowValue rowValue) { if (!isValidSender(sender)) return; // TODO May need extra condition to distinguish between singleton result of EXECUTE PROCEDURE and INSERT ... RETURNING ... if (isSingletonResult) { specialResult.clear(); specialResult.add(rowValue); } } @Override public void allRowsFetched(FbStatement sender) { if (!isValidSender(sender)) return; // TODO Evaluate if we need to do any processing } @Override public void statementExecuted(FbStatement sender, boolean hasResultSet, boolean hasSingletonResult) { if (!isValidSender(sender)) return; // TODO If true create ResultSet and attach listener to sender currentStatementResult = hasResultSet || hasSingletonResult && !isGeneratedKeyQuery() ? StatementResult.RESULT_SET : StatementResult.UPDATE_COUNT; isSingletonResult = hasSingletonResult; } @Override public void statementStateChanged(FbStatement sender, StatementState newState, StatementState previousState) { if (!isValidSender(sender)) return; switch (newState) { case PREPARED: // TODO Evaluate correct changes when state goes to prepared break; case EXECUTING: specialResult.clear(); sqlCountHolder = null; currentStatementResult = StatementResult.NO_MORE_RESULTS; isSingletonResult = false; try { clearWarnings(); } catch (SQLException e) { // Ignoring exception (can't happen in current implementation) throw new AssertionError("Unexpected SQLException"); } break; } } @Override public void warningReceived(FbStatement sender, SQLWarning warning) { if (!isValidSender(sender)) return; addWarning(warning); } @Override public void sqlCounts(FbStatement sender, SqlCountHolder sqlCounts) { if (!isValidSender(sender)) return; sqlCountHolder = sqlCounts; } private boolean isValidSender(FbStatement sender) { if (sender != fbStatement) { log.debug(String.format("Received statement listener update from unrelated statement [%s]", sender.toString())); sender.removeStatementListener(this); return false; } return true; } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy