Search in sources :

Example 11 with ConstraintDescriptorList

use of org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList in project derby by apache.

the class RenameConstantAction method execGutsRenameColumn.

// do necessary work for rename column at execute time.
private void execGutsRenameColumn(TableDescriptor td, Activation activation) throws StandardException {
    ColumnDescriptor columnDescriptor = null;
    int columnPosition = 0;
    ConstraintDescriptorList constraintDescriptorList;
    ConstraintDescriptor constraintDescriptor;
    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    DependencyManager dm = dd.getDependencyManager();
    TransactionController tc = lcc.getTransactionExecute();
    /* get the column descriptor for column to be renamed and
		 * using it's position in the table, set the referenced
		 * column map of the table indicating which column is being
		 * renamed. Dependency Manager uses this to find out the
		 * dependents on the column.
		 */
    columnDescriptor = td.getColumnDescriptor(oldObjectName);
    if (columnDescriptor.isAutoincrement())
        columnDescriptor.setAutoinc_create_or_modify_Start_Increment(ColumnDefinitionNode.CREATE_AUTOINCREMENT);
    columnPosition = columnDescriptor.getPosition();
    FormatableBitSet toRename = new FormatableBitSet(td.getColumnDescriptorList().size() + 1);
    toRename.set(columnPosition);
    td.setReferencedColumnMap(toRename);
    dm.invalidateFor(td, DependencyManager.RENAME, lcc);
    // look for foreign key dependency on the column.
    constraintDescriptorList = dd.getConstraintDescriptors(td);
    for (int index = 0; index < constraintDescriptorList.size(); index++) {
        constraintDescriptor = constraintDescriptorList.elementAt(index);
        int[] referencedColumns = constraintDescriptor.getReferencedColumns();
        int numRefCols = referencedColumns.length;
        for (int j = 0; j < numRefCols; j++) {
            if ((referencedColumns[j] == columnPosition) && (constraintDescriptor instanceof ReferencedKeyConstraintDescriptor))
                dm.invalidateFor(constraintDescriptor, DependencyManager.RENAME, lcc);
        }
    }
    // Drop the column
    dd.dropColumnDescriptor(td.getUUID(), oldObjectName, tc);
    columnDescriptor.setColumnName(newObjectName);
    dd.addDescriptor(columnDescriptor, td, DataDictionary.SYSCOLUMNS_CATALOG_NUM, false, tc);
    // Need to do following to reload the cache so that table
    // descriptor now has new column name
    td = dd.getTableDescriptor(td.getObjectID());
}
Also used : LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) ColumnDescriptor(org.apache.derby.iapi.sql.dictionary.ColumnDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) ConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) DependencyManager(org.apache.derby.iapi.sql.depend.DependencyManager) FormatableBitSet(org.apache.derby.iapi.services.io.FormatableBitSet) ConstraintDescriptorList(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary) TransactionController(org.apache.derby.iapi.store.access.TransactionController)

Example 12 with ConstraintDescriptorList

use of org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList in project derby by apache.

the class RenameConstantAction method execGutsRenameTable.

// do necessary work for rename table at execute time.
private void execGutsRenameTable(TableDescriptor td, Activation activation) throws StandardException {
    ConstraintDescriptorList constraintDescriptorList;
    ConstraintDescriptor constraintDescriptor;
    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    DependencyManager dm = dd.getDependencyManager();
    TransactionController tc = lcc.getTransactionExecute();
    dm.invalidateFor(td, DependencyManager.RENAME, lcc);
    /* look for foreign key dependency on the table. If found any,
		use dependency manager to pass the rename action to the
		dependents. */
    constraintDescriptorList = dd.getConstraintDescriptors(td);
    for (int index = 0; index < constraintDescriptorList.size(); index++) {
        constraintDescriptor = constraintDescriptorList.elementAt(index);
        if (constraintDescriptor instanceof ReferencedKeyConstraintDescriptor)
            dm.invalidateFor(constraintDescriptor, DependencyManager.RENAME, lcc);
    }
    // Drop the table
    dd.dropTableDescriptor(td, sd, tc);
    // Change the table name of the table descriptor
    td.setTableName(newTableName);
    // add the table descriptor with new name
    dd.addDescriptor(td, sd, DataDictionary.SYSTABLES_CATALOG_NUM, false, tc);
}
Also used : LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) ConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) DependencyManager(org.apache.derby.iapi.sql.depend.DependencyManager) ConstraintDescriptorList(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary) TransactionController(org.apache.derby.iapi.store.access.TransactionController)

Example 13 with ConstraintDescriptorList

use of org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList in project derby by apache.

the class DropTableConstantAction method dropAllConstraintDescriptors.

