Search in sources :

Example 1 with ResultDescription

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

the class EmbedResultSet method updateRow.

/**
 * JDBC 2.0
 *
 * Update the underlying database with the new contents of the
 * current row.  Cannot be called when on the insert row.
 *
 * @exception SQLException if a database-access error occurs, or
 * if called when on the insert row
 */
public void updateRow() throws SQLException {
    synchronized (getConnectionSynchronization()) {
        checksBeforeUpdateOrDelete("updateRow", -1);
        // Check that the cursor is not positioned on insertRow
        checkNotOnInsertRow();
        setupContextStack();
        LanguageConnectionContext lcc = getLanguageConnectionContext(getEmbedConnection());
        StatementContext statementContext = null;
        try {
            if (// nothing got updated on this row
            currentRowHasBeenUpdated == false)
                // nothing to do since no updates were made to this row
                return;
            // now construct the update where current of sql
            boolean foundOneColumnAlready = false;
            StringBuffer updateWhereCurrentOfSQL = new StringBuffer("UPDATE ");
            CursorActivation activation = lcc.lookupCursorActivation(getCursorName());
            ExecCursorTableReference targetTable = activation.getPreparedStatement().getTargetTable();
            // got the underlying (schema.)table name
            updateWhereCurrentOfSQL.append(getFullBaseTableName(targetTable));
            updateWhereCurrentOfSQL.append(" SET ");
            ResultDescription rd = theResults.getResultDescription();
            for (int i = 1; i <= rd.getColumnCount(); i++) {
                // in this for loop we are constructing columnname=?,... part of the update sql
                if (columnGotUpdated[i - 1]) {
                    // if the column got updated, do following
                    if (foundOneColumnAlready)
                        updateWhereCurrentOfSQL.append(",");
                    // using quotes around the column name to preserve case sensitivity
                    updateWhereCurrentOfSQL.append(IdUtil.normalToDelimited(rd.getColumnDescriptor(i).getName()) + "=?");
                    foundOneColumnAlready = true;
                }
            }
            // using quotes around the cursor name to preserve case sensitivity
            updateWhereCurrentOfSQL.append(" WHERE CURRENT OF " + IdUtil.normalToDelimited(getCursorName()));
            StatementContext currSC = lcc.getStatementContext();
            Activation parentAct = null;
            if (currSC != null) {
                parentAct = currSC.getActivation();
            }
            // Context used for preparing, don't set any timeout (use 0)
            statementContext = lcc.pushStatementContext(isAtomic, false, updateWhereCurrentOfSQL.toString(), null, false, 0L);
            // A priori, the new statement context inherits the activation of
            // the existing statementContext, so that that activation ends up
            // as parent of the new activation 'act' created below, which will
            // be the activation of the pushed statement context.
            statementContext.setActivation(parentAct);
            org.apache.derby.iapi.sql.PreparedStatement ps = lcc.prepareInternalStatement(updateWhereCurrentOfSQL.toString());
            Activation act = ps.getActivation(lcc, false);
            statementContext.setActivation(act);
            // in this for loop we are assigning values for parameters in sql constructed earlier with columnname=?,...
            for (int i = 1, paramPosition = 0; i <= rd.getColumnCount(); i++) {
                if (// if the column got updated, do following
                columnGotUpdated[i - 1])
                    act.getParameterValueSet().getParameterForSet(paramPosition++).setValue(updateRow.getColumn(i));
            }
            // Don't set any timeout when updating rows (use 0)
            // Execute the update where current of sql.
            org.apache.derby.iapi.sql.ResultSet rs = ps.executeSubStatement(activation, act, true, 0L);
            SQLWarning w = act.getWarnings();
            if (w != null) {
                addWarning(w);
            }
            act.close();
            // For forward only resultsets, after a update, the ResultSet will be positioned right before the next row.
            if (getType() == TYPE_FORWARD_ONLY) {
                currentRow = null;
            } else {
                movePosition(RELATIVE, 0, "relative");
            }
            lcc.popStatementContext(statementContext, null);
            InterruptStatus.restoreIntrFlagIfSeen(lcc);
        } catch (Throwable t) {
            throw closeOnTransactionError(t);
        } finally {
            if (statementContext != null)
                lcc.popStatementContext(statementContext, null);
            restoreContextStack();
            initializeUpdateRowModifiers();
        }
    }
}
Also used : SQLWarning(java.sql.SQLWarning) CursorActivation(org.apache.derby.iapi.sql.execute.CursorActivation) Activation(org.apache.derby.iapi.sql.Activation) CursorActivation(org.apache.derby.iapi.sql.execute.CursorActivation) StatementContext(org.apache.derby.iapi.sql.conn.StatementContext) ExecCursorTableReference(org.apache.derby.iapi.sql.execute.ExecCursorTableReference) LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) ResultDescription(org.apache.derby.iapi.sql.ResultDescription) ResultSet(org.apache.derby.iapi.sql.ResultSet)

