Search in sources :

Example 26 with TableDescriptor

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

the class DropViewNode method bindStatement.

/**
 *  Bind the drop view node
 *
 * @exception StandardException		Thrown on error
 */
@Override
public void bindStatement() throws StandardException {
    DataDictionary dd = getDataDictionary();
    CompilerContext cc = getCompilerContext();
    TableDescriptor td = dd.getTableDescriptor(getRelativeName(), getSchemaDescriptor(), getLanguageConnectionContext().getTransactionCompile());
    /* 
		 * Statement is dependent on the TableDescriptor 
		 * If td is null, let execution throw the error like
		 * it is before.
		 */
    if (td != null) {
        cc.createDependency(td);
    }
}
Also used : CompilerContext(org.apache.derby.iapi.sql.compile.CompilerContext) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

Example 27 with TableDescriptor

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

the class BaseJoinStrategy method fillInScanArgs2.

final void fillInScanArgs2(MethodBuilder mb, Optimizable innerTable, int bulkFetch, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel) throws StandardException {
    mb.push(innerTable.getBaseTableName());
    // run time statistics.
    if (innerTable.getProperties() != null)
        mb.push(PropertyUtil.sortProperties(innerTable.getProperties()));
    else
        mb.pushNull("java.lang.String");
    ConglomerateDescriptor cd = innerTable.getTrulyTheBestAccessPath().getConglomerateDescriptor();
    if (cd.isConstraint()) {
        DataDictionary dd = innerTable.getDataDictionary();
        TableDescriptor td = innerTable.getTableDescriptor();
        ConstraintDescriptor constraintDesc = dd.getConstraintDescriptor(td, cd.getUUID());
        mb.push(constraintDesc.getConstraintName());
    } else if (cd.isIndex()) {
        mb.push(cd.getConglomerateName());
    } else {
        mb.pushNull("java.lang.String");
    }
    // Whether or not the conglomerate is the backing index for a constraint
    mb.push(cd.isConstraint());
    // tell it whether it's to open for update, which we should do if
    // it's an update or delete statement, or if it's the target
    // table of an updatable cursor.
    mb.push(innerTable.forUpdate());
    mb.push(colRefItem);
    mb.push(indexColItem);
    mb.push(lockMode);
    mb.push(tableLocked);
    mb.push(isolationLevel);
    if (bulkFetch > 0) {
        mb.push(bulkFetch);
        // If the table references LOBs, we want to disable bulk fetching
        // when the cursor is holdable. Otherwise, a commit could close
        // LOBs before they have been returned to the user.
        mb.push(innerTable.hasLargeObjectColumns());
    }
    /* 1 row scans (avoiding 2nd next()) are
 		 * only meaningful for some join strategies.
		 * (Only an issue for outer table, which currently
		 * can only be nested loop, as avoidance of 2nd next
		 * on inner table already factored in to join node.)
		 */
    if (validForOutermostTable()) {
        mb.push(innerTable.isOneRowScan());
    }
    mb.push(innerTable.getTrulyTheBestAccessPath().getCostEstimate().rowCount());
    mb.push(innerTable.getTrulyTheBestAccessPath().getCostEstimate().getEstimatedCost());
}
Also used : ConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary) ConglomerateDescriptor(org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

Example 28 with TableDescriptor

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

the class GenericLanguageConnectionContext method tempTablesAndCommit.

/**
 * Do the necessary work at commit time for temporary tables
 * <p>
 * 1)If a temporary table was marked as dropped in this transaction, then
 *   remove it from the list of temp tables for this connection
 * 2)If a temporary table was not dropped in this transaction, then mark
 *   it's declared savepoint level and modified savepoint level as -1
 * 3)After savepoint fix up, then handle all ON COMMIT DELETE ROWS with
 *   no open held cursor temp tables.
 * <p>
 *
 * @param in_xa_transaction if true, then transaction is an XA transaction,
 *                          and special nested transaction may be necessary
 *                          to cleanup internal containers supporting the
 *                          temp tables at commit time.
 *
 * @exception  StandardException  Standard exception policy.
 */
private void tempTablesAndCommit(boolean in_xa_transaction) throws StandardException {
    // the current savepoint level.
    for (int i = allDeclaredGlobalTempTables.size() - 1; i >= 0; i--) {
        TempTableInfo tempTableInfo = allDeclaredGlobalTempTables.get(i);
        if (tempTableInfo.getDroppedInSavepointLevel() != -1) {
            // this means table was dropped in this unit of work and hence
            // should be removed from valid list of temp tables
            allDeclaredGlobalTempTables.remove(i);
        } else {
            // this table was not dropped in this unit of work, hence set
            // its declaredInSavepointLevel as -1 and also mark it as not
            // modified
            tempTableInfo.setDeclaredInSavepointLevel(-1);
            tempTableInfo.setModifiedInSavepointLevel(-1);
        }
    }
    for (int i = 0; i < allDeclaredGlobalTempTables.size(); i++) {
        TableDescriptor td = allDeclaredGlobalTempTables.get(i).getTableDescriptor();
        if (td.isOnCommitDeleteRows() == false) {
            // do nothing for temp table with ON COMMIT PRESERVE ROWS
            continue;
        } else if (checkIfAnyActivationHasHoldCursor(td.getName()) == false) {
            // temp tables with ON COMMIT DELETE ROWS and
            // no open held cursors
            getDataDictionary().getDependencyManager().invalidateFor(td, DependencyManager.DROP_TABLE, this);
            if (!in_xa_transaction) {
                // delay physical cleanup to after the commit for XA
                // transactions.   In XA the transaction is likely in
                // prepare state at this point and physical changes to
                // store are not allowed until after the commit.
                // Do the work here for non-XA so that fast path does
                // have to do the 2 commits that the XA path will.
                cleanupTempTableOnCommitOrRollback(td, true);
            }
        }
    }
}
Also used : TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

Example 29 with TableDescriptor

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

the class GenericLanguageConnectionContext method dropAllDeclaredGlobalTempTables.

/**
 * Drop all the declared global temporary tables associated with this
 * connection. This gets called when a getConnection() is done on a
 * PooledConnection. This will ensure all the temporary tables declared on
 * earlier connection handle associated with this physical database
 * connection are dropped before a new connection handle is issued on that
 * same physical database connection.
 */
private void dropAllDeclaredGlobalTempTables() throws StandardException {
    if (allDeclaredGlobalTempTables == null)
        return;
    DependencyManager dm = getDataDictionary().getDependencyManager();
    StandardException topLevelStandardException = null;
    // temporary tables and throw them as one chained exception at the end.
    for (int i = 0; i < allDeclaredGlobalTempTables.size(); i++) {
        try {
            TempTableInfo tempTableInfo = allDeclaredGlobalTempTables.get(i);
            TableDescriptor td = tempTableInfo.getTableDescriptor();
            // the following 2 lines of code has been copied from
            // DropTableConstantAction. If there are any changes made there
            // in future, we should check if they need to be made here too.
            dm.invalidateFor(td, DependencyManager.DROP_TABLE, this);
            tran.dropConglomerate(td.getHeapConglomerateId());
        } catch (StandardException e) {
            if (topLevelStandardException == null) {
                // always keep the first exception unchanged
                topLevelStandardException = e;
            } else {
                try {
                    // Try to create a chain of exceptions. If successful,
                    // the current exception is the top-level exception,
                    // and the previous exception the cause of it.
                    e.initCause(topLevelStandardException);
                    topLevelStandardException = e;
                } catch (IllegalStateException ise) {
                // initCause() has already been called on e. We don't
                // expect this to happen, but if it happens, just skip
                // the current exception from the chain. This is safe
                // since we always keep the first exception.
                }
            }
        }
    }
    allDeclaredGlobalTempTables = null;
    try {
        internalCommit(true);
    } catch (StandardException e) {
        // do the same chaining as above
        if (topLevelStandardException == null) {
            topLevelStandardException = e;
        } else {
            try {
                e.initCause(topLevelStandardException);
                topLevelStandardException = e;
            } catch (IllegalStateException ise) {
            /* ignore */
            }
        }
    }
    if (topLevelStandardException != null)
        throw topLevelStandardException;
}
Also used : StandardException(org.apache.derby.shared.common.error.StandardException) DependencyManager(org.apache.derby.iapi.sql.depend.DependencyManager) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

Example 30 with TableDescriptor

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

the class CreateConstraintConstantAction method executeConstantAction.

// INTERFACE METHODS
/**
 *	This is the guts of the Execution-time logic for CREATE CONSTRAINT.
 *  <P>
 *  A constraint is represented as:
 *  <UL>
 *  <LI> ConstraintDescriptor.
 *  </UL>
 *  If a backing index is required then the index will
 *  be created through an CreateIndexConstantAction setup
 *  by the compiler.
 *  <BR>
 *  Dependencies are created as:
 *  <UL>
 *  <LI> ConstraintDescriptor depends on all the providers collected
 *  at compile time and passed into the constructor.
 *  <LI> For a FOREIGN KEY constraint ConstraintDescriptor depends
 *  on the ConstraintDescriptor for the referenced constraints
 *  and the privileges required to create the constraint.
 *  </UL>
 *
 *  @see ConstraintDescriptor
 *  @see CreateIndexConstantAction
 *	@see ConstantAction#executeConstantAction
 *
 * @exception StandardException		Thrown on failure
 */
public void executeConstantAction(Activation activation) throws StandardException {
    ConglomerateDescriptor conglomDesc = null;
    ConglomerateDescriptor[] conglomDescs = null;
    ConstraintDescriptor conDesc = null;
    TableDescriptor td = null;
    UUID indexId = null;
    String uniqueName;
    String backingIndexName;
    /* RESOLVE - blow off not null constraints for now (and probably for ever) */
    if (constraintType == DataDictionary.NOTNULL_CONSTRAINT) {
        return;
    }
    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    DependencyManager dm = dd.getDependencyManager();
    TransactionController tc = lcc.getTransactionExecute();
    cf = lcc.getLanguageConnectionFactory().getClassFactory();
    /*
		** 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);
    /* 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 sd = dd.getSchemaDescriptor(schemaName, tc, true);
    /* Try to get the TableDescriptor from
		 * the Activation. We will go to the
		 * DD if not there. (It should always be
		 * there except when in a target.)
		 */
    td = activation.getDDLTableDescriptor();
    if (td == null) {
        /* tableId will be non-null if adding a
			 * constraint to an existing table.
			 */
        if (tableId != null) {
            td = dd.getTableDescriptor(tableId);
        } else {
            td = dd.getTableDescriptor(tableName, sd, tc);
        }
        if (td == null) {
            throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tableName);
        }
        activation.setDDLTableDescriptor(td);
    }
    /* Generate the UUID for the backing index.  This will become the
		 * constraint's name, if no name was specified.
		 */
    UUIDFactory uuidFactory = dd.getUUIDFactory();
    UUID constrId = uuidFactory.createUUID();
    /* Create the index, if there's one for this constraint */
    if (indexAction != null) {
        if (indexAction.getIndexName() == null) {
            /* Set the index name */
            backingIndexName = uuidFactory.createUUID().toString();
            indexAction.setIndexName(backingIndexName);
        } else {
            backingIndexName = indexAction.getIndexName();
        }
        indexAction.setConstraintID(constrId);
        /* Create the index */
        indexAction.executeConstantAction(activation);
        /* Get the conglomerate descriptor for the backing index */
        conglomDescs = td.getConglomerateDescriptors();
        for (int index = 0; index < conglomDescs.length; index++) {
            conglomDesc = conglomDescs[index];
            /* Check for conglomerate being an index first, since
				 * name is null for heap.
				 */
            if (conglomDesc.isIndex() && backingIndexName.equals(conglomDesc.getConglomerateName())) {
                break;
            }
        }
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(conglomDesc != null, "conglomDesc is expected to be non-null after search for backing index");
            SanityManager.ASSERT(conglomDesc.isIndex(), "conglomDesc is expected to be indexable after search for backing index");
            SanityManager.ASSERT(conglomDesc.getConglomerateName().equals(backingIndexName), "conglomDesc name expected to be the same as backing index name after search for backing index");
        }
        indexId = conglomDesc.getUUID();
    }
    boolean[] defaults = new boolean[] { ConstraintDefinitionNode.DEFERRABLE_DEFAULT, ConstraintDefinitionNode.INITIALLY_DEFERRED_DEFAULT, ConstraintDefinitionNode.ENFORCED_DEFAULT };
    for (int i = 0; i < characteristics.length; i++) {
        if (characteristics[i] != defaults[i]) {
            dd.checkVersion(DataDictionary.DD_VERSION_DERBY_10_11, "DEFERRED CONSTRAINTS");
            if (constraintType == DataDictionary.NOTNULL_CONSTRAINT || !characteristics[2]) /* not enforced */
            {
                // Remove when feature DERBY-532 is completed
                if (!PropertyUtil.getSystemProperty("derby.constraintsTesting", "false").equals("true")) {
                    throw StandardException.newException(SQLState.NOT_IMPLEMENTED, "non-default constraint characteristics");
                }
            }
        }
    }
    /* Now, lets create the constraint descriptor */
    DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator();
    switch(constraintType) {
        case DataDictionary.PRIMARYKEY_CONSTRAINT:
            conDesc = ddg.newPrimaryKeyConstraintDescriptor(td, constraintName, // deferable,
            characteristics[0], // initiallyDeferred,
            characteristics[1], // int[],
            genColumnPositions(td, false), constrId, indexId, sd, characteristics[2], // referenceCount
            0);
            dd.addConstraintDescriptor(conDesc, tc);
            break;
        case DataDictionary.UNIQUE_CONSTRAINT:
            conDesc = ddg.newUniqueConstraintDescriptor(td, constraintName, // deferable,
            characteristics[0], // initiallyDeferred,
            characteristics[1], // int[],
            genColumnPositions(td, false), constrId, indexId, sd, characteristics[2], // referenceCount
            0);
            dd.addConstraintDescriptor(conDesc, tc);
            break;
        case DataDictionary.CHECK_CONSTRAINT:
            conDesc = ddg.newCheckConstraintDescriptor(td, constraintName, // deferable,
            characteristics[0], // initiallyDeferred,
            characteristics[1], constrId, constraintText, // int[],
            new ReferencedColumnsDescriptorImpl(genColumnPositions(td, false)), sd, characteristics[2]);
            dd.addConstraintDescriptor(conDesc, tc);
            storeConstraintDependenciesOnPrivileges(activation, conDesc, null, providerInfo);
            break;
        case DataDictionary.FOREIGNKEY_CONSTRAINT:
            ReferencedKeyConstraintDescriptor referencedConstraint = DDUtils.locateReferencedConstraint(dd, td, constraintName, columnNames, otherConstraintInfo);
            DDUtils.validateReferentialActions(dd, td, constraintName, otherConstraintInfo, columnNames);
            conDesc = ddg.newForeignKeyConstraintDescriptor(td, constraintName, // deferable,
            characteristics[0], // initiallyDeferred,
            characteristics[1], // int[],
            genColumnPositions(td, false), constrId, indexId, sd, referencedConstraint, characteristics[2], otherConstraintInfo.getReferentialActionDeleteRule(), otherConstraintInfo.getReferentialActionUpdateRule());
            // try to create the constraint first, because it
            // is expensive to do the bulk check, find obvious
            // errors first
            dd.addConstraintDescriptor(conDesc, tc);
            /* No need to do check if we're creating a 
				 * table.
				 */
            if ((!forCreateTable) && dd.activeConstraint(conDesc)) {
                validateFKConstraint(activation, tc, dd, (ForeignKeyConstraintDescriptor) conDesc, referencedConstraint, ((CreateIndexConstantAction) indexAction).getIndexTemplateRow());
            }
            /* Create stored dependency on the referenced constraint */
            dm.addDependency(conDesc, referencedConstraint, lcc.getContextManager());
            // store constraint's dependency on REFERENCES privileges in the dependeny system
            storeConstraintDependenciesOnPrivileges(activation, conDesc, referencedConstraint.getTableId(), providerInfo);
            break;
        case DataDictionary.MODIFY_CONSTRAINT:
            throw StandardException.newException(SQLState.NOT_IMPLEMENTED, "ALTER CONSTRAINT");
        default:
            if (SanityManager.DEBUG) {
                SanityManager.THROWASSERT("contraintType (" + constraintType + ") has unexpected value");
            }
            break;
    }
    /* Create stored dependencies for each provider */
    if (providerInfo != null) {
        for (int ix = 0; ix < providerInfo.length; ix++) {
            Provider provider = null;
            /* We should always be able to find the Provider */
            provider = (Provider) providerInfo[ix].getDependableFinder().getDependable(dd, providerInfo[ix].getObjectId());
            dm.addDependency(conDesc, provider, lcc.getContextManager());
        }
    }
    /* Finally, invalidate off of the table descriptor(s)
		 * to ensure that any dependent statements get
		 * re-compiled.
		 */
    if (!forCreateTable) {
        dm.invalidateFor(td, DependencyManager.CREATE_CONSTRAINT, lcc);
    }
    if (constraintType == DataDictionary.FOREIGNKEY_CONSTRAINT) {
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(conDesc != null, "conDesc expected to be non-null");
            if (!(conDesc instanceof ForeignKeyConstraintDescriptor)) {
                SanityManager.THROWASSERT("conDesc expected to be instance of ForeignKeyConstraintDescriptor, not " + conDesc.getClass().getName());
            }
        }
        dm.invalidateFor(((ForeignKeyConstraintDescriptor) conDesc).getReferencedConstraint().getTableDescriptor(), DependencyManager.CREATE_CONSTRAINT, lcc);
    }
    this.constraintId = constrId;
}
Also used : SchemaDescriptor(org.apache.derby.iapi.sql.dictionary.SchemaDescriptor) UUIDFactory(org.apache.derby.iapi.services.uuid.UUIDFactory) DependencyManager(org.apache.derby.iapi.sql.depend.DependencyManager) ReferencedColumnsDescriptorImpl(org.apache.derby.catalog.types.ReferencedColumnsDescriptorImpl) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary) ConglomerateDescriptor(org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor) Provider(org.apache.derby.iapi.sql.depend.Provider) DataDescriptorGenerator(org.apache.derby.iapi.sql.dictionary.DataDescriptorGenerator) LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) ReferencedKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ReferencedKeyConstraintDescriptor) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor) 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)

