Search in sources :

Example 6 with ForeignKeyConstraintDescriptor

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

the class DropConstraintConstantAction method executeConstantAction.

// INTERFACE METHODS
/**
 *	This is the guts of the Execution-time logic for DROP CONSTRAINT.
 *
 *	@see ConstantAction#executeConstantAction
 *
 * @exception StandardException		Thrown on failure
 */
public void executeConstantAction(Activation activation) throws StandardException {
    ConstraintDescriptor conDesc = null;
    TableDescriptor td;
    UUID indexId = null;
    String indexUUIDString;
    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    DependencyManager dm = dd.getDependencyManager();
    TransactionController tc = lcc.getTransactionExecute();
    /*
		** 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);
    td = dd.getTableDescriptor(tableId);
    if (td == null) {
        throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tableName);
    }
    /* Table gets locked in AlterTableConstantAction */
    /*
		** 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.
		*/
    SchemaDescriptor tdSd = td.getSchemaDescriptor();
    SchemaDescriptor constraintSd = constraintSchemaName == null ? tdSd : dd.getSchemaDescriptor(constraintSchemaName, tc, true);
    /* Get the constraint descriptor for the index, along
		 * with an exclusive row lock on the row in sys.sysconstraints
		 * in order to ensure that no one else compiles against the
		 * index.
		 */
    if (// this means "alter table drop primary key"
    constraintName == null)
        conDesc = dd.getConstraintDescriptors(td).getPrimaryKey();
    else
        conDesc = dd.getConstraintDescriptorByName(td, constraintSd, constraintName, true);
    // Error if constraint doesn't exist
    if (conDesc == null) {
        String errorName = constraintName == null ? "PRIMARY KEY" : (constraintSd.getSchemaName() + "." + constraintName);
        throw StandardException.newException(SQLState.LANG_DROP_OR_ALTER_NON_EXISTING_CONSTRAINT, errorName, td.getQualifiedName());
    }
    switch(verifyType) {
        case DataDictionary.UNIQUE_CONSTRAINT:
            if (conDesc.getConstraintType() != verifyType)
                throw StandardException.newException(SQLState.LANG_DROP_CONSTRAINT_TYPE, constraintName, "UNIQUE");
            break;
        case DataDictionary.CHECK_CONSTRAINT:
            if (conDesc.getConstraintType() != verifyType)
                throw StandardException.newException(SQLState.LANG_DROP_CONSTRAINT_TYPE, constraintName, "CHECK");
            break;
        case DataDictionary.FOREIGNKEY_CONSTRAINT:
            if (conDesc.getConstraintType() != verifyType)
                throw StandardException.newException(SQLState.LANG_DROP_CONSTRAINT_TYPE, constraintName, "FOREIGN KEY");
            break;
    }
    boolean cascadeOnRefKey = (cascade && conDesc instanceof ReferencedKeyConstraintDescriptor);
    if (!cascadeOnRefKey) {
        dm.invalidateFor(conDesc, DependencyManager.DROP_CONSTRAINT, lcc);
    }
    /*
		** If we had a primary/unique key and it is drop cascade,	
		** drop all the referencing keys now.  We MUST do this AFTER
		** dropping the referenced key because otherwise we would
		** be repeatedly changing the reference count of the referenced
		** key and generating unnecessary I/O.
		*/
    dropConstraint(conDesc, activation, lcc, !cascadeOnRefKey);
    if (cascadeOnRefKey) {
        ForeignKeyConstraintDescriptor fkcd;
        ReferencedKeyConstraintDescriptor cd;
        ConstraintDescriptorList cdl;
        cd = (ReferencedKeyConstraintDescriptor) conDesc;
        cdl = cd.getForeignKeyConstraints(ReferencedKeyConstraintDescriptor.ALL);
        int cdlSize = cdl.size();
        for (int index = 0; index < cdlSize; index++) {
            fkcd = (ForeignKeyConstraintDescriptor) cdl.elementAt(index);
            dm.invalidateFor(fkcd, DependencyManager.DROP_CONSTRAINT, lcc);
            dropConstraint(fkcd, activation, lcc, true);
        }
        /*
			** We told dropConstraintAndIndex not to
			** remove our dependencies, so send an invalidate,
			** and drop the dependencies.
			*/
        dm.invalidateFor(conDesc, DependencyManager.DROP_CONSTRAINT, lcc);
        dm.clearDependencies(lcc, conDesc);
    }
}
Also used : SchemaDescriptor(org.apache.derby.iapi.sql.dictionary.SchemaDescriptor) DependencyManager(org.apache.derby.iapi.sql.depend.DependencyManager) ConstraintDescriptorList(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor) LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) ConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) UUID(org.apache.derby.catalog.UUID) TransactionController(org.apache.derby.iapi.store.access.TransactionController)