private void dropAllConstraintDescriptors(TableDescriptor td, Activation activation) throws StandardException {
    ConstraintDescriptor cd;
    ConstraintDescriptorList cdl;
    ConstraintDescriptor fkcd;
    ConstraintDescriptorList fkcdl;
    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    DependencyManager dm = dd.getDependencyManager();
    TransactionController tc = lcc.getTransactionExecute();
    cdl = dd.getConstraintDescriptors(td);
    /* The current element will be deleted underneath
		 * the loop, so we only increment the counter when
		 * skipping an element. (HACK!)
		 */
    for (int index = 0; index < cdl.size(); ) {
        cd = cdl.elementAt(index);
        if (cd instanceof ReferencedKeyConstraintDescriptor) {
            index++;
            continue;
        }
        dm.invalidateFor(cd, DependencyManager.DROP_CONSTRAINT, lcc);
        dropConstraint(cd, td, activation, lcc, true);
    }
    /* The current element will be deleted underneath
		 * the loop. (HACK!)
		 */
    while (cdl.size() > 0) {
        cd = cdl.elementAt(0);
        if (SanityManager.DEBUG) {
            if (!(cd instanceof ReferencedKeyConstraintDescriptor)) {
                SanityManager.THROWASSERT("Constraint descriptor not an instance of " + "ReferencedKeyConstraintDescriptor as expected.  Is a " + cd.getClass().getName());
            }
        }
        /*
			** Drop the referenced constraint (after we got
			** the primary keys) now.  Do this prior to
			** droping the referenced keys to avoid performing
			** a lot of extra work updating the referencedcount
			** field of sys.sysconstraints.
			**
			** Pass in false to dropConstraintsAndIndex so it
			** doesn't clear dependencies, we'll do that ourselves.
			*/
        dropConstraint(cd, td, activation, lcc, false);
        /*
			** If we are going to cascade, get all the
			** referencing foreign keys and zap them first.
			*/
        if (cascade) {
            /*
				** Go to the system tables to get the foreign keys
				** to be safe
				*/
            fkcdl = dd.getForeignKeys(cd.getUUID());
            /*
				** For each FK that references this key, drop
				** it.
				*/
            for (int inner = 0; inner < fkcdl.size(); inner++) {
                fkcd = (ConstraintDescriptor) fkcdl.elementAt(inner);
                dm.invalidateFor(fkcd, DependencyManager.DROP_CONSTRAINT, lcc);
                dropConstraint(fkcd, td, activation, lcc, true);
                activation.addWarning(StandardException.newWarning(SQLState.LANG_CONSTRAINT_DROPPED, fkcd.getConstraintName(), fkcd.getTableDescriptor().getName()));
            }
        }
        /*
			** Now that we got rid of the fks (if we were cascading), it is 
			** ok to do an invalidate for.
			*/
        dm.invalidateFor(cd, DependencyManager.DROP_CONSTRAINT, lcc);
        dm.clearDependencies(lcc, cd);
    }
}
Also used : LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) ConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) DependencyManager(org.apache.derby.iapi.sql.depend.DependencyManager) ConstraintDescriptorList(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary) TransactionController(org.apache.derby.iapi.store.access.TransactionController)

Example 14 with ConstraintDescriptorList

use of org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList in project derby by apache.

the class AlterTableConstantAction method dropColumnFromTable.

/**
 * Workhorse for dropping a column from a table.
 *
 * This routine drops a column from a table, taking care
 * to properly handle the various related schema objects.
 *
 * The syntax which gets you here is:
 *
 *   ALTER TABLE tbl DROP [COLUMN] col [CASCADE|RESTRICT]
 *
 * The keyword COLUMN is optional, and if you don't
 * specify CASCADE or RESTRICT, the default is CASCADE
 * (the default is chosen in the parser, not here).
 *
 * If you specify RESTRICT, then the column drop should be
 * rejected if it would cause a dependent schema object
 * to become invalid.
 *
 * If you specify CASCADE, then the column drop should
 * additionally drop other schema objects which have
 * become invalid.
 *
 * You may not drop the last (only) column in a table.
 *
 * Schema objects of interest include:
 *  - views
 *  - triggers
 *  - constraints
 *    - check constraints
 *    - primary key constraints
 *    - foreign key constraints
 *    - unique key constraints
 *    - not null constraints
 *  - privileges
 *  - indexes
 *  - default values
 *
 * Dropping a column may also change the column position
 * numbers of other columns in the table, which may require
 * fixup of schema objects (such as triggers and column
 * privileges) which refer to columns by column position number.
 *
 * Indexes are a bit interesting. The official SQL spec
 * doesn't talk about indexes; they are considered to be
 * an imlementation-specific performance optimization.
 * The current Derby behavior is that:
 *  - CASCADE/RESTRICT doesn't matter for indexes
 *  - when a column is dropped, it is removed from any indexes
 *    which contain it.
 *  - if that column was the only column in the index, the
 *    entire index is dropped.
 *
 * @param   columnName the name of the column specfication in the ALTER
 *						statement-- currently we allow only one.
 * @exception StandardException 	thrown on failure.
 */
