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();
}
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();
}
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;
}
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);
}
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();
}
}
}
Aggregations