Example 2 with ResultDescription

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

the class EmbedResultSet method insertRow.

/**
 * JDBC 2.0
 *
 * Insert the contents of the insert row into the result set and the
 * database. Must be on the insert row when this method is called.
 *
 * @exception SQLException
 *                if a database-access error occurs, if called when not on
 *                the insert row, or if all non-nullable columns in the
 *                insert row have not been given a value
 */
public void insertRow() throws SQLException {
    synchronized (getConnectionSynchronization()) {
        checksBeforeInsert();
        setupContextStack();
        LanguageConnectionContext lcc = getLanguageConnectionContext(getEmbedConnection());
        StatementContext statementContext = null;
        try {
            /*
                 * construct the insert statement
                 *
                 * If no values have been supplied for a column, it will be set 
                 * to the column's default value, if any. 
                 * If no default value had been defined, the default value of a 
                 * nullable column is set to NULL.
                 */
            boolean foundOneColumnAlready = false;
            StringBuffer insertSQL = new StringBuffer("INSERT INTO ");
            StringBuffer valuesSQL = new StringBuffer("VALUES (");
            CursorActivation activation = lcc.lookupCursorActivation(getCursorName());
            ExecCursorTableReference targetTable = activation.getPreparedStatement().getTargetTable();
            // got the underlying (schema.)table name
            insertSQL.append(getFullBaseTableName(targetTable));
            ResultDescription rd = theResults.getResultDescription();
            insertSQL.append(" (");
            // and values (?) ,... part of the insert sql
            for (int i = 1; i <= rd.getColumnCount(); i++) {
                if (foundOneColumnAlready) {
                    insertSQL.append(",");
                    valuesSQL.append(",");
                }
                // using quotes around the column name
                // to preserve case sensitivity
                insertSQL.append(IdUtil.normalToDelimited(rd.getColumnDescriptor(i).getName()));
                if (columnGotUpdated[i - 1]) {
                    valuesSQL.append("?");
                } else {
                    valuesSQL.append("DEFAULT");
                }
                foundOneColumnAlready = true;
            }
            insertSQL.append(") ");
            valuesSQL.append(") ");
            insertSQL.append(valuesSQL);
            StatementContext currSC = lcc.getStatementContext();
            Activation parentAct = null;
            if (currSC != null) {
                parentAct = currSC.getActivation();
            }
            // Context used for preparing, don't set any timeout (use 0)
            statementContext = lcc.pushStatementContext(isAtomic, false, insertSQL.toString(), null, false, 0L);
            // A priori, the new statement context inherits the activation
            // of the existing statementContext, so that that activation
            // ends up as parent of the new activation 'act' created below,
            // which will be the activation of the pushed statement
            // context.
            statementContext.setActivation(parentAct);
            org.apache.derby.iapi.sql.PreparedStatement ps = lcc.prepareInternalStatement(insertSQL.toString());
            Activation act = ps.getActivation(lcc, false);
            statementContext.setActivation(act);
            // in sql constructed earlier VALUES (?, ..)
            for (int i = 1, paramPosition = 0; i <= rd.getColumnCount(); i++) {
                // if the column got updated, do following
                if (columnGotUpdated[i - 1]) {
                    act.getParameterValueSet().getParameterForSet(paramPosition++).setValue(updateRow.getColumn(i));
                }
            }
            // Don't see any timeout when inserting rows (use 0)
            // execute the insert
            org.apache.derby.iapi.sql.ResultSet rs = ps.executeSubStatement(activation, act, true, 0L);
            act.close();
            lcc.popStatementContext(statementContext, null);
            InterruptStatus.restoreIntrFlagIfSeen(lcc);
        } catch (Throwable t) {
            throw closeOnTransactionError(t);
        } finally {
            if (statementContext != null)
                lcc.popStatementContext(statementContext, null);
            restoreContextStack();
        }
    }
}
Also used : CursorActivation(org.apache.derby.iapi.sql.execute.CursorActivation) Activation(org.apache.derby.iapi.sql.Activation) CursorActivation(org.apache.derby.iapi.sql.execute.CursorActivation) StatementContext(org.apache.derby.iapi.sql.conn.StatementContext) ExecCursorTableReference(org.apache.derby.iapi.sql.execute.ExecCursorTableReference) LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) ResultDescription(org.apache.derby.iapi.sql.ResultDescription) ResultSet(org.apache.derby.iapi.sql.ResultSet)