Example 7 with ForeignKeyConstraintDescriptor

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

the class SYSFOREIGNKEYSRowFactory method makeRow.

// ///////////////////////////////////////////////////////////////////////////
// 
// METHODS
// 
// ///////////////////////////////////////////////////////////////////////////
/**
 * Make a SYSFOREIGNKEYS row
 *
 * @return	Row suitable for inserting into SYSFOREIGNKEYS.
 *
 * @exception   StandardException thrown on failure
 */
public ExecRow makeRow(TupleDescriptor td, TupleDescriptor parent) throws StandardException {
    DataValueDescriptor col;
    ExecIndexRow row;
    String constraintId = null;
    String keyConstraintId = null;
    String conglomId = null;
    String raDeleteRule = "N";
    String raUpdateRule = "N";
    if (td != null) {
        ForeignKeyConstraintDescriptor cd = (ForeignKeyConstraintDescriptor) td;
        constraintId = cd.getUUID().toString();
        ReferencedKeyConstraintDescriptor refCd = cd.getReferencedConstraint();
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(refCd != null, "this fk returned a null referenced key");
        }
        keyConstraintId = refCd.getUUID().toString();
        conglomId = cd.getIndexUUIDString();
        raDeleteRule = getRefActionAsString(cd.getRaDeleteRule());
        raUpdateRule = getRefActionAsString(cd.getRaUpdateRule());
    }
    /* Build the row  */
    row = getExecutionFactory().getIndexableRow(SYSFOREIGNKEYS_COLUMN_COUNT);
    /* 1st column is CONSTRAINTID (UUID - char(36)) */
    row.setColumn(SYSFOREIGNKEYS_CONSTRAINTID, new SQLChar(constraintId));
    /* 2nd column is CONGLOMERATEID (UUID - char(36)) */
    row.setColumn(SYSFOREIGNKEYS_CONGLOMERATEID, new SQLChar(conglomId));
    /* 3rd column is KEYCONSTRAINTID (UUID - char(36)) */
    row.setColumn(SYSFOREIGNKEYS_KEYCONSTRAINTID, new SQLChar(keyConstraintId));
    // currently, DELETERULE and UPDATERULE are always "R" for restrict
    /* 4th column is DELETERULE char(1) */
    row.setColumn(SYSFOREIGNKEYS_DELETERULE, new SQLChar(raDeleteRule));
    /* 5th column is UPDATERULE char(1) */
    row.setColumn(SYSFOREIGNKEYS_UPDATERULE, new SQLChar(raUpdateRule));
    return row;
}
Also used : ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) SQLChar(org.apache.derby.iapi.types.SQLChar) DataValueDescriptor(org.apache.derby.iapi.types.DataValueDescriptor) ExecIndexRow(org.apache.derby.iapi.sql.execute.ExecIndexRow) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor)

Example 8 with ForeignKeyConstraintDescriptor

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

the class AlterTableConstantAction method truncateTable.

