Search in sources :

Example 1 with PreparedStatement

use of org.apache.derby.iapi.sql.PreparedStatement in project derby by apache.

the class AlterTableConstantAction method getColumnMax.

/**
 * computes the minimum/maximum value in a column of a table.
 */
private long getColumnMax(TableDescriptor td, String columnName, long increment) throws StandardException {
    String maxStr = (increment > 0) ? "MAX" : "MIN";
    String maxStmt = "SELECT  " + maxStr + "(" + IdUtil.normalToDelimited(columnName) + ") FROM " + IdUtil.mkQualifiedName(td.getSchemaName(), td.getName());
    PreparedStatement ps = lcc.prepareInternalStatement(maxStmt);
    // This is a substatement, for now we do not set any timeout for it
    // We might change this later by linking timeout to parent statement
    ResultSet rs = ps.executeSubStatement(lcc, false, 0L);
    DataValueDescriptor[] rowArray = rs.getNextRow().getRowArray();
    rs.close();
    rs.finish();
    return rowArray[0].getLong();
}
Also used : ResultSet(org.apache.derby.iapi.sql.ResultSet) PreparedStatement(org.apache.derby.iapi.sql.PreparedStatement) DataValueDescriptor(org.apache.derby.iapi.types.DataValueDescriptor)

Example 2 with PreparedStatement

use of org.apache.derby.iapi.sql.PreparedStatement in project derby by apache.

the class AlterTableConstantAction method executeUpdate.

private static void executeUpdate(LanguageConnectionContext lcc, String updateStmt) throws StandardException {
    PreparedStatement ps = lcc.prepareInternalStatement(updateStmt);
    // This is a substatement; for now, we do not set any timeout
    // for it. We might change this behaviour later, by linking
    // timeout to its parent statement's timeout settings.
    ResultSet rs = ps.executeSubStatement(lcc, true, 0L);
    rs.close();
}
Also used : ResultSet(org.apache.derby.iapi.sql.ResultSet) PreparedStatement(org.apache.derby.iapi.sql.PreparedStatement)

Example 3 with PreparedStatement

use of org.apache.derby.iapi.sql.PreparedStatement in project derby by apache.

the class ConstraintConstantAction method validateConstraint.

/**
 * Evaluate a check constraint or not null column constraint.
 * Generate a query of the
 * form SELECT COUNT(*) FROM t where NOT(<check constraint>)
 * and run it by compiling and executing it.   Will
 * work ok if the table is empty and query returns null.
 *
 * @param constraintName	constraint name
 * @param constraintText	constraint text
 * @param constraintId      constraint id
 * @param td				referenced table
 * @param lcc				the language connection context
 * @param isCheckConstraint	the constraint is a check constraint
 * @param isInitiallyDeferred {@code true} if the constraint is
 *                          initially deferred
 *
 * @return true if null constraint passes, false otherwise
 *
 * @exception StandardException if check constraint fails
 */
static boolean validateConstraint(String constraintName, String constraintText, UUID constraintId, TableDescriptor td, LanguageConnectionContext lcc, boolean isCheckConstraint, boolean isInitiallyDeferred) throws StandardException {
    StringBuilder checkStmt = new StringBuilder();
    /* should not use select sum(not(<check-predicate>) ? 1: 0) because
		 * that would generate much more complicated code and may exceed Java
		 * limits if we have a large number of check constraints, beetle 4347
		 */
    checkStmt.append("SELECT COUNT(*) FROM ");
    checkStmt.append(td.getQualifiedName());
    checkStmt.append(" WHERE NOT(");
    checkStmt.append(constraintText);
    checkStmt.append(")");
    ResultSet rs = null;
    try {
        PreparedStatement ps = lcc.prepareInternalStatement(checkStmt.toString());
        // This is a substatement; for now, we do not set any timeout
        // for it. We might change this behaviour later, by linking
        // timeout to its parent statement's timeout settings.
        rs = ps.executeSubStatement(lcc, false, 0L);
        ExecRow row = rs.getNextRow();
        if (SanityManager.DEBUG) {
            if (row == null) {
                SanityManager.THROWASSERT("did not get any rows back from query: " + checkStmt.toString());
            }
        }
        Number value = ((Number) ((NumberDataValue) row.getRowArray()[0]).getObject());
        /*
			** Value may be null if there are no rows in the
			** table.
			*/
        if ((value != null) && (value.longValue() != 0)) {
            // check constraint is violated.
            if (isCheckConstraint) {
                if (isInitiallyDeferred) {
                    // Remember the violation
                    List<UUID> violatingConstraints = new ArrayList<UUID>();
                    violatingConstraints.add(constraintId);
                    // FIXME: We don't know the row locations of the
                    // violating rows, so for now, just pretend we know one,
                    // then invalidate the row location information forcing
                    // full table check at validation time
                    CheckInfo[] newCi = new CheckInfo[1];
                    DeferredConstraintsMemory.rememberCheckViolations(lcc, td.getObjectID(), td.getSchemaName(), td.getName(), null, violatingConstraints, new HeapRowLocation(), /* dummy */
                    newCi);
                    newCi[0].setInvalidatedRowLocations();
                } else {
                    throw StandardException.newException(SQLState.LANG_ADD_CHECK_CONSTRAINT_FAILED, constraintName, td.getQualifiedName(), value.toString());
                }
            }
            /*
				 * for not null constraint violations exception will be thrown in caller
				 * check constraint will not get here since exception is thrown
				 * above
				 */
            return false;
        }
    } finally {
        if (rs != null) {
            rs.close();
        }
    }
    return true;
}
Also used : HeapRowLocation(org.apache.derby.impl.store.access.heap.HeapRowLocation) ResultSet(org.apache.derby.iapi.sql.ResultSet) ExecRow(org.apache.derby.iapi.sql.execute.ExecRow) ArrayList(java.util.ArrayList) CheckInfo(org.apache.derby.impl.sql.execute.DeferredConstraintsMemory.CheckInfo) PreparedStatement(org.apache.derby.iapi.sql.PreparedStatement) UUID(org.apache.derby.catalog.UUID) NumberDataValue(org.apache.derby.iapi.types.NumberDataValue)