private void dropColumnFromTable(String columnName) throws StandardException {
    boolean cascade = (behavior == StatementType.DROP_CASCADE);
    // drop any generated columns which reference this column
    ColumnDescriptorList generatedColumnList = td.getGeneratedColumns();
    int generatedColumnCount = generatedColumnList.size();
    ArrayList<String> cascadedDroppedColumns = new ArrayList<String>();
    for (int i = 0; i < generatedColumnCount; i++) {
        ColumnDescriptor generatedColumn = generatedColumnList.elementAt(i);
        String[] referencedColumnNames = generatedColumn.getDefaultInfo().getReferencedColumnNames();
        int referencedColumnCount = referencedColumnNames.length;
        for (int j = 0; j < referencedColumnCount; j++) {
            if (columnName.equals(referencedColumnNames[j])) {
                String generatedColumnName = generatedColumn.getColumnName();
                // we're trying to drop
                if (!cascade) {
                    // 
                    throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT, dm.getActionString(DependencyManager.DROP_COLUMN), columnName, "GENERATED COLUMN", generatedColumnName);
                } else {
                    cascadedDroppedColumns.add(generatedColumnName);
                }
            }
        }
    }
    DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator();
    int cascadedDrops = cascadedDroppedColumns.size();
    int sizeAfterCascadedDrops = td.getColumnDescriptorList().size() - cascadedDrops;
    // can NOT drop a column if it is the only one in the table
    if (sizeAfterCascadedDrops == 1) {
        throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT, dm.getActionString(DependencyManager.DROP_COLUMN), "THE *LAST* COLUMN " + columnName, "TABLE", td.getQualifiedName());
    }
    // now drop dependent generated columns
    for (int i = 0; i < cascadedDrops; i++) {
        String generatedColumnName = cascadedDroppedColumns.get(i);
        activation.addWarning(StandardException.newWarning(SQLState.LANG_GEN_COL_DROPPED, generatedColumnName, td.getName()));
        // 
        // We can only recurse 2 levels since a generation clause cannot
        // refer to other generated columns.
        // 
        dropColumnFromTable(generatedColumnName);
    }
    /*
         * Cascaded drops of dependent generated columns may require us to
         * rebuild the table descriptor.
         */
    td = dd.getTableDescriptor(tableId);
    ColumnDescriptor columnDescriptor = td.getColumnDescriptor(columnName);
    // We already verified this in bind, but do it again
    if (columnDescriptor == null) {
        throw StandardException.newException(SQLState.LANG_COLUMN_NOT_FOUND_IN_TABLE, columnName, td.getQualifiedName());
    }
    int size = td.getColumnDescriptorList().size();
    droppedColumnPosition = columnDescriptor.getPosition();
    FormatableBitSet toDrop = new FormatableBitSet(size + 1);
    toDrop.set(droppedColumnPosition);
    td.setReferencedColumnMap(toDrop);
    dm.invalidateFor(td, (cascade ? DependencyManager.DROP_COLUMN : DependencyManager.DROP_COLUMN_RESTRICT), lcc);
    // If column has a default we drop the default and any dependencies
    if (columnDescriptor.getDefaultInfo() != null) {
        dm.clearDependencies(lcc, columnDescriptor.getDefaultDescriptor(dd));
    }
    // then we need to drop the system-generated sequence backing it.
    if (columnDescriptor.isAutoincrement() && dd.checkVersion(DataDictionary.DD_VERSION_DERBY_10_11, null)) {
        DropTableConstantAction.dropIdentitySequence(dd, td, activation);
    }
    // columns which are used through REFERENCING clause
    for (TriggerDescriptor trd : dd.getTriggerDescriptors(td)) {
        // If we find that the trigger is dependent on the column being
        // dropped because column is part of trigger columns list, then
        // we will give a warning or drop the trigger based on whether
        // ALTER TABLE DROP COLUMN is RESTRICT or CASCADE. In such a
        // case, no need to check if the trigger action columns referenced
        // through REFERENCING clause also used the column being dropped.
        boolean triggerDroppedAlready = false;
        int[] referencedCols = trd.getReferencedCols();
        if (referencedCols != null) {
            int refColLen = referencedCols.length, j;
            boolean changed = false;
            for (j = 0; j < refColLen; j++) {
                if (referencedCols[j] > droppedColumnPosition) {
                    // Trigger is not defined on the column being dropped
                    // but the column position of trigger column is changing
                    // because the position of the column being dropped is
                    // before the the trigger column
                    changed = true;
                } else if (referencedCols[j] == droppedColumnPosition) {
                    // the trigger is defined on the column being dropped
                    if (cascade) {
                        trd.drop(lcc);
                        triggerDroppedAlready = true;
                        activation.addWarning(StandardException.newWarning(SQLState.LANG_TRIGGER_DROPPED, trd.getName(), td.getName()));
                    } else {
                        // otherwsie there would be unexpected behaviors
                        throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT, dm.getActionString(DependencyManager.DROP_COLUMN), columnName, "TRIGGER", trd.getName());
                    }
                    break;
                }
            }
            // drop column.
            if (j == refColLen && changed) {
                dd.dropTriggerDescriptor(trd, tc);
                for (j = 0; j < refColLen; j++) {
                    if (referencedCols[j] > droppedColumnPosition)
                        referencedCols[j]--;
                }
                trd.setReferencedCols(referencedCols);
                dd.addDescriptor(trd, sd, DataDictionary.SYSTRIGGERS_CATALOG_NUM, false, tc);
            }
        }
        // loop above, then move to next trigger
        if (triggerDroppedAlready)
            continue;
        // Column being dropped is not one of trigger columns. Check if
        // that column is getting used inside the trigger action through
        // REFERENCING clause. This can be tracked only for triggers
        // created in 10.7 and higher releases. Derby releases prior to
        // that did not keep track of trigger action columns used
        // through the REFERENCING clause.
        int[] referencedColsInTriggerAction = trd.getReferencedColsInTriggerAction();
        if (referencedColsInTriggerAction != null) {
            int refColInTriggerActionLen = referencedColsInTriggerAction.length, j;
            boolean changedColPositionInTriggerAction = false;
            for (j = 0; j < refColInTriggerActionLen; j++) {
                if (referencedColsInTriggerAction[j] > droppedColumnPosition) {
                    changedColPositionInTriggerAction = true;
                } else if (referencedColsInTriggerAction[j] == droppedColumnPosition) {
                    if (cascade) {
                        trd.drop(lcc);
                        triggerDroppedAlready = true;
                        activation.addWarning(StandardException.newWarning(SQLState.LANG_TRIGGER_DROPPED, trd.getName(), td.getName()));
                    } else {
                        // we'd better give an error if don't drop it,
                        throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT, dm.getActionString(DependencyManager.DROP_COLUMN), columnName, "TRIGGER", trd.getName());
                    }
                    break;
                }
            }
            // column has been actually dropped from the table descriptor.
            if (j == refColInTriggerActionLen && changedColPositionInTriggerAction) {
                dd.dropTriggerDescriptor(trd, tc);
                for (j = 0; j < refColInTriggerActionLen; j++) {
                    if (referencedColsInTriggerAction[j] > droppedColumnPosition)
                        referencedColsInTriggerAction[j]--;
                }
                trd.setReferencedColsInTriggerAction(referencedColsInTriggerAction);
                dd.addDescriptor(trd, sd, DataDictionary.SYSTRIGGERS_CATALOG_NUM, false, tc);
            }
        }
    }
    ConstraintDescriptorList csdl = dd.getConstraintDescriptors(td);
    int csdl_size = csdl.size();
    ArrayList<ConstantAction> newCongloms = new ArrayList<ConstantAction>();
    // we want to remove referenced primary/unique keys in the second
    // round.  This will ensure that self-referential constraints will
    // work OK.
    int tbr_size = 0;
    ConstraintDescriptor[] toBeRemoved = new ConstraintDescriptor[csdl_size];
    // let's go downwards, don't want to get messed up while removing
    for (int i = csdl_size - 1; i >= 0; i--) {
        ConstraintDescriptor cd = csdl.elementAt(i);
        int[] referencedColumns = cd.getReferencedColumns();
        int numRefCols = referencedColumns.length, j;
        boolean changed = false;
        for (j = 0; j < numRefCols; j++) {
            if (referencedColumns[j] > droppedColumnPosition)
                changed = true;
            if (referencedColumns[j] == droppedColumnPosition)
                break;
        }
        if (// column not referenced
        j == numRefCols) {
            if ((cd instanceof CheckConstraintDescriptor) && changed) {
                dd.dropConstraintDescriptor(cd, tc);
                for (j = 0; j < numRefCols; j++) {
                    if (referencedColumns[j] > droppedColumnPosition)
                        referencedColumns[j]--;
                }
                ((CheckConstraintDescriptor) cd).setReferencedColumnsDescriptor(new ReferencedColumnsDescriptorImpl(referencedColumns));
                dd.addConstraintDescriptor(cd, tc);
            }
            continue;
        }
        if (!cascade) {
            // 
            throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT, dm.getActionString(DependencyManager.DROP_COLUMN), columnName, "CONSTRAINT", cd.getConstraintName());
        }
        if (cd instanceof ReferencedKeyConstraintDescriptor) {
            // restrict will raise an error in invalidate if referenced
            toBeRemoved[tbr_size++] = cd;
            continue;
        }
        // drop now in all other cases
        dm.invalidateFor(cd, DependencyManager.DROP_CONSTRAINT, lcc);
        dropConstraint(cd, td, newCongloms, activation, lcc, true);
        activation.addWarning(StandardException.newWarning(SQLState.LANG_CONSTRAINT_DROPPED, cd.getConstraintName(), td.getName()));
    }
    for (int i = tbr_size - 1; i >= 0; i--) {
        ConstraintDescriptor cd = toBeRemoved[i];
        dropConstraint(cd, td, newCongloms, activation, lcc, false);
        activation.addWarning(StandardException.newWarning(SQLState.LANG_CONSTRAINT_DROPPED, cd.getConstraintName(), td.getName()));
        if (cascade) {
            ConstraintDescriptorList fkcdl = dd.getForeignKeys(cd.getUUID());
            for (ConstraintDescriptor fkcd : fkcdl) {
                dm.invalidateFor(fkcd, DependencyManager.DROP_CONSTRAINT, lcc);
                dropConstraint(fkcd, td, newCongloms, activation, lcc, true);
                activation.addWarning(StandardException.newWarning(SQLState.LANG_CONSTRAINT_DROPPED, fkcd.getConstraintName(), fkcd.getTableDescriptor().getName()));
            }
        }
        dm.invalidateFor(cd, DependencyManager.DROP_CONSTRAINT, lcc);
        dm.clearDependencies(lcc, cd);
    }
    /* If there are new backing conglomerates which must be
		 * created to replace a dropped shared conglomerate
		 * (where the shared conglomerate was dropped as part
		 * of a "drop constraint" call above), then create them
		 * now.  We do this *after* dropping all dependent
		 * constraints because we don't want to waste time
		 * creating a new conglomerate if it's just going to be
		 * dropped again as part of another "drop constraint".
		 */
    createNewBackingCongloms(newCongloms, (long[]) null);
    /*
         * The work we've done above, specifically the possible
         * dropping of primary key, foreign key, and unique constraints
         * and their underlying indexes, may have affected the table
         * descriptor. By re-reading the table descriptor here, we
         * ensure that the compressTable code is working with an
         * accurate table descriptor. Without this line, we may get
         * conglomerate-not-found errors and the like due to our
         * stale table descriptor.
         */
    td = dd.getTableDescriptor(tableId);
    compressTable();
    ColumnDescriptorList tab_cdl = td.getColumnDescriptorList();
    // drop the column from syscolumns
    dd.dropColumnDescriptor(td.getUUID(), columnName, tc);
    ColumnDescriptor[] cdlArray = new ColumnDescriptor[size - columnDescriptor.getPosition()];
    // 
    for (int i = columnDescriptor.getPosition(), j = 0; i < size; i++, j++) {
        ColumnDescriptor cd = tab_cdl.elementAt(i);
        dd.dropColumnDescriptor(td.getUUID(), cd.getColumnName(), tc);
        cd.setPosition(i);
        if (cd.isAutoincrement()) {
            cd.setAutoinc_create_or_modify_Start_Increment(ColumnDefinitionNode.CREATE_AUTOINCREMENT);
        }
        cdlArray[j] = cd;
    }
    dd.addDescriptorArray(cdlArray, td, DataDictionary.SYSCOLUMNS_CATALOG_NUM, false, tc);
    // By this time, the column has been removed from the table descriptor.
    // Now, go through all the triggers and regenerate their trigger action
    // SPS and rebind the generated trigger action sql. If the trigger
    // action is using the dropped column, it will get detected here. If
    // not, then we will have generated the internal trigger action sql
    // which matches the trigger action sql provided by the user.
    // 
    // eg of positive test case
    // create table atdc_16_tab1 (a1 integer, b1 integer, c1 integer);
    // create table atdc_16_tab2 (a2 integer, b2 integer, c2 integer);
    // create trigger atdc_16_trigger_1
    // after update of b1 on atdc_16_tab1
    // REFERENCING NEW AS newt
    // for each row
    // update atdc_16_tab2 set c2 = newt.c1
    // The internal representation for the trigger action before the column
    // is dropped is as follows
    // update atdc_16_tab2 set c2 =
    // org.apache.derby.iapi.db.Factory::getTriggerExecutionContext().
    // getONewRow().getInt(3)
    // After the drop column shown as below
    // alter table DERBY4998_SOFT_UPGRADE_RESTRICT drop column c11
    // The above internal representation of tigger action sql is not
    // correct anymore because column position of c1 in atdc_16_tab1 has
    // now changed from 3 to 2. Following while loop will regenerate it and
    // change it to as follows
    // update atdc_16_tab2 set c2 =
    // org.apache.derby.iapi.db.Factory::getTriggerExecutionContext().
    // getONewRow().getInt(2)
    // 
    // We could not do this before the actual column drop, because the
    // rebind would have still found the column being dropped in the
    // table descriptor and hence use of such a column in the trigger
    // action rebind would not have been caught.
    // For the table on which ALTER TABLE is getting performed, find out
    // all the SPSDescriptors that use that table as a provider. We are
    // looking for SPSDescriptors that have been created internally for
    // trigger action SPSes. Through those SPSDescriptors, we will be
    // able to get to the triggers dependent on the table being altered
    // Following will get all the dependent objects that are using
    // ALTER TABLE table as provider
    List<DependencyDescriptor> depsOnAlterTableList = dd.getProvidersDescriptorList(td.getObjectID().toString());
    for (DependencyDescriptor depOnAT : depsOnAlterTableList) {
        // Go through all the dependent objects on the table being altered
        DependableFinder dependent = depOnAT.getDependentFinder();
        // stored prepared statement.
        if (dependent.getSQLObjectType().equals(Dependable.STORED_PREPARED_STATEMENT)) {
            // Look for all the dependent objects that are using this
            // stored prepared statement as provider. We are only
            // interested in dependents that are triggers.
            List<DependencyDescriptor> depsTrigger = dd.getProvidersDescriptorList(depOnAT.getUUID().toString());
            for (DependencyDescriptor depsTriggerDesc : depsTrigger) {
                DependableFinder providerIsTrigger = depsTriggerDesc.getDependentFinder();
                // it is a trigger
                if (providerIsTrigger.getSQLObjectType().equals(Dependable.TRIGGER)) {
                    // Drop and recreate the trigger after regenerating
                    // it's trigger action plan. If the trigger action
                    // depends on the column being dropped, it will be
                    // caught here.
                    TriggerDescriptor trdToBeDropped = dd.getTriggerDescriptor(depsTriggerDesc.getUUID());
                    // First check for dependencies in the trigger's WHEN
                    // clause, if there is one.
                    UUID whenClauseId = trdToBeDropped.getWhenClauseId();
                    boolean gotDropped = false;
                    if (whenClauseId != null) {
                        gotDropped = columnDroppedAndTriggerDependencies(trdToBeDropped, whenClauseId, true, cascade, columnName);
                    }
                    // dependencies.
                    if (!gotDropped) {
                        columnDroppedAndTriggerDependencies(trdToBeDropped, trdToBeDropped.getActionId(), false, cascade, columnName);
                    }
                }
            }
        }
    }
    // Adjust the column permissions rows in SYSCOLPERMS to reflect the
    // changed column positions due to the dropped column:
    dd.updateSYSCOLPERMSforDropColumn(td.getUUID(), tc, columnDescriptor);
    // remove column descriptor from table descriptor. this fixes up the
    // list in case we were called recursively in order to cascade-drop a
    // dependent generated column.
    tab_cdl.remove(td.getColumnDescriptor(columnName));
}
Also used : DependencyDescriptor(org.apache.derby.iapi.sql.dictionary.DependencyDescriptor) ArrayList(java.util.ArrayList) ReferencedColumnsDescriptorImpl(org.apache.derby.catalog.types.ReferencedColumnsDescriptorImpl) CheckConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.CheckConstraintDescriptor) DataDescriptorGenerator(org.apache.derby.iapi.sql.dictionary.DataDescriptorGenerator) ConstantAction(org.apache.derby.iapi.sql.execute.ConstantAction) DependableFinder(org.apache.derby.catalog.DependableFinder) ColumnDescriptorList(org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList) FormatableBitSet(org.apache.derby.iapi.services.io.FormatableBitSet) UUID(org.apache.derby.catalog.UUID) ColumnDescriptor(org.apache.derby.iapi.sql.dictionary.ColumnDescriptor) ConstraintDescriptorList(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList) TriggerDescriptor(org.apache.derby.iapi.sql.dictionary.TriggerDescriptor) CheckConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.CheckConstraintDescriptor) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor) ConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor)