/* 
	 * TRUNCATE TABLE  TABLENAME; (quickly removes all the rows from table and
	 * it's correctponding indexes).
	 * Truncate is implemented by dropping the existing conglomerates(heap,indexes) and recreating a
	 * new ones  with the properties of dropped conglomerates. Currently Store
	 * does not have support to truncate existing conglomerated until store
	 * supports it , this is the only way to do it.
	 * Error Cases: Truncate error cases same as other DDL's statements except
	 * 1)Truncate is not allowed when the table is references by another table.
	 * 2)Truncate is not allowed when there are enabled delete triggers on the table.
	 * Note: Because conglomerate number is changed during recreate process all the statements will be
	 * marked as invalide and they will get recompiled internally on their next
	 * execution. This is okay because truncate makes the number of rows to zero
	 * it may be good idea to recompile them becuase plans are likely to be
	 * incorrect. Recompile is done internally by Derby, user does not have
	 * any effect.
	 */
private void truncateTable() throws StandardException {
    ExecRow emptyHeapRow;
    long newHeapConglom;
    Properties properties = new Properties();
    RowLocation rl;
    if (SanityManager.DEBUG) {
        if (lockGranularity != '\0') {
            SanityManager.THROWASSERT("lockGranularity expected to be '\0', not " + lockGranularity);
        }
        SanityManager.ASSERT(columnInfo == null, "columnInfo expected to be null");
        SanityManager.ASSERT(constraintActions == null, "constraintActions expected to be null");
    }
    // and the ON DELETE action is NO ACTION.
    for (ConstraintDescriptor cd : dd.getConstraintDescriptors(td)) {
        if (cd instanceof ReferencedKeyConstraintDescriptor) {
            final ReferencedKeyConstraintDescriptor rfcd = (ReferencedKeyConstraintDescriptor) cd;
            for (ConstraintDescriptor fkcd : rfcd.getNonSelfReferencingFK(ConstraintDescriptor.ENABLED)) {
                final ForeignKeyConstraintDescriptor fk = (ForeignKeyConstraintDescriptor) fkcd;
                throw StandardException.newException(SQLState.LANG_NO_TRUNCATE_ON_FK_REFERENCE_TABLE, td.getName());
            }
        }
    }
    // truncate is not allowed when there are enabled DELETE triggers
    for (TriggerDescriptor trd : dd.getTriggerDescriptors(td)) {
        if (trd.listensForEvent(TriggerDescriptor.TRIGGER_EVENT_DELETE) && trd.isEnabled()) {
            throw StandardException.newException(SQLState.LANG_NO_TRUNCATE_ON_ENABLED_DELETE_TRIGGERS, td.getName(), trd.getName());
        }
    }
    // gather information from the existing conglomerate to create new one.
    emptyHeapRow = td.getEmptyExecRow();
    compressHeapCC = tc.openConglomerate(td.getHeapConglomerateId(), false, TransactionController.OPENMODE_FORUPDATE, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE);
    rl = compressHeapCC.newRowLocationTemplate();
    // Get the properties on the old heap
    compressHeapCC.getInternalTablePropertySet(properties);
    compressHeapCC.close();
    compressHeapCC = null;
    // create new conglomerate
    newHeapConglom = tc.createConglomerate("heap", emptyHeapRow.getRowArray(), // column sort order - not required for heap
    null, td.getColumnCollationIds(), properties, TransactionController.IS_DEFAULT);
    /* Set up index info to perform truncate on them*/
    getAffectedIndexes();
    if (numIndexes > 0) {
        indexRows = new ExecIndexRow[numIndexes];
        ordering = new ColumnOrdering[numIndexes][];
        collation = new int[numIndexes][];
        for (int index = 0; index < numIndexes; index++) {
            IndexRowGenerator curIndex = compressIRGs[index];
            // create a single index row template for each index
            indexRows[index] = curIndex.getIndexRowTemplate();
            curIndex.getIndexRow(emptyHeapRow, rl, indexRows[index], (FormatableBitSet) null);
            /* For non-unique indexes, we order by all columns + the RID.
				 * For unique indexes, we just order by the columns.
				 * No need to try to enforce uniqueness here as
				 * index should be valid.
				 */
            int[] baseColumnPositions = curIndex.baseColumnPositions();
            boolean[] isAscending = curIndex.isAscending();
            int numColumnOrderings;
            numColumnOrderings = baseColumnPositions.length + 1;
            ordering[index] = new ColumnOrdering[numColumnOrderings];
            collation[index] = curIndex.getColumnCollationIds(td.getColumnDescriptorList());
            for (int ii = 0; ii < numColumnOrderings - 1; ii++) {
                ordering[index][ii] = new IndexColumnOrder(ii, isAscending[ii]);
            }
            ordering[index][numColumnOrderings - 1] = new IndexColumnOrder(numColumnOrderings - 1);
        }
    }
    /*
		** 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);
    // truncate  all indexes
    if (numIndexes > 0) {
        long[] newIndexCongloms = new long[numIndexes];
        for (int index = 0; index < numIndexes; index++) {
            updateIndex(newHeapConglom, dd, index, newIndexCongloms);
        }
    }
    // Update the DataDictionary
    // Get the ConglomerateDescriptor for the heap
    long oldHeapConglom = td.getHeapConglomerateId();
    ConglomerateDescriptor cd = td.getConglomerateDescriptor(oldHeapConglom);
    // Update sys.sysconglomerates with new conglomerate #
    dd.updateConglomerateDescriptor(cd, newHeapConglom, tc);
    // Now that the updated information is available in the system tables,
    // we should invalidate all statements that use the old conglomerates
    dm.invalidateFor(td, DependencyManager.TRUNCATE_TABLE, lcc);
    // Drop the old conglomerate
    tc.dropConglomerate(oldHeapConglom);
    cleanUp();
}
Also used : Properties(java.util.Properties) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor) ConglomerateDescriptor(org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor) TriggerDescriptor(org.apache.derby.iapi.sql.dictionary.TriggerDescriptor) IndexRowGenerator(org.apache.derby.iapi.sql.dictionary.IndexRowGenerator) 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) ExecRow(org.apache.derby.iapi.sql.execute.ExecRow) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) RowLocation(org.apache.derby.iapi.types.RowLocation)

Aggregations

ForeignKeyConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor)8 ReferencedKeyConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor)8 ConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor)5 UUID (org.apache.derby.catalog.UUID)3 ConglomerateDescriptor (org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor)3 ConstraintDescriptorList (org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList)3 TableDescriptor (org.apache.derby.iapi.sql.dictionary.TableDescriptor)3 LanguageConnectionContext (org.apache.derby.iapi.sql.conn.LanguageConnectionContext)2 DependencyManager (org.apache.derby.iapi.sql.depend.DependencyManager)2 DataDictionary (org.apache.derby.iapi.sql.dictionary.DataDictionary)2 SchemaDescriptor (org.apache.derby.iapi.sql.dictionary.SchemaDescriptor)2 ExecIndexRow (org.apache.derby.iapi.sql.execute.ExecIndexRow)2 ExecRow (org.apache.derby.iapi.sql.execute.ExecRow)2 TransactionController (org.apache.derby.iapi.store.access.TransactionController)2 DataValueDescriptor (org.apache.derby.iapi.types.DataValueDescriptor)2 ArrayList (java.util.ArrayList)1 Properties (java.util.Properties)1 ReferencedColumnsDescriptorImpl (org.apache.derby.catalog.types.ReferencedColumnsDescriptorImpl)1 UUIDFactory (org.apache.derby.iapi.services.uuid.UUIDFactory)1 CompilerContext (org.apache.derby.iapi.sql.compile.CompilerContext)1