Search in sources :

Example 36 with CompilerContext

use of org.apache.derby.iapi.sql.compile.CompilerContext in project derby by apache.

the class CreateViewNode method bindStatement.

// We inherit the generate() method from DDLStatementNode.
/**
 * Bind this CreateViewNode.  This means doing any static error
 * checking that can be done before actually creating the table.
 * For example, verifying that the ResultColumnList does not
 * contain any duplicate column names.
 *
 * @exception StandardException		Thrown on error
 */
@Override
public void bindStatement() throws StandardException {
    CompilerContext cc = getCompilerContext();
    DataDictionary dataDictionary = getDataDictionary();
    ResultColumnList qeRCL;
    String duplicateColName;
    // bind the query expression
    providerInfos = bindViewDefinition(dataDictionary, cc, getLanguageConnectionContext(), getOptimizerFactory(), queryExpression, getContextManager());
    qeRCL = queryExpression.getResultColumns();
    /* If there is an RCL for the view definition then
		 * copy the names to the queryExpression's RCL after verifying
		 * that they both have the same size.
		 */
    if (resultColumns != null) {
        if (resultColumns.size() != qeRCL.visibleSize()) {
            throw StandardException.newException(SQLState.LANG_VIEW_DEFINITION_R_C_L_MISMATCH, getFullName());
        }
        qeRCL.copyResultColumnNames(resultColumns);
    }
    /* Check to make sure the queryExpression's RCL has unique names. If target column
		 * names not specified, raise error if there are any un-named columns to match DB2
		 */
    duplicateColName = qeRCL.verifyUniqueNames((resultColumns == null) ? true : false);
    if (duplicateColName != null) {
        throw StandardException.newException(SQLState.LANG_DUPLICATE_COLUMN_NAME_CREATE_VIEW, duplicateColName);
    }
    /* Only 5000 columns allowed per view */
    if (queryExpression.getResultColumns().size() > Limits.DB2_MAX_COLUMNS_IN_VIEW) {
        throw StandardException.newException(SQLState.LANG_TOO_MANY_COLUMNS_IN_TABLE_OR_VIEW, String.valueOf(queryExpression.getResultColumns().size()), getRelativeName(), String.valueOf(Limits.DB2_MAX_COLUMNS_IN_VIEW));
    }
    // for each column, stuff system.column
    // System columns should only include visible columns DERBY-4230
    colInfos = new ColumnInfo[queryExpression.getResultColumns().visibleSize()];
    genColumnInfos(colInfos);
}
Also used : CompilerContext(org.apache.derby.iapi.sql.compile.CompilerContext) DataDictionary(org.apache.derby.iapi.sql.dictionary.DataDictionary)

Example 37 with CompilerContext

use of org.apache.derby.iapi.sql.compile.CompilerContext in project derby by apache.

the class DDLStatementNode method getSchemaDescriptor.

/**
 * Get a schema descriptor for this DDL object.
 * Uses this.objectName.  Always returns a schema,
 * we lock in the schema name prior to execution.
 *
 * The most common call to this method is with 2nd
 * parameter true which says that SchemaDescriptor
 * should not be requested for system schema. The only
 * time this method will get called with 2nd parameter
 * set to false will be when user has requested for
 * inplace compress using
 * SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE
 * Above inplace compress can be invoked on system tables.
 * A call to SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE
 * internally gets translated into ALTER TABLE sql.
 * When ALTER TABLE is executed for SYSCS_INPLACE_COMPRESS_TABLE,
 * we want to allow SchemaDescriptor request for system
 * tables. DERBY-1062
 *
 * @param ownerCheck		If check for schema owner is needed
 * @param doSystemSchemaCheck   If check for system schema is needed.
 *    If set to true, then throw an exception if schema descriptor
 *    is requested for a system schema. The only time this param
 *    will be set to false is when user is asking for inplace
 *    compress of a system table. DERBY-1062
 *
 * @return Schema Descriptor
 *
 * @exception	StandardException	throws on schema name
 *						that doesn't exist
 */