Example 3 with ResultDescription

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

the class EmbedResultSet method checksBeforeUpdateXXX.

// do following few checks before accepting updateXXX resultset api
protected void checksBeforeUpdateXXX(String methodName, int columnIndex) throws SQLException {
    checksBeforeUpdateOrDelete(methodName, columnIndex);
    // 1)Make sure for updateXXX methods, the column position is not out of range
    ResultDescription rd = theResults.getResultDescription();
    if (columnIndex < 1 || columnIndex > rd.getColumnCount())
        throw Util.generateCsSQLException(SQLState.LANG_INVALID_COLUMN_POSITION, columnIndex, String.valueOf(rd.getColumnCount()));
    // 2)Make sure the column corresponds to a column in the base table and it is not a derived column
    if (rd.getColumnDescriptor(columnIndex).getSourceTableName() == null)
        throw Util.generateCsSQLException(SQLState.COLUMN_NOT_FROM_BASE_TABLE, methodName);
    // 3)If column not updatable then throw an exception
    if (!getMetaData().isWritable(columnIndex))
        throw Util.generateCsSQLException(SQLState.LANG_COLUMN_NOT_UPDATABLE_IN_CURSOR, theResults.getResultDescription().getColumnDescriptor(columnIndex).getName(), getCursorName());
}
Also used : ResultDescription(org.apache.derby.iapi.sql.ResultDescription)

Example 4 with ResultDescription

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

the class DeleteNode method makeConstantAction.

/**
 * Compile constants that Execution will use
 *
 * @exception StandardException		Thrown on failure
 */
@Override
public ConstantAction makeConstantAction() throws StandardException {
    /* Different constant actions for base tables and updatable VTIs */
    if (targetTableDescriptor != null) {
        // Base table
        int lckMode = resultSet.updateTargetLockMode();
        long heapConglomId = targetTableDescriptor.getHeapConglomerateId();
        TransactionController tc = getLanguageConnectionContext().getTransactionCompile();
        StaticCompiledOpenConglomInfo[] indexSCOCIs = new StaticCompiledOpenConglomInfo[indexConglomerateNumbers.length];
        for (int index = 0; index < indexSCOCIs.length; index++) {
            indexSCOCIs[index] = tc.getStaticCompiledConglomInfo(indexConglomerateNumbers[index]);
        }
        /*
			** Do table locking if the table's lock granularity is
			** set to table.
			*/
        if (targetTableDescriptor.getLockGranularity() == TableDescriptor.TABLE_LOCK_GRANULARITY) {
            lckMode = TransactionController.MODE_TABLE;
        }
        ResultDescription resultDescription = null;
        if (isDependentTable) {
            // triggers need the result description ,
            // dependent tables  don't have a source from generation time
            // to get the result description
            resultDescription = makeResultDescription();
        }
        return getGenericConstantActionFactory().getDeleteConstantAction(heapConglomId, targetTableDescriptor.getTableType(), tc.getStaticCompiledConglomInfo(heapConglomId), indicesToMaintain, indexConglomerateNumbers, indexSCOCIs, deferred, false, targetTableDescriptor.getUUID(), lckMode, null, null, null, 0, null, null, resultDescription, getFKInfo(), getTriggerInfo(), (readColsBitSet == null) ? (FormatableBitSet) null : new FormatableBitSet(readColsBitSet), getReadColMap(targetTableDescriptor.getNumberOfColumns(), readColsBitSet), resultColumnList.getStreamStorableColIds(targetTableDescriptor.getNumberOfColumns()), (readColsBitSet == null) ? targetTableDescriptor.getNumberOfColumns() : readColsBitSet.getNumBitsSet(), (UUID) null, resultSet.isOneRowResultSet(), dependentConstantActions, inMatchingClause());
    } else {
        /* Return constant action for VTI
			 * NOTE: ConstantAction responsible for preserving instantiated
			 * VTIs for in-memory queries and for only preserving VTIs
			 * that implement Serializable for SPSs.
			 */
        return getGenericConstantActionFactory().getUpdatableVTIConstantAction(DeferModification.DELETE_STATEMENT, deferred);
    }
}
Also used : ResultDescription(org.apache.derby.iapi.sql.ResultDescription) FormatableBitSet(org.apache.derby.iapi.services.io.FormatableBitSet) StaticCompiledOpenConglomInfo(org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo) TransactionController(org.apache.derby.iapi.store.access.TransactionController)