Aggregations

TableDescriptor (org.apache.derby.iapi.sql.dictionary.TableDescriptor)80 SchemaDescriptor (org.apache.derby.iapi.sql.dictionary.SchemaDescriptor)27 DataDictionary (org.apache.derby.iapi.sql.dictionary.DataDictionary)23 UUID (org.apache.derby.catalog.UUID)22 LanguageConnectionContext (org.apache.derby.iapi.sql.conn.LanguageConnectionContext)20 ColumnDescriptor (org.apache.derby.iapi.sql.dictionary.ColumnDescriptor)20 TransactionController (org.apache.derby.iapi.store.access.TransactionController)20 ConglomerateDescriptor (org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor)19 DependencyManager (org.apache.derby.iapi.sql.depend.DependencyManager)11 ColumnDescriptorList (org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList)11 ConstraintDescriptor (org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor)9 DataValueDescriptor (org.apache.derby.iapi.types.DataValueDescriptor)9 StandardException (org.apache.derby.shared.common.error.StandardException)9 FormatableBitSet (org.apache.derby.iapi.services.io.FormatableBitSet)7 DataDescriptorGenerator (org.apache.derby.iapi.sql.dictionary.DataDescriptorGenerator)7 ExecRow (org.apache.derby.iapi.sql.execute.ExecRow)7 ArrayList (java.util.ArrayList)6 AliasDescriptor (org.apache.derby.iapi.sql.dictionary.AliasDescriptor)6 ConstraintDescriptorList (org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList)6 ViewDescriptor (org.apache.derby.iapi.sql.dictionary.ViewDescriptor)6