Example 4 with PreparedStatement

use of org.apache.derby.iapi.sql.PreparedStatement in project derby by apache.

the class RealResultSetStatisticsFactory method getRunTimeStatistics.

// 
// ExecutionFactory interface
// 
// 
// ResultSetStatisticsFactory interface
// 
/**
 *		@see ResultSetStatisticsFactory#getRunTimeStatistics
 */
public RunTimeStatistics getRunTimeStatistics(Activation activation, ResultSet rs, NoPutResultSet[] subqueryTrackingArray) throws StandardException {
    PreparedStatement preStmt = activation.getPreparedStatement();
    // In this case statistics should not be generated.
    if (preStmt == null)
        return null;
    ResultSetStatistics topResultSetStatistics;
    if (rs instanceof NoPutResultSet) {
        topResultSetStatistics = getResultSetStatistics((NoPutResultSet) rs);
    } else {
        topResultSetStatistics = getResultSetStatistics(rs);
    }
    /* Build up the info on the materialized subqueries */
    int subqueryTrackingArrayLength = (subqueryTrackingArray == null) ? 0 : subqueryTrackingArray.length;
    ResultSetStatistics[] subqueryRSS = new ResultSetStatistics[subqueryTrackingArrayLength];
    boolean anyAttached = false;
    for (int index = 0; index < subqueryTrackingArrayLength; index++) {
        if (subqueryTrackingArray[index] != null && subqueryTrackingArray[index].getPointOfAttachment() == -1) {
            subqueryRSS[index] = getResultSetStatistics(subqueryTrackingArray[index]);
            anyAttached = true;
        }
    }
    if (anyAttached == false) {
        subqueryRSS = null;
    }
    // Get the info on all of the materialized subqueries (attachment point = -1)
    return new RunTimeStatisticsImpl(preStmt.getSPSName(), activation.getCursorName(), preStmt.getSource(), preStmt.getCompileTimeInMillis(), preStmt.getParseTimeInMillis(), preStmt.getBindTimeInMillis(), preStmt.getOptimizeTimeInMillis(), preStmt.getGenerateTimeInMillis(), rs.getExecuteTime(), preStmt.getBeginCompileTimestamp(), preStmt.getEndCompileTimestamp(), rs.getBeginExecutionTimestamp(), rs.getEndExecutionTimestamp(), subqueryRSS, topResultSetStatistics);
}
Also used : ResultSetStatistics(org.apache.derby.iapi.sql.execute.ResultSetStatistics) RealUpdateResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealUpdateResultSetStatistics) RealDeleteResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealDeleteResultSetStatistics) RealDeleteVTIResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealDeleteVTIResultSetStatistics) RealAnyResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealAnyResultSetStatistics) RealScrollInsensitiveResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealScrollInsensitiveResultSetStatistics) RealRowResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealRowResultSetStatistics) RealMaterializedResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealMaterializedResultSetStatistics) RealNormalizeResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealNormalizeResultSetStatistics) RealUnionResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealUnionResultSetStatistics) RealOnceResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealOnceResultSetStatistics) RealInsertResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealInsertResultSetStatistics) RealJoinResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealJoinResultSetStatistics) RealWindowResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealWindowResultSetStatistics) RealSetOpResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealSetOpResultSetStatistics) RealInsertVTIResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealInsertVTIResultSetStatistics) RealDeleteCascadeResultSetStatistics(org.apache.derby.impl.sql.execute.rts.RealDeleteCascadeResultSetStatistics) NoPutResultSet(org.apache.derby.iapi.sql.execute.NoPutResultSet) PreparedStatement(org.apache.derby.iapi.sql.PreparedStatement) RunTimeStatisticsImpl(org.apache.derby.impl.sql.execute.rts.RunTimeStatisticsImpl)

