Search in sources :

Example 21 with TableDescriptor

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

the class IndexStatisticsDaemonImpl method processingLoop.

/**
 * Main processing loop which will compute statistics until the queue
 * of scheduled work units has been drained.
 */
private void processingLoop() {
    // If we don't have a connection to the database, create one.
    if (daemonLCC == null) {
        try {
            daemonLCC = db.setupConnection(ctxMgr, dbOwner, null, databaseName);
            // Initialize the lcc/transaction.
            // TODO: Would be nice to name the transaction.
            daemonLCC.setIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED);
            // Don't wait for any locks.
            daemonLCC.getTransactionExecute().setNoLockWait(true);
        } catch (StandardException se) {
            log(AS_BACKGROUND_TASK, null, se, "failed to initialize index statistics updater");
            return;
        }
    }
    TransactionController tc = null;
    try {
        tc = daemonLCC.getTransactionExecute();
        trace(0, "worker thread started (xid=" + tc.getTransactionIdString() + ")");
        TableDescriptor td = null;
        long start = 0;
        while (true) {
            synchronized (queue) {
                if (daemonDisabled) {
                    // Clean the lcc and exit.
                    try {
                        tc.destroy();
                    } catch (ShutdownException se) {
                    // Ignore
                    }
                    tc = null;
                    daemonLCC = null;
                    queue.clear();
                    trace(1, "daemon disabled");
                    break;
                }
                if (queue.isEmpty()) {
                    trace(1, "queue empty");
                    break;
                }
                td = queue.get(0);
            }
            try {
                start = System.currentTimeMillis();
                generateStatistics(daemonLCC, td);
                wuProcessed++;
                // Reset consecutive error counter.
                errorsConsecutive = 0;
                log(AS_BACKGROUND_TASK, td, "generation complete (" + ((System.currentTimeMillis() - start)) + " ms)");
            } catch (StandardException se) {
                errorsConsecutive++;
                // For less severe errors, rollback tx to clean up.
                if (!handleFatalErrors(ctxMgr, se)) {
                    boolean handled = handleExpectedErrors(td, se);
                    if (!handled) {
                        handled = handleUnexpectedErrors(td, se);
                    }
                    daemonLCC.internalRollback();
                    if (SanityManager.DEBUG) {
                        SanityManager.ASSERT(handled);
                    }
                }
            } finally {
                // Whatever happened, discard the unit of work.
                synchronized (queue) {
                    // Queue may have been cleared due to shutdown.
                    if (!queue.isEmpty()) {
                        queue.remove(0);
                    }
                }
                // Create an exception to force logging of the message.
                if (errorsConsecutive >= 50) {
                    log(AS_BACKGROUND_TASK, null, new IllegalStateException("degraded state"), "shutting down daemon, " + errorsConsecutive + " consecutive errors seen");
                    stop();
                }
            }
        }
    } catch (StandardException se) {
        log(AS_BACKGROUND_TASK, null, se, "thread died");
    // Do nothing, just let the thread die.
    } finally {
        synchronized (queue) {
            runningThread = null;
        }
        if (daemonLCC != null && !daemonLCC.isTransactionPristine()) {
            if (SanityManager.DEBUG) {
                SanityManager.THROWASSERT("transaction not pristine");
            }
            log(AS_BACKGROUND_TASK, null, "transaction not pristine - forcing rollback");
            try {
                daemonLCC.internalRollback();
            } catch (StandardException se) {
                // Log, then continue.
                log(AS_BACKGROUND_TASK, null, se, "forced rollback failed");
            }
        }
    }
}
Also used : StandardException(org.apache.derby.shared.common.error.StandardException) ShutdownException(org.apache.derby.shared.common.error.ShutdownException) TransactionController(org.apache.derby.iapi.store.access.TransactionController) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

Example 22 with TableDescriptor

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

the class FromBaseTable method bindNonVTITables.

/**
 * Bind the table in this FromBaseTable.
 * This is where view resolution occurs
 *
 * @param dataDictionary	The DataDictionary to use for binding
 * @param fromListParam		FromList to use/append to.
 *
 * @return	ResultSetNode	The FromTable for the table or resolved view.
 *
 * @exception StandardException		Thrown on error
 */
