Examples of DataDictionary


Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

    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);
   
    /*
    ** First go, don't drop unique or primary keys.
    ** This will ensure that self-referential constraints
    ** will work ok, even if not cascading.
     */
    /* 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);
      cd.drop(lcc, true);
    }

    /*
     ** Referenced keys (unique or pk) constraints only
    */
    /* 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.
      */
      cd.drop(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.
        */
 
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

    LanguageConnectionContext lcc       = ConnectionUtil.getCurrentLCC();
    TransactionController     tc        = lcc.getTransactionExecute();

    try
        {
            DataDictionary data_dictionary = lcc.getDataDictionary();
            SchemaDescriptor sd =
                data_dictionary.getSchemaDescriptor(schema, tc, true);
            TableDescriptor  td =
                data_dictionary.getTableDescriptor(tablename, sd, tc);

            if (td != null && td.getTableType() == TableDescriptor.VTI_TYPE)
            {
                return;
            }
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

        ** Tell the data dictionary that we are about to do
        ** a bunch of "get" operations that must be consistent with
        ** each other.
        */
       
        DataDictionary dataDictionary = lcc.getDataDictionary();

        int ddMode = dataDictionary == null ? 0 : dataDictionary.startReading(lcc);

        try
        {
          // start a nested transaction -- all locks acquired by bind
          // and optimize will be released when we end the nested
          // transaction.
          lcc.beginNestedTransaction(true);

          qt.bindStatement();
          bindTime = getCurrentTimeMillis(lcc);

                    // Call user-written tree-printer if it exists
                    walkAST( lcc, qt, ASTVisitor.AFTER_BIND);

          if (SanityManager.DEBUG)
          {
            if (SanityManager.DEBUG_ON("DumpBindTree"))
            {
              SanityManager.GET_DEBUG_STREAM().print(
                "\n\n============BIND===========\n\n");
              qt.treePrint();
              lcc.getPrintedObjectsMap().clear();
            }

            if (SanityManager.DEBUG_ON("StopAfterBinding")) {
              throw StandardException.newException(SQLState.LANG_STOP_AFTER_BINDING);
            }
          }

          //Derby424 - In order to avoid caching select statements referencing
          // any SESSION schema objects (including statements referencing views
          // in SESSION schema), we need to do the SESSION schema object check
          // here. 
          //a specific eg for statement referencing a view in SESSION schema
          //CREATE TABLE t28A (c28 int)
          //INSERT INTO t28A VALUES (280),(281)
          //CREATE VIEW SESSION.t28v1 as select * from t28A
          //SELECT * from SESSION.t28v1 should show contents of view and we
          // should not cache this statement because a user can later define
          // a global temporary table with the same name as the view name.
          //Following demonstrates that
          //DECLARE GLOBAL TEMPORARY TABLE SESSION.t28v1(c21 int, c22 int) not
          //     logged
          //INSERT INTO SESSION.t28v1 VALUES (280,1),(281,2)
          //SELECT * from SESSION.t28v1 should show contents of global temporary
          //table and not the view.  Since this select statement was not cached
          // earlier, it will be compiled again and will go to global temporary
          // table to fetch data. This plan will not be cached either because
          // select statement is using SESSION schema object.
          //
          //Following if statement makes sure that if the statement is
          // referencing SESSION schema objects, then we do not want to cache it.
          // We will remove the entry that was made into the cache for
          //this statement at the beginning of the compile phase.
          //The reason we do this check here rather than later in the compile
          // phase is because for a view, later on, we loose the information that
          // it was referencing SESSION schema because the reference
          //view gets replaced with the actual view definition. Right after
          // binding, we still have the information on the view and that is why
          // we do the check here.
          if (preparedStmt.referencesSessionSchema(qt)) {
            if (foundInCache)
              ((GenericLanguageConnectionContext)lcc).removeStatement(this);
          }
         
          qt.optimizeStatement();

          optimizeTime = getCurrentTimeMillis(lcc);

                    // Call user-written tree-printer if it exists
                    walkAST( lcc, qt, ASTVisitor.AFTER_OPTIMIZE);

          // Statement logging if lcc.getLogStatementText() is true
          if (istream != null)
          {
            String xactId = lcc.getTransactionExecute().getActiveStateTxIdString();
            istream.printlnWithHeader(LanguageConnectionContext.xidStr +
                          xactId +
                          "), " +
                          LanguageConnectionContext.lccStr +
                          lcc.getInstanceNumber() +
                          "), " +
                          LanguageConnectionContext.dbnameStr +
                          lcc.getDbname() +
                          "), " +
                          LanguageConnectionContext.drdaStr +
                          lcc.getDrdaID() +
                          "), End compiling prepared statement: " +
                          getSource() +
                          " :End prepared statement");
          }
        }

        catch (StandardException se)
        {
          lcc.commitNestedTransaction();

          // Statement logging if lcc.getLogStatementText() is true
          if (istream != null)
          {
            String xactId = lcc.getTransactionExecute().getActiveStateTxIdString();
            istream.printlnWithHeader(LanguageConnectionContext.xidStr +
                          xactId +
                          "), " +
                          LanguageConnectionContext.lccStr +
                          lcc.getInstanceNumber() +
                          "), " +
                          LanguageConnectionContext.dbnameStr +
                          lcc.getDbname() +
                          "), " +
                          LanguageConnectionContext.drdaStr +
                          lcc.getDrdaID() +
                          "), Error compiling prepared statement: " +
                          getSource() +
                          " :End prepared statement");
          }
          throw se;
        }

        finally
        {
          /* Tell the data dictionary that we are done reading */
          if (dataDictionary != null)
          dataDictionary.doneReading(ddMode, lcc);
        }

        /* we need to move the commit of nested sub-transaction
         * after we mark PS valid, during compilation, we might need
         * to get some lock to synchronize with another thread's DDL
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

  {
    TableDescriptor td;
    ConglomerateDescriptor cd;

    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    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);

    // need to lock heap in exclusive mode first.  Because we can't first
    // shared lock the row in SYSCONGLOMERATES and later exclusively lock
    // it, this is potential deadlock (track 879).  Also td need to be
    // gotten after we get the lock, a concurrent thread could be modifying
    // table shape (track 3804, 3825)

    // older version (or 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 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) ;

    /* Get the conglomerate descriptor for the index, along
     * with an exclusive row lock on the row in sys.sysconglomerates
     * in order to ensure that no one else compiles against the
     * index.
     */
    cd = dd.getConglomerateDescriptor(indexName, sd, true);

    if (cd == null)
    {
      throw StandardException.newException(SQLState.LANG_INDEX_NOT_FOUND_DURING_EXECUTION, fullIndexName);
    }
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

    SchemaDescriptor      schemaDescriptor;
    ColumnDescriptor      columnDescriptor;
    ExecRow            template;

    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    DependencyManager dm = dd.getDependencyManager();
    TransactionController tc = lcc.getTransactionExecute();

    /* Mark the activation as being for create table */
    activation.setForCreateTable();

        // setup for create conglomerate call:
        //   o create row template to tell the store what type of rows this
        //     table holds.
        //   o create array of collation id's to tell collation id of each
        //     column in table.
    template            = RowUtil.getEmptyValueRow(columnInfo.length, lcc);
        int[] collation_ids = new int[columnInfo.length];

    for (int ix = 0; ix < columnInfo.length; ix++)
    {
            ColumnInfo  col_info = columnInfo[ix];

            // Get a template value for each column

      if (col_info.defaultValue != null)
            {
                /* If there is a default value, use it, otherwise use null */
        template.setColumn(ix + 1, col_info.defaultValue);
            }
      else
            {
        template.setColumn(ix + 1, col_info.dataType.getNull());
            }

            // get collation info for each column.

            collation_ids[ix] = col_info.dataType.getCollationType();
    }


    /* create the conglomerate to hold the table's rows
     * RESOLVE - If we ever have a conglomerate creator
     * that lets us specify the conglomerate number then
     * we will need to handle it here.
     */
    long conglomId = tc.createConglomerate(
        "heap", // we're requesting a heap conglomerate
        template.getRowArray(), // row template
        null, //column sort order - not required for heap
                collation_ids,
        properties, // properties
        tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ?
                    (TransactionController.IS_TEMPORARY |
                     TransactionController.IS_KEPT) :
                        TransactionController.IS_DEFAULT);

    /*
    ** 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.
    */
    if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE )
      dd.startWriting(lcc);

    SchemaDescriptor sd;
    if (tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE)
      sd = dd.getSchemaDescriptor(schemaName, tc, true);
    else
      sd = DDLConstantAction.getSchemaDescriptorForCreate(dd, activation, schemaName);

    //
    // Create a new table descriptor.
    //
    DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator();

    if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE )
    {
      td = ddg.newTableDescriptor(tableName, sd, tableType, lockGranularity);
      dd.addDescriptor(td, sd, DataDictionary.SYSTABLES_CATALOG_NUM, false, tc);
    } else
    {
      td = ddg.newTableDescriptor(tableName, sd, tableType, onCommitDeleteRows, onRollbackDeleteRows);
      td.setUUID(dd.getUUIDFactory().createUUID());
    }
    toid = td.getUUID();

    // Save the TableDescriptor off in the Activation
    activation.setDDLTableDescriptor(td);

    /* NOTE: We must write the columns out to the system
     * tables before any of the conglomerates, including
     * the heap, since we read the columns before the
     * conglomerates when building a TableDescriptor.
     * This will hopefully reduce the probability of
     * a deadlock involving those system tables.
     */
   
    // for each column, stuff system.column
    int index = 1;

    ColumnDescriptor[] cdlArray = new ColumnDescriptor[columnInfo.length];
    for (int ix = 0; ix < columnInfo.length; ix++)
    {
      UUID defaultUUID = columnInfo[ix].newDefaultUUID;

      /* Generate a UUID for the default, if one exists
       * and there is no default id yet.
       */
      if (columnInfo[ix].defaultInfo != null &&
        defaultUUID == null)
      {
        defaultUUID = dd.getUUIDFactory().createUUID();
      }

      if (columnInfo[ix].autoincInc != 0)//dealing with autoinc column
      columnDescriptor = new ColumnDescriptor(
                           columnInfo[ix].name,
                   index++,
                   columnInfo[ix].dataType,
                   columnInfo[ix].defaultValue,
                   columnInfo[ix].defaultInfo,
                   td,
                   defaultUUID,
                   columnInfo[ix].autoincStart,
                   columnInfo[ix].autoincInc,
                   columnInfo[ix].autoinc_create_or_modify_Start_Increment
                 );
      else
        columnDescriptor = new ColumnDescriptor(
                       columnInfo[ix].name,
               index++,
               columnInfo[ix].dataType,
               columnInfo[ix].defaultValue,
               columnInfo[ix].defaultInfo,
               td,
               defaultUUID,
               columnInfo[ix].autoincStart,
               columnInfo[ix].autoincInc
             );

      cdlArray[ix] = columnDescriptor;
    }

    if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE )
    {
      dd.addDescriptorArray(cdlArray, td,
                DataDictionary.SYSCOLUMNS_CATALOG_NUM,
                false, tc);
    }

    // now add the column descriptors to the table.
    ColumnDescriptorList cdl = td.getColumnDescriptorList();
    for (int i = 0; i < cdlArray.length; i++)
      cdl.add(cdlArray[i]);
        
    //
    // Create a conglomerate desciptor with the conglomId filled in and
    // add it.
    //
    // RESOLVE: Get information from the conglomerate descriptor which
    //          was provided.
    //
    ConglomerateDescriptor cgd =
      ddg.newConglomerateDescriptor(conglomId, null, false, null, false, null, toid,
                      sd.getUUID());
    if ( tableType != TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE )
    {
      dd.addDescriptor(cgd, sd, DataDictionary.SYSCONGLOMERATES_CATALOG_NUM,
             false, tc);
    }

    // add the newly added conglomerate to the table descriptor
    ConglomerateDescriptorList conglomList = td.getConglomerateDescriptorList();
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

    {
      return;
    }

    LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
    DataDictionary dd = lcc.getDataDictionary();
    DependencyManager dm = dd.getDependencyManager();
    TransactionController tc = lcc.getTransactionExecute();

    cf = lcc.getLanguageConnectionFactory().getClassFactory();

    /* Remember whether or not we are doing a create table */
    forCreateTable = activation.getForCreateTable();

    /*
    ** 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);
      }

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


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

    UUID constraintId = uuidFactory.createUUID();

    /* Now, lets create the constraint descriptor */
    DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator();
    switch (constraintType)
    {
      case DataDictionary.PRIMARYKEY_CONSTRAINT:
        conDesc = ddg.newPrimaryKeyConstraintDescriptor(
                td, constraintName,
                false, //deferable,
                false, //initiallyDeferred,
                genColumnPositions(td, false), //int[],
                constraintId,
                indexId,
                sd,
                enabled,
                0        // referenceCount
                );
        dd.addConstraintDescriptor(conDesc, tc);
        break;

      case DataDictionary.UNIQUE_CONSTRAINT:
        conDesc = ddg.newUniqueConstraintDescriptor(
                td, constraintName,
                false, //deferable,
                false, //initiallyDeferred,
                genColumnPositions(td, false), //int[],
                constraintId,
                indexId,
                sd,
                enabled,
                0        // referenceCount
                );
        dd.addConstraintDescriptor(conDesc, tc);
        break;

      case DataDictionary.CHECK_CONSTRAINT:
        conDesc = ddg.newCheckConstraintDescriptor(
                td, constraintName,
                false, //deferable,
                false, //initiallyDeferred,
                constraintId,
                constraintText,
                new ReferencedColumnsDescriptorImpl(genColumnPositions(td, false)), //int[],
                sd,
                enabled
                );
        dd.addConstraintDescriptor(conDesc, tc);
        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,
                false, //deferable,
                false, //initiallyDeferred,
                genColumnPositions(td, false), //int[],
                constraintId,
                indexId,
                sd,
                referencedConstraint,
                enabled,
                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(tc,
                     dd,
                     (ForeignKeyConstraintDescriptor)conDesc,
                     referencedConstraint,
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

                                   boolean asBackgroundTask)
            throws StandardException {
        TransactionController tc = lcc.getTransactionExecute();
        trace(1, "writing new stats (xid=" + tc.getTransactionIdString() + ")");
        UUID table = td.getUUID();
        DataDictionary dd = lcc.getDataDictionary();
        UUIDFactory uf = dd.getUUIDFactory();

        // Update the heap row count estimate.
        setHeapRowEstimate(tc, td.getHeapConglomerateId(), numRows);
        // Invalidate statments accessing the given table.
        // Note that due to retry logic, swithcing the data dictionary to
        // write mode is done inside invalidateStatements.
        invalidateStatements(lcc, td, asBackgroundTask);
        // Drop existing index statistics for this index.
        dd.dropStatisticsDescriptors(table, index, tc);

        // Don't write statistics if the table is empty.
        if (numRows == 0) {
            trace(2, "empty table, no stats written");
        } else {
            // Construct and add the statistics entries.
            for (int i=0; i < cardinality.length; i++) {
                StatisticsDescriptor statDesc = new StatisticsDescriptor(
                        dd, uf.createUUID(), index, table, "I",
                     new StatisticsImpl(numRows, cardinality[i]),
                     i+1);
                dd.addDescriptor(statDesc, null,
                        DataDictionary.SYSSTATISTICS_CATALOG_NUM, true, tc);
            }

            // Log some information.
            ConglomerateDescriptor cd = dd.getConglomerateDescriptor(index);
            log(asBackgroundTask, td,
                    "wrote stats for index "  +
                    (cd == null ? "n/a" : cd.getDescriptorName()) +
                    " (" + index + "): rows=" + numRows +
                    ", card=" + cardToStr(cardinality));
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

    private void invalidateStatements(LanguageConnectionContext lcc,
                                      TableDescriptor td,
                                      boolean asBackgroundTask)
            throws StandardException {
        // Invalidate compiled statements accessing the table.
        DataDictionary dd = lcc.getDataDictionary();
        DependencyManager dm = dd.getDependencyManager();
        boolean inWrite = false;
        int retries = 0;
        while (true) {
            try {
                if (!inWrite) {
                    dd.startWriting(lcc);
                    inWrite = true;
                }
                dm.invalidateFor(
                        td, DependencyManager.UPDATE_STATISTICS, lcc);
                trace(1, "invalidation completed");
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

        TransactionController tc = lcc.getTransactionExecute();

    try {

    // find the DataDictionary
    DataDictionary dd = lcc.getDataDictionary();


    // get the SchemaDescriptor
    SchemaDescriptor sd = dd.getSchemaDescriptor(schemaName, tc, true);
    if ( !isIndex)
    {
      // get the TableDescriptor for the table
      TableDescriptor td = dd.getTableDescriptor(conglomerateName, sd);

      // Return an empty Properties if table does not exist or if it is for a view.
      if ((td == null) || td.getTableType() == TableDescriptor.VIEW_TYPE) { return new Properties(); }

      conglomerateNumber = td.getHeapConglomerateId();
    }
    else
    {
      // get the ConglomerateDescriptor for the index
      ConglomerateDescriptor cd = dd.getConglomerateDescriptor(conglomerateName, sd, false);

      // Return an empty Properties if index does not exist
      if (cd == null) { return new Properties(); }

      conglomerateNumber = cd.getConglomerateNumber();
View Full Code Here

Examples of org.apache.derby.iapi.sql.dictionary.DataDictionary

   *                  exception is thrown..
   */
  public static boolean checkTable(String schemaName, String tableName)
            throws SQLException
  {
    DataDictionary      dd;
    TableDescriptor      td;
    long          baseRowCount = -1;
    TransactionController  tc;
    ConglomerateDescriptor  heapCD;
    ConglomerateDescriptor  indexCD;
    ExecRow          baseRow;
    ExecRow          indexRow;
    RowLocation        rl = null;
    RowLocation        scanRL = null;
    ScanController      scan = null;
    int[]          baseColumnPositions;
    int            baseColumns = 0;
    DataValueFactory    dvf;
    long          indexRows;
    ConglomerateController  baseCC = null;
    ConglomerateController  indexCC = null;
    SchemaDescriptor    sd;
    ConstraintDescriptor  constraintDesc;

    LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC();
    tc = lcc.getTransactionExecute();

    try {

            dd = lcc.getDataDictionary();

            dvf = lcc.getDataValueFactory();
           
            ExecutionFactory ef = lcc.getLanguageConnectionFactory().getExecutionFactory();

            sd = dd.getSchemaDescriptor(schemaName, tc, true);
            td = dd.getTableDescriptor(tableName, sd);

            if (td == null)
            {
                throw StandardException.newException(
                    SQLState.LANG_TABLE_NOT_FOUND,
                    schemaName + "." + tableName);
            }

            /* Skip views */
            if (td.getTableType() == TableDescriptor.VIEW_TYPE)
            {
                return true;
            }

      /* Open the heap for reading */
      baseCC = tc.openConglomerate(
                  td.getHeapConglomerateId(), false, 0,
                TransactionController.MODE_TABLE,
              TransactionController.ISOLATION_SERIALIZABLE);

      /* Check the consistency of the heap */
      baseCC.checkConsistency();

      heapCD = td.getConglomerateDescriptor(td.getHeapConglomerateId());

      /* Get a row template for the base table */
      baseRow = ef.getValueRow(td.getNumberOfColumns());

      /* Fill the row with nulls of the correct type */
      ColumnDescriptorList cdl = td.getColumnDescriptorList();
      int           cdlSize = cdl.size();

      for (int index = 0; index < cdlSize; index++)
      {
        ColumnDescriptor cd = (ColumnDescriptor) cdl.elementAt(index);
        baseRow.setColumn(cd.getPosition(),
                    cd.getType().getNull());
      }

      /* Look at all the indexes on the table */
      ConglomerateDescriptor[] cds = td.getConglomerateDescriptors();
      for (int index = 0; index < cds.length; index++)
      {
        indexCD = cds[index];
        /* Skip the heap */
        if ( ! indexCD.isIndex())
          continue;

        /* Check the internal consistency of the index */
        indexCC =
              tc.openConglomerate(
                indexCD.getConglomerateNumber(),
                        false,
              0,
            TransactionController.MODE_TABLE,
                      TransactionController.ISOLATION_SERIALIZABLE);

        indexCC.checkConsistency();
        indexCC.close();
        indexCC = null;

        /* if index is for a constraint check that the constraint exists */

        if (indexCD.isConstraint())
        {
          constraintDesc = dd.getConstraintDescriptor(td, indexCD.getUUID());
          if (constraintDesc == null)
          {
            throw StandardException.newException(
                    SQLState.LANG_OBJECT_NOT_FOUND,
                    "CONSTRAINT for INDEX",
                    indexCD.getConglomerateName());
          }
        }

        /*
        ** Set the base row count when we get to the first index.
        ** We do this here, rather than outside the index loop, so
        ** we won't do the work of counting the rows in the base table
        ** if there are no indexes to check.
        */
        if (baseRowCount < 0)
        {
          scan = tc.openScan(heapCD.getConglomerateNumber(),
                    false,  // hold
                    0,    // not forUpdate
                      TransactionController.MODE_TABLE,
                      TransactionController.ISOLATION_SERIALIZABLE,
                                        RowUtil.EMPTY_ROW_BITSET,
                    null,  // startKeyValue
                    0,    // not used with null start posn.
                    null,  // qualifier
                    null,  // stopKeyValue
                    0);    // not used with null stop posn.

          /* Also, get the row location template for index rows */
          rl = scan.newRowLocationTemplate();
          scanRL = scan.newRowLocationTemplate();

          for (baseRowCount = 0; scan.next(); baseRowCount++)
            /* Empty statement */

          scan.close();
          scan = null;
        }

        baseColumnPositions =
            indexCD.getIndexDescriptor().baseColumnPositions();
        baseColumns = baseColumnPositions.length;

        FormatableBitSet indexColsBitSet = new FormatableBitSet();
        for (int i = 0; i < baseColumns; i++)
        {
          indexColsBitSet.grow(baseColumnPositions[i]);
          indexColsBitSet.set(baseColumnPositions[i] - 1);
        }

        /* Get one row template for the index scan, and one for the fetch */
        indexRow = ef.getValueRow(baseColumns + 1);

        /* Fill the row with nulls of the correct type */
        for (int column = 0; column < baseColumns; column++)
        {
          /* Column positions in the data dictionary are one-based */
           ColumnDescriptor cd = td.getColumnDescriptor(baseColumnPositions[column]);
          indexRow.setColumn(column + 1,
                      cd.getType().getNull());
        }

        /* Set the row location in the last column of the index row */
        indexRow.setColumn(baseColumns + 1, rl);

        /* Do a full scan of the index */
        scan = tc.openScan(indexCD.getConglomerateNumber(),
                  false,  // hold
                  0,    // not forUpdate
                    TransactionController.MODE_TABLE,
                        TransactionController.ISOLATION_SERIALIZABLE,
                  (FormatableBitSet) null,
                  null,  // startKeyValue
                  0,    // not used with null start posn.
                  null,  // qualifier
                  null,  // stopKeyValue
                  0);    // not used with null stop posn.

        DataValueDescriptor[] baseRowIndexOrder =
                    new DataValueDescriptor[baseColumns];
        DataValueDescriptor[] baseObjectArray = baseRow.getRowArray();

        for (int i = 0; i < baseColumns; i++)
        {
          baseRowIndexOrder[i] = baseObjectArray[baseColumnPositions[i] - 1];
        }
     
        /* Get the index rows and count them */
        for (indexRows = 0; scan.fetchNext(indexRow.getRowArray()); indexRows++)
        {
          /*
          ** Get the base row using the RowLocation in the index row,
          ** which is in the last column. 
          */
          RowLocation baseRL = (RowLocation) indexRow.getColumn(baseColumns + 1);

          boolean base_row_exists =
                    baseCC.fetch(
                      baseRL, baseObjectArray, indexColsBitSet);

          /* Throw exception if fetch() returns false */
          if (! base_row_exists)
          {
            String indexName = indexCD.getConglomerateName();
            throw StandardException.newException(SQLState.LANG_INCONSISTENT_ROW_LOCATION,
                  (schemaName + "." + tableName),
                  indexName,
                  baseRL.toString(),
                  indexRow.toString());
          }

          /* Compare all the column values */
          for (int column = 0; column < baseColumns; column++)
          {
            DataValueDescriptor indexColumn =
              indexRow.getColumn(column + 1);
            DataValueDescriptor baseColumn =
              baseRowIndexOrder[column];

            /*
            ** With this form of compare(), null is considered equal
            ** to null.
            */
            if (indexColumn.compare(baseColumn) != 0)
            {
              ColumnDescriptor cd =
                                td.getColumnDescriptor(
                                    baseColumnPositions[column]);

                            /*
                            System.out.println(
                                "SQLState.LANG_INDEX_COLUMN_NOT_EQUAL:" +
                                "indexCD.getConglomerateName()" + indexCD.getConglomerateName() +
                                ";td.getSchemaName() = " + td.getSchemaName() +
                                ";td.getName() = " + td.getName() +
                                ";baseRL.toString() = " + baseRL.toString() +
                                ";cd.getColumnName() = " + cd.getColumnName() +
                                ";indexColumn.toString() = " + indexColumn.toString() +
                                ";baseColumn.toString() = " + baseColumn.toString() +
                                ";indexRow.toString() = " + indexRow.toString());
                            */

              throw StandardException.newException(
                                SQLState.LANG_INDEX_COLUMN_NOT_EQUAL,
                                indexCD.getConglomerateName(),
                                td.getSchemaName(),
                                td.getName(),
                                baseRL.toString(),
                                cd.getColumnName(),
                                indexColumn.toString(),
                                baseColumn.toString(),
                                indexRow.toString());
            }
          }
        }

        /* Clean up after the index scan */
        scan.close();
        scan = null;

        /*
        ** The index is supposed to have the same number of rows as the
        ** base conglomerate.
        */
        if (indexRows != baseRowCount)
        {
          throw StandardException.newException(SQLState.LANG_INDEX_ROW_COUNT_MISMATCH,
                    indexCD.getConglomerateName(),
                    td.getSchemaName(),
                    td.getName(),
                    Long.toString(indexRows),
                    Long.toString(baseRowCount));
        }
      }
      /* check that all constraints have backing index */
      ConstraintDescriptorList constraintDescList =
        dd.getConstraintDescriptors(td);
      for (int index = 0; index < constraintDescList.size(); index++)
      {
        constraintDesc = constraintDescList.elementAt(index);
        if (constraintDesc.hasBackingIndex())
        {
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.