protected final SchemaDescriptor getSchemaDescriptor(boolean ownerCheck, boolean doSystemSchemaCheck) throws StandardException {
    String schemaName = tableName.getSchemaName();
    // boolean needError = !(implicitCreateSchema || (schemaName == null));
    boolean needError = !implicitCreateSchema;
    SchemaDescriptor sd = getSchemaDescriptor(schemaName, needError);
    CompilerContext cc = getCompilerContext();
    if (sd == null) {
        /* Disable creating schemas starting with SYS */
        if (schemaName.startsWith("SYS"))
            throw StandardException.newException(SQLState.LANG_NO_USER_DDL_IN_SYSTEM_SCHEMA, statementToString(), schemaName);
        sd = new SchemaDescriptor(getDataDictionary(), schemaName, (String) null, (UUID) null, false);
        if (isPrivilegeCollectionRequired())
            cc.addRequiredSchemaPriv(schemaName, null, Authorizer.CREATE_SCHEMA_PRIV);
    }
    if (ownerCheck && isPrivilegeCollectionRequired())
        cc.addRequiredSchemaPriv(sd.getSchemaName(), null, Authorizer.MODIFY_SCHEMA_PRIV);
    /*
		** Catch the system schema here if the caller wants us to.
		** Currently, the only time we allow system schema is for inplace
		** compress table calls.
		*/
    if (doSystemSchemaCheck && sd.isSystemSchema()) {
        throw StandardException.newException(SQLState.LANG_NO_USER_DDL_IN_SYSTEM_SCHEMA, statementToString(), sd);
    }
    return sd;
}
Also used : SchemaDescriptor(org.apache.derby.iapi.sql.dictionary.SchemaDescriptor) CompilerContext(org.apache.derby.iapi.sql.compile.CompilerContext) UUID(org.apache.derby.catalog.UUID)

Example 38 with CompilerContext

use of org.apache.derby.iapi.sql.compile.CompilerContext in project derby by apache.

the class DMLModStatementNode method parseGenerationClause.

/**
 *	Parse the generation clause for a column.
 *
 *	@param	clauseText  Text of the generation clause
 *
 * @return	The parsed expression as a query tree.
 *
 * @exception StandardException		Thrown on failure
 */
public ValueNode parseGenerationClause(String clauseText, TableDescriptor td) throws StandardException {
    Parser p;
    ValueNode clauseTree;
    LanguageConnectionContext lcc = getLanguageConnectionContext();
    /* Get a Statement to pass to the parser */
    /* We're all set up to parse. We have to build a compilable SQL statement
		 * before we can parse -  So, we goober up a VALUES defaultText.
		 */
    String select = "SELECT " + clauseText + " FROM " + td.getQualifiedName();
    /*
		** Get a new compiler context, so the parsing of the select statement
		** doesn't mess up anything in the current context (it could clobber
		** the ParameterValueSet, for example).
		*/
    CompilerContext newCC = lcc.pushCompilerContext();
    p = newCC.getParser();
    /* Finally, we can call the parser */
    // Since this is always nested inside another SQL statement, so topLevel flag
    // should be false
    Visitable qt = p.parseStatement(select);
    if (SanityManager.DEBUG) {
        if (!(qt instanceof CursorNode)) {
            SanityManager.THROWASSERT("qt expected to be instanceof CursorNode, not " + qt.getClass().getName());
        }
        CursorNode cn = (CursorNode) qt;
        if (!(cn.getResultSetNode() instanceof SelectNode)) {
            SanityManager.THROWASSERT("cn.getResultSetNode() expected to be instanceof SelectNode, not " + cn.getResultSetNode().getClass().getName());
        }
    }
    clauseTree = ((CursorNode) qt).getResultSetNode().getResultColumns().elementAt(0).getExpression();
    lcc.popCompilerContext(newCC);
    return clauseTree;
}
Also used : LanguageConnectionContext(org.apache.derby.iapi.sql.conn.LanguageConnectionContext) CompilerContext(org.apache.derby.iapi.sql.compile.CompilerContext) Visitable(org.apache.derby.iapi.sql.compile.Visitable) Parser(org.apache.derby.iapi.sql.compile.Parser)

Example 39 with CompilerContext

use of org.apache.derby.iapi.sql.compile.CompilerContext in project derby by apache.