Example 5 with PreparedStatement

use of org.apache.derby.iapi.sql.PreparedStatement in project derby by apache.

the class EmbedStatement method execute.

/**
 * Execute a 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're executing a stored procedure that you know may
 * return multiple results, or unless you're dynamically executing an
 * unknown SQL string.  The "execute", "getMoreResults", "getResultSet"
 * and "getUpdateCount" methods let you navigate through multiple results.
 *
 * The "execute" method executes a SQL statement and indicates the
 * form of the first result.  You can then use getResultSet or
 * getUpdateCount to retrieve the result, and getMoreResults to
 * move to any subsequent result(s).
 *
 * @param sql					any SQL statement
 * @param executeQuery			caller is executeQuery()
 * @param executeUpdate			caller is executeUpdate()
 * @param autoGeneratedKeys
 * @param columnIndexes
 * @param columnNames
 *
 * @return true if the first result is a ResultSet; false if it is an integer
 * @see #getResultSet
 * @see #getUpdateCount
 * @see #getMoreResults
 * @exception SQLException thrown on failure
 */
private boolean execute(String sql, boolean executeQuery, boolean executeUpdate, int autoGeneratedKeys, int[] columnIndexes, String[] columnNames) throws SQLException {
    synchronized (getConnectionSynchronization()) {
        checkExecStatus();
        if (sql == null) {
            throw newSQLException(SQLState.NULL_SQL_TEXT);
        }
        checkIfInMiddleOfBatch();
        // release the last statement executed, if any.
        clearResultSets();
        // make sure there's context
        setupContextStack();
        // try to remember the SQL statement in case anybody asks for it
        SQLText = sql;
        try {
            Activation activation;
            try {
                PreparedStatement preparedStatement = lcc.prepareInternalStatement(lcc.getDefaultSchema(), sql, resultSetConcurrency == java.sql.ResultSet.CONCUR_READ_ONLY, false);
                activation = preparedStatement.getActivation(lcc, resultSetType == java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE);
                checkRequiresCallableStatement(activation);
                InterruptStatus.restoreIntrFlagIfSeen(lcc);
            } catch (Throwable t) {
                throw handleException(t);
            }
            // this is for a Statement execution
            activation.setSingleExecution();
            // information in lcc will not work work it can be tampered by a nested trasaction
            if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) {
                activation.setAutoGeneratedKeysResultsetInfo(columnIndexes, columnNames);
            }
            return executeStatement(activation, executeQuery, executeUpdate);
        } finally {
            restoreContextStack();
        }
    }
}
Also used : Activation(org.apache.derby.iapi.sql.Activation) PreparedStatement(org.apache.derby.iapi.sql.PreparedStatement)

Aggregations

PreparedStatement (org.apache.derby.iapi.sql.PreparedStatement)6 ResultSet (org.apache.derby.iapi.sql.ResultSet)4 ArrayList (java.util.ArrayList)1 UUID (org.apache.derby.catalog.UUID)1 Activation (org.apache.derby.iapi.sql.Activation)1 ExecRow (org.apache.derby.iapi.sql.execute.ExecRow)1 NoPutResultSet (org.apache.derby.iapi.sql.execute.NoPutResultSet)1 ResultSetStatistics (org.apache.derby.iapi.sql.execute.ResultSetStatistics)1 DataValueDescriptor (org.apache.derby.iapi.types.DataValueDescriptor)1 NumberDataValue (org.apache.derby.iapi.types.NumberDataValue)1 CheckInfo (org.apache.derby.impl.sql.execute.DeferredConstraintsMemory.CheckInfo)1 RealAnyResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealAnyResultSetStatistics)1 RealDeleteCascadeResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealDeleteCascadeResultSetStatistics)1 RealDeleteResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealDeleteResultSetStatistics)1 RealDeleteVTIResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealDeleteVTIResultSetStatistics)1 RealInsertResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealInsertResultSetStatistics)1 RealInsertVTIResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealInsertVTIResultSetStatistics)1 RealJoinResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealJoinResultSetStatistics)1 RealMaterializedResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealMaterializedResultSetStatistics)1 RealNormalizeResultSetStatistics (org.apache.derby.impl.sql.execute.rts.RealNormalizeResultSetStatistics)1