Example 15 with ConstraintDescriptorList

use of org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList in project derby by apache.

the class AlterTableConstantAction method executeConstantActionBody.

/**
 *	This is the guts of the Execution-time logic for ALTER TABLE.
 *
 *	@see ConstantAction#executeConstantAction
 *
 * @exception StandardException		Thrown on failure
 */
private void executeConstantActionBody(Activation activation) throws StandardException {
    // Save references to the main structures we need.
    this.activation = activation;
    lcc = activation.getLanguageConnectionContext();
    dd = lcc.getDataDictionary();
    dm = dd.getDependencyManager();
    tc = lcc.getTransactionExecute();
    int numRows = 0;
    boolean tableScanned = false;
    if (compressTable || truncateTable) {
        DeferredConstraintsMemory.compressOrTruncate(lcc, tableId, tableName);
    }
    // tables to do the compression is done later in this method.
    if (compressTable) {
        if (purge || defragment || truncateEndOfTable) {
            td = dd.getTableDescriptor(tableId);
            if (td == null) {
                throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tableName);
            }
            // made larger by the previous purge/defragment pass.
            if (purge)
                purgeRows(tc);
            if (defragment)
                defragmentRows(tc);
            if (truncateEndOfTable)
                truncateEnd(tc);
            return;
        }
    }
    if (updateStatistics) {
        updateStatistics();
        return;
    }
    if (dropStatistics) {
        dropStatistics();
        return;
    }
    /*
		** Inform the data dictionary that we are about to write to it.
		** There are several calls to data dictionary "get" methods here
		** that might be done in "read" mode in the data dictionary, but
		** it seemed safer to do this whole operation in "write" mode.
		**
		** We tell the data dictionary we're done writing at the end of
		** the transaction.
		*/
    dd.startWriting(lcc);
    // older version (or at target) has to get td first, potential deadlock
    if (tableConglomerateId == 0) {
        td = dd.getTableDescriptor(tableId);
        if (td == null) {
            throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tableName);
        }
        tableConglomerateId = td.getHeapConglomerateId();
    }
    lockTableForDDL(tc, tableConglomerateId, true);
    td = dd.getTableDescriptor(tableId);
    if (td == null) {
        throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tableName);
    }
    if (truncateTable)
        dm.invalidateFor(td, DependencyManager.TRUNCATE_TABLE, lcc);
    else
        dm.invalidateFor(td, DependencyManager.ALTER_TABLE, lcc);
    // Save the TableDescriptor off in the Activation
    activation.setDDLTableDescriptor(td);
    /*
		** If the schema descriptor is null, then we must have just read 
        ** ourselves in.  So we will get the corresponding schema descriptor 
        ** from the data dictionary.
		*/
    if (sd == null) {
        sd = getAndCheckSchemaDescriptor(dd, schemaId, "ALTER TABLE");
    }
    /* Prepare all dependents to invalidate.  (This is their chance
		 * to say that they can't be invalidated.  For example, an open
		 * cursor referencing a table/view that the user is attempting to
		 * alter.) If no one objects, then invalidate any dependent objects.
		 */
    if (truncateTable)
        dm.invalidateFor(td, DependencyManager.TRUNCATE_TABLE, lcc);
    else
        dm.invalidateFor(td, DependencyManager.ALTER_TABLE, lcc);
    // Are we working on columns?
    if (columnInfo != null) {
        boolean tableNeedsScanning = false;
        /* for each new column, see if the user is adding a non-nullable
			 * column.  This is only allowed on an empty table.
			 */
        for (int ix = 0; ix < columnInfo.length; ix++) {
            /* Is this new column non-nullable?  
				 * If so, it can only be added to an
				 * empty table if it does not have a default value.	
				 * We need to scan the table to find out how many rows 
				 * there are.
				 */
            if ((columnInfo[ix].action == ColumnInfo.CREATE) && !(columnInfo[ix].dataType.isNullable()) && (columnInfo[ix].defaultInfo == null) && (columnInfo[ix].autoincInc == 0)) {
                tableNeedsScanning = true;
            }
        }
        // Scan the table if necessary
        if (tableNeedsScanning) {
            numRows = getSemiRowCount(tc);
            // Don't allow add of non-nullable column to non-empty table
            if (numRows > 0) {
                throw StandardException.newException(SQLState.LANG_ADDING_NON_NULL_COLUMN_TO_NON_EMPTY_TABLE, td.getQualifiedName());
            }
            tableScanned = true;
        }
        // for each related column, stuff system.column
        for (int ix = 0; ix < columnInfo.length; ix++) {
            if (columnInfo[ix].action == ColumnInfo.CREATE) {
                addNewColumnToTable(ix);
            } else if (columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_DEFAULT_RESTART || columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_DEFAULT_INCREMENT || columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_DEFAULT_CYCLE || columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_DEFAULT_VALUE) {
                modifyColumnDefault(ix);
            } else if (columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_TYPE) {
                modifyColumnType(ix);
            } else if (columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_CONSTRAINT) {
                modifyColumnConstraint(columnInfo[ix].name, true);
            } else if (columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_CONSTRAINT_NOT_NULL) {
                if (!tableScanned) {
                    tableScanned = true;
                    numRows = getSemiRowCount(tc);
                }
                // check that the data in the column is not null
                String[] colNames = new String[1];
                colNames[0] = columnInfo[ix].name;
                boolean[] nullCols = new boolean[1];
                /* note validateNotNullConstraint returns true if the
					 * column is nullable
					 */
                if (validateNotNullConstraint(colNames, nullCols, numRows, lcc, SQLState.LANG_NULL_DATA_IN_NON_NULL_COLUMN)) {
                    /* nullable column - modify it to be not null
						 * This is O.K. at this point since we would have
						 * thrown an exception if any data was null
						 */
                    modifyColumnConstraint(columnInfo[ix].name, false);
                }
            } else if (columnInfo[ix].action == ColumnInfo.DROP) {
                dropColumnFromTable(columnInfo[ix].name);
            } else if ((columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_GENERATED_ALWAYS) || (columnInfo[ix].action == ColumnInfo.MODIFY_COLUMN_GENERATED_BY_DEFAULT)) {
                modifyIdentityState(ix);
            } else if (SanityManager.DEBUG) {
                SanityManager.THROWASSERT("Unexpected action in AlterTableConstantAction");
            }
        }
    }
    // adjust dependencies on user defined types
    adjustUDTDependencies(lcc, dd, td, columnInfo, false);
    /* Create/Drop/alter any constraints */
    if (constraintActions != null) {
        for (int conIndex = 0; conIndex < constraintActions.length; conIndex++) {
            ConstraintConstantAction cca = constraintActions[conIndex];
            boolean isCheckInitiallyDeferred = false;
            if (cca instanceof CreateConstraintConstantAction) {
                final CreateConstraintConstantAction ccca = (CreateConstraintConstantAction) cca;
                int constraintType = ccca.getConstraintType();
                isCheckInitiallyDeferred = (constraintType == DataDictionary.CHECK_CONSTRAINT) && ccca.isInitiallyDeferred();
                /* Some constraint types require special checking:
					 *   Check		 - table must be empty, for now
					 *   Primary Key - table cannot already have a primary key
					 */
                switch(constraintType) {
                    case DataDictionary.PRIMARYKEY_CONSTRAINT:
                        // Check to see if a constraint of the same type
                        // already exists
                        ConstraintDescriptorList cdl = dd.getConstraintDescriptors(td);
                        if (cdl.getPrimaryKey() != null) {
                            throw StandardException.newException(SQLState.LANG_ADD_PRIMARY_KEY_FAILED1, td.getQualifiedName());
                        }
                        if (!tableScanned) {
                            tableScanned = true;
                            numRows = getSemiRowCount(tc);
                        }
                        break;
                    case DataDictionary.CHECK_CONSTRAINT:
                        if (!tableScanned) {
                            tableScanned = true;
                            numRows = getSemiRowCount(tc);
                        }
                        if (isCheckInitiallyDeferred) {
                            // Need to do this early to get UUID
                            // assigned
                            constraintActions[conIndex].executeConstantAction(activation);
                        }
                        if (numRows > 0) {
                            /*
								** We are assuming that there will only be one 
								** check constraint that we are adding, so it
								** is ok to do the check now rather than try
								** to lump together several checks.	
								*/
                            ConstraintConstantAction.validateConstraint(cca.getConstraintName(), ((CreateConstraintConstantAction) cca).getConstraintText(), cca.getConstraintId(), td, lcc, true, isCheckInitiallyDeferred);
                        }
                        break;
                }
            } else {
                if (SanityManager.DEBUG) {
                    if (!(cca instanceof DropConstraintConstantAction || cca instanceof AlterConstraintConstantAction)) {
                        SanityManager.THROWASSERT("constraintActions[" + conIndex + "] expected to be instanceof " + "DropConstraintConstantAction not " + cca.getClass().getName());
                    }
                }
            }
            if (!isCheckInitiallyDeferred) {
                constraintActions[conIndex].executeConstantAction(activation);
            }
        // else it is done early, see above.
        }
    }
    // Are we changing the lock granularity?
    if (lockGranularity != '\0') {
        if (SanityManager.DEBUG) {
            if (lockGranularity != 'T' && lockGranularity != 'R') {
                SanityManager.THROWASSERT("lockGranularity expected to be 'T'or 'R', not " + lockGranularity);
            }
        }
        // update the TableDescriptor
        td.setLockGranularity(lockGranularity);
        // update the DataDictionary
        dd.updateLockGranularity(td, sd, lockGranularity, tc);
    }
    // Are we doing a compress table?
    if (compressTable) {
        compressTable();
    }
    // Are we doing a truncate table?
    if (truncateTable) {
        truncateTable();
    }
}
Also used : ConstraintDescriptorList(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList)