the class DMLModStatementNode method parseAndBindGenerationClauses.

/**
 * Parse and bind the generating expressions of computed columns.
 *
 * @param dataDictionary    metadata
 * @param targetTableDescriptor metadata for the table that has the generated columns
 * @param sourceRCL  the tuple stream which drives the INSERT or UPDATE
 * @param targetRCL  the row in the table that's being INSERTed or UPDATEd
 * @param forUpdate true if this is an UPDATE. false otherwise.
 * @param updateResultSet more information on the tuple stream driving the UPDATE
 */
void parseAndBindGenerationClauses(DataDictionary dataDictionary, TableDescriptor targetTableDescriptor, ResultColumnList sourceRCL, ResultColumnList targetRCL, boolean forUpdate, ResultSetNode updateResultSet) throws StandardException {
    CompilerContext compilerContext = getCompilerContext();
    int count = targetRCL.size();
    for (int i = 0; i < count; i++) {
        ResultColumn rc = targetRCL.elementAt(i);
        // 
        if (forUpdate && !rc.updated()) {
            continue;
        }
        if (rc.hasGenerationClause()) {
            ColumnDescriptor colDesc = rc.getTableColumnDescriptor();
            DataTypeDescriptor dtd = colDesc.getType();
            DefaultInfo di = colDesc.getDefaultInfo();
            ValueNode generationClause = parseGenerationClause(di.getDefaultText(), targetTableDescriptor);
            // insert CAST in case column data type is not same as the
            // resolved type of the generation clause
            generationClause = new CastNode(generationClause, dtd, getContextManager());
            // Assignment semantics of implicit cast here:
            // Section 9.2 (Store assignment). There, General Rule
            // 2.b.v.2 says that the database should raise an exception
            // if truncation occurs when stuffing a string value into a
            // VARCHAR, so make sure CAST doesn't issue warning only.
            ((CastNode) generationClause).setAssignmentSemantics();
            // 
            // Unqualified function references should resolve to the
            // current schema at the time that the table was
            // created/altered. See DERBY-3945.
            // 
            compilerContext.pushCompilationSchema(getSchemaDescriptor(di.getOriginalCurrentSchema(), false));
            try {
                bindRowScopedExpression(getOptimizerFactory(), getContextManager(), targetTableDescriptor, sourceRCL, generationClause);
            } finally {
                compilerContext.popCompilationSchema();
            }
            ResultColumn newRC = new ResultColumn(generationClause.getTypeServices(), generationClause, getContextManager());
            // replace the result column in place
            // column ids are 1-based
            newRC.setVirtualColumnId(i + 1);
            newRC.setColumnDescriptor(targetTableDescriptor, colDesc);
            targetRCL.setElementAt(newRC, i);
            // generate correctly if they reference the generated column
            if (forUpdate) {
                for (int j = 0; j < sourceRCL.size(); j++) {
                    if (rc == sourceRCL.elementAt(j)) {
                        newRC.setName(rc.getName());
                        newRC.setResultSetNumber(updateResultSet.getResultSetNumber());
                        sourceRCL.setElementAt(newRC, j);
                    }
                }
            // end of loop through sourceRCL
            }
        // end if this is an update statement
        }
    // end if this is a generated column
    }
// end of loop through targetRCL
}
Also used : DataTypeDescriptor(org.apache.derby.iapi.types.DataTypeDescriptor) DefaultInfo(org.apache.derby.catalog.DefaultInfo) CompilerContext(org.apache.derby.iapi.sql.compile.CompilerContext) ColumnDescriptor(org.apache.derby.iapi.sql.dictionary.ColumnDescriptor)

Example 40 with CompilerContext

use of org.apache.derby.iapi.sql.compile.CompilerContext in project derby by apache.

the class DMLModStatementNode method createConstraintDependencies.

/**
 * Get all of our dependents due to a constraint.
 *
 * Makes the calling object (usually a Statement) dependent on all the constraints.
 *
 * @param dd				The data dictionary
 * @param cdl				The constraint descriptor list
 * @param dependent			Parent object that will depend on all the constraints
 *							that we look up. If this argument is null, then we
 *							use the default dependent (the statement being compiled).
 *
 * @exception StandardException		Thrown on failure
 */