@Override
ResultSetNode bindNonVTITables(DataDictionary dataDictionary, FromList fromListParam) throws StandardException {
    tableName.bind();
    TableDescriptor tabDescr = bindTableDescriptor();
    if (tabDescr.getTableType() == TableDescriptor.VTI_TYPE) {
        ResultSetNode vtiNode = mapTableAsVTI(tabDescr, getCorrelationName(), getResultColumns(), getProperties(), getContextManager());
        return vtiNode.bindNonVTITables(dataDictionary, fromListParam);
    }
    ResultColumnList derivedRCL = getResultColumns();
    // make sure there's a restriction list
    restrictionList = new PredicateList(getContextManager());
    baseTableRestrictionList = new PredicateList(getContextManager());
    CompilerContext compilerContext = getCompilerContext();
    /* Generate the ResultColumnList */
    setResultColumns(genResultColList());
    templateColumns = getResultColumns();
    /* Resolve the view, if this is a view */
    if (tabDescr.getTableType() == TableDescriptor.VIEW_TYPE) {
        FromSubquery fsq;
        ResultSetNode rsn;
        ViewDescriptor vd;
        CreateViewNode cvn;
        SchemaDescriptor compSchema;
        /* Get the associated ViewDescriptor so that we can get 
			 * the view definition text.
			 */
        vd = dataDictionary.getViewDescriptor(tabDescr);
        /*
			** Set the default compilation schema to be whatever
			** this schema this view was originally compiled against.
			** That way we pick up the same tables no matter what
			** schema we are running against.
			*/
        compSchema = dataDictionary.getSchemaDescriptor(vd.getCompSchemaId(), null);
        compilerContext.pushCompilationSchema(compSchema);
        try {
            /* This represents a view - query is dependent on the ViewDescriptor */
            compilerContext.createDependency(vd);
            cvn = (CreateViewNode) parseStatement(vd.getViewText(), false);
            rsn = cvn.getParsedQueryExpression();
            /* If the view contains a '*' then we mark the views derived column list
				 * so that the view will still work, and return the expected results,
				 * if any of the tables referenced in the view have columns added to
				 * them via ALTER TABLE.  The expected results means that the view
				 * will always return the same # of columns.
				 */
            if (rsn.getResultColumns().containsAllResultColumn()) {
                getResultColumns().setCountMismatchAllowed(true);
            }
            // checking.
            for (ResultColumn rc : getResultColumns()) {
                if (isPrivilegeCollectionRequired()) {
                    compilerContext.addRequiredColumnPriv(rc.getTableColumnDescriptor());
                }
            }
            fsq = new FromSubquery(rsn, cvn.getOrderByList(), cvn.getOffset(), cvn.getFetchFirst(), cvn.hasJDBClimitClause(), (correlationName != null) ? correlationName : getOrigTableName().getTableName(), getResultColumns(), tableProperties, getContextManager());
            // Transfer the nesting level to the new FromSubquery
            fsq.setLevel(level);
            // We are getting ready to bind the query underneath the view. Since
            // that query is going to run with definer's privileges, we do not
            // need to collect any privilege requirement for that query.
            // Following call is marking the query to run with definer
            // privileges. This marking will make sure that we do not collect
            // any privilege requirement for it.
            CollectNodesVisitor<QueryTreeNode> cnv = new CollectNodesVisitor<QueryTreeNode>(QueryTreeNode.class);
            fsq.accept(cnv);
            for (QueryTreeNode node : cnv.getList()) {
                node.disablePrivilegeCollection();
            }
            fsq.setOrigTableName(this.getOrigTableName());
            // since we reset the compilation schema when we return, we
            // need to save it for use when we bind expressions:
            fsq.setOrigCompilationSchema(compSchema);
            ResultSetNode fsqBound = fsq.bindNonVTITables(dataDictionary, fromListParam);
            /* Do error checking on derived column list and update "exposed"
				 * column names if valid.
				 */
            if (derivedRCL != null) {
                fsqBound.getResultColumns().propagateDCLInfo(derivedRCL, origTableName.getFullTableName());
            }
            return fsqBound;
        } finally {
            compilerContext.popCompilationSchema();
        }
    } else {
        /* This represents a table - query is dependent on the TableDescriptor */
        compilerContext.createDependency(tabDescr);
        /* Get the base conglomerate descriptor */
        baseConglomerateDescriptor = tabDescr.getConglomerateDescriptor(tabDescr.getHeapConglomerateId());
        // probably doesn't exist anymore.
        if (baseConglomerateDescriptor == null) {
            throw StandardException.newException(SQLState.STORE_CONGLOMERATE_DOES_NOT_EXIST, Long.valueOf(tabDescr.getHeapConglomerateId()));
        }
        /* Build the 0-based array of base column names. */
        columnNames = getResultColumns().getColumnNames();
        /* Do error checking on derived column list and update "exposed"
			 * column names if valid.
			 */
        if (derivedRCL != null) {
            getResultColumns().propagateDCLInfo(derivedRCL, origTableName.getFullTableName());
        }
        /* Assign the tableNumber */
        if (// allow re-bind, in which case use old number
        tableNumber == -1)
            tableNumber = compilerContext.getNextTableNumber();
    }
    // 
    // Only the DBO can select from SYS.SYSUSERS.
    // 
    authorizeSYSUSERS = dataDictionary.usesSqlAuthorization() && tabDescr.getUUID().toString().equals(SYSUSERSRowFactory.SYSUSERS_UUID);
    if (authorizeSYSUSERS) {
        String databaseOwner = dataDictionary.getAuthorizationDatabaseOwner();
        String currentUser = getLanguageConnectionContext().getStatementContext().getSQLSessionContext().getCurrentUser();
        if (!databaseOwner.equals(currentUser)) {
            throw StandardException.newException(SQLState.DBO_ONLY);
        }
    }
    return this;
}
Also used : SchemaDescriptor(org.apache.derby.iapi.sql.dictionary.SchemaDescriptor) CompilerContext(org.apache.derby.iapi.sql.compile.CompilerContext) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor) ViewDescriptor(org.apache.derby.iapi.sql.dictionary.ViewDescriptor) OptimizablePredicateList(org.apache.derby.iapi.sql.compile.OptimizablePredicateList)