Aggregations

ConstraintDescriptorList (org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList)24 ConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor)15 ReferencedKeyConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor)10 DataDictionary (org.apache.derby.iapi.sql.dictionary.DataDictionary)7 ForeignKeyConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor)7 ColumnDescriptor (org.apache.derby.iapi.sql.dictionary.ColumnDescriptor)6 LanguageConnectionContext (org.apache.derby.iapi.sql.conn.LanguageConnectionContext)5 ColumnDescriptorList (org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList)5 TransactionController (org.apache.derby.iapi.store.access.TransactionController)5 ArrayList (java.util.ArrayList)4 FormatableBitSet (org.apache.derby.iapi.services.io.FormatableBitSet)4 DependencyManager (org.apache.derby.iapi.sql.depend.DependencyManager)4 ConglomerateDescriptor (org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor)4 TableDescriptor (org.apache.derby.iapi.sql.dictionary.TableDescriptor)4 UUID (org.apache.derby.catalog.UUID)3 CheckConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.CheckConstraintDescriptor)3 SchemaDescriptor (org.apache.derby.iapi.sql.dictionary.SchemaDescriptor)3 DataValueDescriptor (org.apache.derby.iapi.types.DataValueDescriptor)3 KeyConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.KeyConstraintDescriptor)2 SubKeyConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.SubKeyConstraintDescriptor)2