private void createConstraintDependencies(DataDictionary dd, ConstraintDescriptorList cdl, Dependent dependent) throws StandardException {
    CompilerContext compilerContext = getCompilerContext();
    int cdlSize = cdl.size();
    for (int index = 0; index < cdlSize; index++) {
        ConstraintDescriptor cd = cdl.elementAt(index);
        /*
			** The dependent now depends on this constraint. 
			** the default dependent is the statement 
			** being compiled.
			*/
        if (dependent == null) {
            compilerContext.createDependency(cd);
        } else {
            compilerContext.createDependency(dependent, cd);
        }
        /*
			** We are also dependent on all referencing keys --
			** if one of them is deleted, we'll have to recompile.
			** Also, if there is a BULK_INSERT on the table
			** we are going to scan to validate the constraint,
			** the index number will change, so we'll add a
			** dependency on all tables we will scan.
			*/
        if (cd instanceof ReferencedKeyConstraintDescriptor) {
            ConstraintDescriptorList fkcdl = dd.getActiveConstraintDescriptors(((ReferencedKeyConstraintDescriptor) cd).getForeignKeyConstraints(ConstraintDescriptor.ENABLED));
            int fklSize = fkcdl.size();
            for (int inner = 0; inner < fklSize; inner++) {
                ConstraintDescriptor fkcd = fkcdl.elementAt(inner);
                if (dependent == null) {
                    compilerContext.createDependency(fkcd);
                    compilerContext.createDependency(fkcd.getTableDescriptor());
                } else {
                    compilerContext.createDependency(dependent, fkcd);
                    compilerContext.createDependency(dependent, fkcd.getTableDescriptor());
                }
            }
        } else if (cd instanceof ForeignKeyConstraintDescriptor) {
            ForeignKeyConstraintDescriptor fkcd = (ForeignKeyConstraintDescriptor) cd;
            if (dependent == null) {
                compilerContext.createDependency(fkcd.getReferencedConstraint().getTableDescriptor());
            } else {
                compilerContext.createDependency(dependent, fkcd.getReferencedConstraint().getTableDescriptor());
            }
        }
    }
}
Also used : CompilerContext(org.apache.derby.iapi.sql.compile.CompilerContext) 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) ConstraintDescriptorList(org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList) ForeignKeyConstraintDescriptor(org.apache.derby.iapi.sql.dictionary.ForeignKeyConstraintDescriptor)

Aggregations

CompilerContext (org.apache.derby.iapi.sql.compile.CompilerContext)53 SchemaDescriptor (org.apache.derby.iapi.sql.dictionary.SchemaDescriptor)12 DataDictionary (org.apache.derby.iapi.sql.dictionary.DataDictionary)10 DataTypeDescriptor (org.apache.derby.iapi.types.DataTypeDescriptor)9 Parser (org.apache.derby.iapi.sql.compile.Parser)8 Visitable (org.apache.derby.iapi.sql.compile.Visitable)6 TypeId (org.apache.derby.iapi.types.TypeId)6 LanguageConnectionContext (org.apache.derby.iapi.sql.conn.LanguageConnectionContext)5 ProviderList (org.apache.derby.iapi.sql.depend.ProviderList)5 ConglomerateDescriptor (org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor)5 ArrayList (java.util.ArrayList)4 ColumnDescriptor (org.apache.derby.iapi.sql.dictionary.ColumnDescriptor)4 TableDescriptor (org.apache.derby.iapi.sql.dictionary.TableDescriptor)4 ContextManager (org.apache.derby.iapi.services.context.ContextManager)3 StandardException (org.apache.derby.shared.common.error.StandardException)3 UUID (org.apache.derby.catalog.UUID)2 DefaultInfoImpl (org.apache.derby.catalog.types.DefaultInfoImpl)2 ClassFactory (org.apache.derby.iapi.services.loader.ClassFactory)2 CostEstimate (org.apache.derby.iapi.sql.compile.CostEstimate)2 TypeCompilerFactory (org.apache.derby.iapi.sql.compile.TypeCompilerFactory)2