Example 5 with ResultDescription

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

the class NoRowsResultSetImpl method evaluateGenerationClauses.

/**
 * Compute the generation clauses on the current row in order to fill in
 * computed columns.
 *
 * @param generationClauses    the generated method which evaluates generation clauses
 * @param activation               the thread-specific instance of the generated class
 * @param source                   the tuple stream driving this INSERT/UPDATE
 * @param newRow                   the base row being stuffed
 * @param isUpdate                 true if this is an UPDATE. false otherwise.
 */
public void evaluateGenerationClauses(GeneratedMethod generationClauses, Activation activation, NoPutResultSet source, ExecRow newRow, boolean isUpdate) throws StandardException {
    if (generationClauses != null) {
        ExecRow oldRow = (ExecRow) activation.getCurrentRow(source.resultSetNumber());
        // 
        try {
            source.setCurrentRow(newRow);
            activation.setCurrentRow(newRow, source.resultSetNumber());
            generationClauses.invoke(activation);
            // 
            if (firstColumn < 0) {
                firstColumn = NormalizeResultSet.computeStartColumn(isUpdate, activation.getResultDescription());
            }
            if (generatedColumnPositions == null) {
                setupGeneratedColumns(activation, (ValueRow) newRow);
            }
            ResultDescription resultDescription = activation.getResultDescription();
            int count = generatedColumnPositions.length;
            for (int i = 0; i < count; i++) {
                int position = generatedColumnPositions[i];
                DataValueDescriptor normalizedColumn = NormalizeResultSet.normalizeColumn(resultDescription.getColumnDescriptor(position).getType(), newRow, position, normalizedGeneratedValues[i], resultDescription);
                newRow.setColumn(position, normalizedColumn);
            }
        } finally {
            // 
            if (oldRow == null) {
                source.clearCurrentRow();
            } else {
                source.setCurrentRow(oldRow);
            }
        }
    }
}
Also used : ResultDescription(org.apache.derby.iapi.sql.ResultDescription) ExecRow(org.apache.derby.iapi.sql.execute.ExecRow) DataValueDescriptor(org.apache.derby.iapi.types.DataValueDescriptor)

Aggregations

ResultDescription (org.apache.derby.iapi.sql.ResultDescription)9 Properties (java.util.Properties)2 Activation (org.apache.derby.iapi.sql.Activation)2 ResultSet (org.apache.derby.iapi.sql.ResultSet)2 LanguageConnectionContext (org.apache.derby.iapi.sql.conn.LanguageConnectionContext)2 StatementContext (org.apache.derby.iapi.sql.conn.StatementContext)2 CursorActivation (org.apache.derby.iapi.sql.execute.CursorActivation)2 ExecCursorTableReference (org.apache.derby.iapi.sql.execute.ExecCursorTableReference)2 ExecRow (org.apache.derby.iapi.sql.execute.ExecRow)2 SQLWarning (java.sql.SQLWarning)1 FormatableBitSet (org.apache.derby.iapi.services.io.FormatableBitSet)1 GeneratedClass (org.apache.derby.iapi.services.loader.GeneratedClass)1 ResultColumnDescriptor (org.apache.derby.iapi.sql.ResultColumnDescriptor)1 ExecPreparedStatement (org.apache.derby.iapi.sql.execute.ExecPreparedStatement)1 StaticCompiledOpenConglomInfo (org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo)1 TransactionController (org.apache.derby.iapi.store.access.TransactionController)1 DataValueDescriptor (org.apache.derby.iapi.types.DataValueDescriptor)1