Example 23 with TableDescriptor

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

the class CursorNode method updateIndexStatisticsFor.

/**
 * Returns a list of base tables for which the index statistics of the
 * associated indexes should be updated.
 *
 * @return A list of table descriptors (potentially empty).
 * @throws StandardException if accessing the index descriptors of a base
 *      table fails
 */
@Override
public TableDescriptor[] updateIndexStatisticsFor() throws StandardException {
    if (!checkIndexStats || statsToUpdate == null) {
        return EMPTY_TD_LIST;
    }
    // mostly up-to-date (minor performance optimization to avoid copy).
    for (int i = statsToUpdate.size() - 1; i >= 0; i--) {
        TableDescriptor td = statsToUpdate.get(i);
        if (td.getAndClearIndexStatsIsUpToDate()) {
            statsToUpdate.remove(i);
        }
    }
    if (statsToUpdate.isEmpty()) {
        return EMPTY_TD_LIST;
    } else {
        TableDescriptor[] tmp = new TableDescriptor[statsToUpdate.size()];
        statsToUpdate.toArray(tmp);
        statsToUpdate.clear();
        return tmp;
    }
}
Also used : TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

Example 24 with TableDescriptor

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

the class DDLStatementNode method justGetDescriptor.

/**
 * Just get the table descriptor. Don't worry if it belongs to a view,
 * system table, synonym or a real table. Let the caller decide what
 * to do.
 *
 * @param tableName
 *
 * @return TableDescriptor for the give TableName
 *
 * @throws StandardException on error
 */
private TableDescriptor justGetDescriptor(TableName tableName) throws StandardException {
    String schemaName = tableName.getSchemaName();
    SchemaDescriptor sd = getSchemaDescriptor(schemaName);
    TableDescriptor td = getTableDescriptor(tableName.getTableName(), sd);
    if (td == null) {
        throw StandardException.newException(SQLState.LANG_OBJECT_DOES_NOT_EXIST, statementToString(), tableName);
    }
    return td;
}
Also used : SchemaDescriptor(org.apache.derby.iapi.sql.dictionary.SchemaDescriptor) TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

Example 25 with TableDescriptor

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

the class DDLStatementNode method getTableDescriptor.

/**
 * Validate that the table is ok for DDL -- e.g.
 * that it exists, it is not a view. It is ok for
 * it to be a system table. Also check that its
 * schema is ok. Currently, the only time this method
 * is called is when user has asked for inplace
 * compress. eg
 * call SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE('SYS','SYSTABLES',1,1,1);
 * Inplace compress is allowed on both system and
 * user tables.
 *
 * @return the validated table descriptor, never null
 *
 * @exception StandardException on error
 */
protected final TableDescriptor getTableDescriptor(boolean doSystemTableCheck) throws StandardException {
    TableDescriptor td = justGetDescriptor(tableName);
    td = checkTableDescriptor(td, doSystemTableCheck);
    return td;
}
Also used : TableDescriptor(org.apache.derby.iapi.sql.dictionary.TableDescriptor)

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