Package org.datanucleus.store.rdbms.sql

Examples of org.datanucleus.store.rdbms.sql.SQLStatement


        RDBMSStoreManager storeMgr = (RDBMSStoreManager)ec.getStoreManager();
        DatastoreClass classTable = (DatastoreClass)datastoreContainer; // Don't support join tables yet
        SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();

        // Generate "SELECT {clobColumn} FROM TABLE WHERE ID=? FOR UPDATE" statement
        SQLStatement sqlStmt = new SQLStatement(storeMgr, datastoreContainer, null, null);
        sqlStmt.setClassLoaderResolver(ec.getClassLoaderResolver());
        sqlStmt.addExtension("lock-for-update", true);
        SQLTable blobSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), mapping.getJavaTypeMapping());
        sqlStmt.select(blobSqlTbl, mapping.getDatastoreField(), null);
        StatementClassMapping mappingDefinition = new StatementClassMapping();
        AbstractClassMetaData cmd = sm.getClassMetaData();
        int inputParamNum = 1;
        if (cmd.getIdentityType() == IdentityType.DATASTORE)
        {
            // Datastore identity value for input
            JavaTypeMapping datastoreIdMapping = classTable.getDatastoreObjectIdMapping();
            SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(),
                datastoreIdMapping);
            SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, datastoreIdMapping, null, "ID");
            sqlStmt.whereAnd(expr.eq(val), true);

            StatementMappingIndex datastoreIdx = mappingDefinition.getMappingForMemberPosition(StatementClassMapping.MEMBER_DATASTORE_ID);
            if (datastoreIdx == null)
            {
                datastoreIdx = new StatementMappingIndex(datastoreIdMapping);
                mappingDefinition.addMappingForMember(StatementClassMapping.MEMBER_DATASTORE_ID, datastoreIdx);
            }
            datastoreIdx.addParameterOccurrence(new int[] {inputParamNum});
        }
        else if (cmd.getIdentityType() == IdentityType.APPLICATION)
        {
            // Application identity value(s) for input
            int[] pkNums = cmd.getPKMemberPositions();
            for (int i=0;i<pkNums.length;i++)
            {
                AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkNums[i]);
                JavaTypeMapping pkMapping = classTable.getMemberMapping(mmd);
                SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(),
                    pkMapping);
                SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, pkMapping, null, "PK" + i);
                sqlStmt.whereAnd(expr.eq(val), true);

                StatementMappingIndex pkIdx = mappingDefinition.getMappingForMemberPosition(pkNums[i]);
                if (pkIdx == null)
                {
                    pkIdx = new StatementMappingIndex(pkMapping);
                    mappingDefinition.addMappingForMember(pkNums[i], pkIdx);
                }
                int[] inputParams = new int[pkMapping.getNumberOfDatastoreMappings()];
                for (int j=0;j<pkMapping.getNumberOfDatastoreMappings();j++)
                {
                    inputParams[j] = inputParamNum++;
                }
                pkIdx.addParameterOccurrence(inputParams);
            }
        }

        String textStmt = sqlStmt.getSelectStatement().toSQL();

        if (sm.isEmbedded())
        {
            // This mapping is embedded, so navigate back to the real owner since that is the "id" in the table
            ObjectProvider[] embeddedOwners = sm.getEmbeddedOwners();
View Full Code Here


        RDBMSStoreManager storeMgr = (RDBMSStoreManager)ec.getStoreManager();
        DatastoreClass classTable = (DatastoreClass)datastoreContainer; // Don't support join tables yet
        SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();

        // Generate "SELECT {blobColumn} FROM TABLE WHERE ID=? FOR UPDATE" statement
        SQLStatement sqlStmt = new SQLStatement(storeMgr, datastoreContainer, null, null);
        sqlStmt.setClassLoaderResolver(ec.getClassLoaderResolver());
        sqlStmt.addExtension("lock-for-update", true);
        SQLTable blobSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), mapping.getJavaTypeMapping());
        sqlStmt.select(blobSqlTbl, mapping.getDatastoreField(), null);
        StatementClassMapping mappingDefinition = new StatementClassMapping();
        AbstractClassMetaData cmd = sm.getClassMetaData();
        int inputParamNum = 1;
        if (cmd.getIdentityType() == IdentityType.DATASTORE)
        {
            // Datastore identity value for input
            JavaTypeMapping datastoreIdMapping = classTable.getDatastoreObjectIdMapping();
            SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(),
                datastoreIdMapping);
            SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, datastoreIdMapping, null, "ID");
            sqlStmt.whereAnd(expr.eq(val), true);

            StatementMappingIndex datastoreIdx = mappingDefinition.getMappingForMemberPosition(StatementClassMapping.MEMBER_DATASTORE_ID);
            if (datastoreIdx == null)
            {
                datastoreIdx = new StatementMappingIndex(datastoreIdMapping);
                mappingDefinition.addMappingForMember(StatementClassMapping.MEMBER_DATASTORE_ID, datastoreIdx);
            }
            datastoreIdx.addParameterOccurrence(new int[] {inputParamNum});
        }
        else if (cmd.getIdentityType() == IdentityType.APPLICATION)
        {
            // Application identity value(s) for input
            int[] pkNums = cmd.getPKMemberPositions();
            for (int i=0;i<pkNums.length;i++)
            {
                AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkNums[i]);
                JavaTypeMapping pkMapping = classTable.getMemberMapping(mmd);
                SQLExpression expr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(),
                    pkMapping);
                SQLExpression val = exprFactory.newLiteralParameter(sqlStmt, pkMapping, null, "PK" + i);
                sqlStmt.whereAnd(expr.eq(val), true);

                StatementMappingIndex pkIdx = mappingDefinition.getMappingForMemberPosition(pkNums[i]);
                if (pkIdx == null)
                {
                    pkIdx = new StatementMappingIndex(pkMapping);
                    mappingDefinition.addMappingForMember(pkNums[i], pkIdx);
                }
                int[] inputParams = new int[pkMapping.getNumberOfDatastoreMappings()];
                for (int j=0;j<pkMapping.getNumberOfDatastoreMappings();j++)
                {
                    inputParams[j] = inputParamNum++;
                }
                pkIdx.addParameterOccurrence(inputParams);
            }
        }

        String textStmt = sqlStmt.getSelectStatement().toSQL();

        if (sm.isEmbedded())
        {
            // This mapping is embedded, so navigate back to the real owner since that is the "id" in the table
            ObjectProvider[] embeddedOwners = sm.getEmbeddedOwners();
View Full Code Here

        if (iteratorStmtLocked == null)
        {
            synchronized (this) // Make sure this completes in case another thread needs the same info
            {
                // Generate the statement, and statement mapping/parameter information
                SQLStatement sqlStmt = getSQLStatementForIterator(ownerSM);
                iteratorStmtUnlocked = sqlStmt.getSelectStatement().toSQL();
                sqlStmt.addExtension("lock-for-update", true);
                iteratorStmtLocked = sqlStmt.getSelectStatement().toSQL();
            }
        }

        Transaction tx = ec.getTransaction();
        String stmt = (tx.lockReadObjects() ? iteratorStmtLocked : iteratorStmtUnlocked);
View Full Code Here

     * @param ownerSM StateManager for the owner object
     * @return The SQLStatement
     */
    protected SQLStatement getSQLStatementForIterator(ObjectProvider ownerSM)
    {
        SQLStatement sqlStmt = null;

        final ClassLoaderResolver clr = ownerSM.getExecutionContext().getClassLoaderResolver();
        final Class valueCls = clr.classForName(elementType);
        RDBMSStoreManager storeMgr = (RDBMSStoreManager)this.storeMgr;
        SQLTable containerSqlTbl = null;
        MapType mapType = getOwnerMemberMetaData().getMap().getMapType();
        if (emd != null && emd.getDiscriminatorStrategyForTable() != null &&
            emd.getDiscriminatorStrategyForTable() != DiscriminatorStrategy.NONE)
        {
            // Map<?, PC> where value has discriminator
            if (ClassUtils.isReferenceType(valueCls))
            {
                // Take the metadata for the first implementation of the reference type
                String[] clsNames = storeMgr.getNucleusContext().getMetaDataManager().getClassesImplementingInterface(elementType, clr);
                Class[] cls = new Class[clsNames.length];
                for (int j=0; j<clsNames.length; j++)
                {
                    cls[j] = clr.classForName(clsNames[j]);
                }
                StatementGenerator stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, cls, true, null, null);
                sqlStmt = stmtGen.getStatement();
            }
            else
            {
                StatementGenerator stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, valueCls, true, null, null);
                sqlStmt = stmtGen.getStatement();
            }
            iterateUsingDiscriminator = true;

            if (mapType == MapType.MAP_TYPE_VALUE_IN_KEY)
            {
                // Join to key table and select value fields
                JavaTypeMapping valueIdMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
                containerSqlTbl = sqlStmt.innerJoin(sqlStmt.getPrimaryTable(), valueIdMapping,
                    containerTable, null, elementMapping, null, null);

                iteratorMappingDef = new StatementClassMapping();
                SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef,
                    ownerSM.getExecutionContext().getFetchPlan(), sqlStmt.getPrimaryTable(), emd, 0);
            }
            else if (mapType == MapType.MAP_TYPE_KEY_IN_VALUE)
            {
                // Select value fields
                containerSqlTbl = sqlStmt.getPrimaryTable();

                iteratorMappingDef = new StatementClassMapping();
                SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef,
                    ownerSM.getExecutionContext().getFetchPlan(), sqlStmt.getPrimaryTable(), emd, 0);
            }
            else
            {
                // Join to join table and select value fields
                JavaTypeMapping valueIdMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
                containerSqlTbl = sqlStmt.innerJoin(sqlStmt.getPrimaryTable(), valueIdMapping,
                    containerTable, null, elementMapping, null, null);

                iteratorMappingDef = new StatementClassMapping();
                SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef,
                    ownerSM.getExecutionContext().getFetchPlan(), sqlStmt.getPrimaryTable(), emd, 0);
            }
        }
        else
        {
            if (mapType == MapType.MAP_TYPE_VALUE_IN_KEY)
            {
                if (emd != null)
                {
                    // TODO Allow for null value [change to select the key table and left outer join to the key]
                    // Select of value table, joining to key table
                    iteratorMappingDef = new StatementClassMapping();
                    UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, valueCls, true, null, null);
                    stmtGen.setOption(StatementGenerator.OPTION_SELECT_NUCLEUS_TYPE);
                    iteratorMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.NUC_TYPE_COLUMN);
                    sqlStmt = stmtGen.getStatement();

                    JavaTypeMapping valueIdMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
                    containerSqlTbl = sqlStmt.innerJoin(sqlStmt.getPrimaryTable(), valueIdMapping,
                        containerTable, null, elementMapping, null, null);

                    SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef,
                        ownerSM.getExecutionContext().getFetchPlan(), sqlStmt.getPrimaryTable(), emd, 0);
                }
                else
                {
                    // Select of value in key table
                    sqlStmt = new SQLStatement(storeMgr, containerTable, null, null);
                    sqlStmt.setClassLoaderResolver(clr);
                    containerSqlTbl = sqlStmt.getPrimaryTable();
                    sqlStmt.select(sqlStmt.getPrimaryTable(), elementMapping, null);
                }
            }
            else if (mapType == MapType.MAP_TYPE_KEY_IN_VALUE)
            {
                // Select of value in value table (allow union of possible value types)
                iteratorMappingDef = new StatementClassMapping();
                UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, valueCls, true, null, null);
                stmtGen.setOption(StatementGenerator.OPTION_SELECT_NUCLEUS_TYPE);
                iteratorMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.NUC_TYPE_COLUMN);
                sqlStmt = stmtGen.getStatement();
                containerSqlTbl = sqlStmt.getPrimaryTable();

                SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef,
                    ownerSM.getExecutionContext().getFetchPlan(), sqlStmt.getPrimaryTable(), emd, 0);
            }
            else
            {
                if (emd != null)
                {
                    // TODO Allow for null value [change to select the join table and left outer join to the key]
                    // Select of value table, joining to key table
                    iteratorMappingDef = new StatementClassMapping();
                    UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, valueCls, true, null, null);
                    stmtGen.setOption(StatementGenerator.OPTION_SELECT_NUCLEUS_TYPE);
                    iteratorMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.NUC_TYPE_COLUMN);
                    sqlStmt = stmtGen.getStatement();

                    JavaTypeMapping valueIdMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
                    containerSqlTbl = sqlStmt.innerJoin(sqlStmt.getPrimaryTable(), valueIdMapping,
                        containerTable, null, elementMapping, null, null);

                    SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef,
                        ownerSM.getExecutionContext().getFetchPlan(), sqlStmt.getPrimaryTable(), emd, 0);
                }
                else
                {
                    // Select of value in join table
                    sqlStmt = new SQLStatement(storeMgr, containerTable, null, null);
                    containerSqlTbl = sqlStmt.getPrimaryTable();
                    sqlStmt.select(sqlStmt.getPrimaryTable(), elementMapping, null);
                }
            }
        }

        // Apply condition on owner field to filter by owner
        SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
        SQLTable ownerSqlTbl =
            SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, containerSqlTbl, ownerMapping);
        SQLExpression ownerExpr = exprFactory.newExpression(sqlStmt, ownerSqlTbl, ownerMapping);
        SQLExpression ownerVal = exprFactory.newLiteralParameter(sqlStmt, ownerMapping, null, "OWNER");
        sqlStmt.whereAnd(ownerExpr.eq(ownerVal), true);

        // Input parameter(s) - the owner
        int inputParamNum = 1;
        StatementMappingIndex ownerIdx = new StatementMappingIndex(ownerMapping);
        if (sqlStmt.getNumberOfUnions() > 0)
        {
            // Add parameter occurrence for each union of statement
            for (int j=0;j<sqlStmt.getNumberOfUnions()+1;j++)
            {
                int[] paramPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
                for (int k=0;k<ownerMapping.getNumberOfDatastoreMappings();k++)
                {
                    paramPositions[k] = inputParamNum++;
View Full Code Here

     */
    public static SQLStatement getStatementForCandidates(SQLStatement parentStmt, AbstractClassMetaData cmd,
            StatementClassMapping clsMapping, ExecutionContext ec, Class candidateCls, boolean subclasses,
            String result, String candidateAlias, String candidateTableGroupName)
    {
        SQLStatement stmt = null;

        RDBMSStoreManager storeMgr = (RDBMSStoreManager)ec.getStoreManager();
        DatastoreIdentifier candidateAliasId = null;
        if (candidateAlias != null)
        {
            candidateAliasId = storeMgr.getIdentifierFactory().newDatastoreContainerIdentifier(candidateAlias);
        }

        ClassLoaderResolver clr = ec.getClassLoaderResolver();
        List<DatastoreClass> candidateTables = new ArrayList<DatastoreClass>();
        if (cmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE)
        {
            DatastoreClass candidateTable = storeMgr.getDatastoreClass(cmd.getFullClassName(), clr);
            if (candidateTable != null)
            {
                candidateTables.add(candidateTable);
            }
            if (subclasses)
            {
                Set<String> subclassNames =
                    storeMgr.getSubClassesForClass(cmd.getFullClassName(), subclasses, clr);
                if (subclassNames != null)
                {
                    Iterator<String> subclassIter = subclassNames.iterator();
                    while (subclassIter.hasNext())
                    {
                        String subclassName = subclassIter.next();
                        DatastoreClass tbl = storeMgr.getDatastoreClass(subclassName, clr);
                        if (tbl != null)
                        {
                            candidateTables.add(tbl);
                        }
                    }
                }
            }

            Iterator<DatastoreClass> iter = candidateTables.iterator();
            int maxClassNameLength = cmd.getFullClassName().length();
            while (iter.hasNext())
            {
                DatastoreClass cls = iter.next();
                String className = cls.getType();
                if (className.length() > maxClassNameLength)
                {
                    maxClassNameLength = className.length();
                }
            }

            iter = candidateTables.iterator();
            while (iter.hasNext())
            {
                DatastoreClass cls = iter.next();

                SQLStatement tblStmt =
                    new SQLStatement(parentStmt, storeMgr, cls, candidateAliasId, candidateTableGroupName);
                tblStmt.setClassLoaderResolver(clr);
                tblStmt.setCandidateClassName(cls.getType());

                // Add SELECT of dummy column accessible as "NUCLEUS_TYPE" containing the classname
                JavaTypeMapping m = storeMgr.getMappingManager().getMapping(String.class);
                String nuctypeName = cls.getType();
                if (maxClassNameLength > nuctypeName.length())
                {
                    nuctypeName = StringUtils.leftAlignedPaddedString(nuctypeName, maxClassNameLength);
                }
                StringLiteral lit = new StringLiteral(tblStmt, m, nuctypeName, null);
                tblStmt.select(lit, UnionStatementGenerator.NUC_TYPE_COLUMN);

                if (stmt == null)
                {
                    stmt = tblStmt;
                }
                else
                {
                    stmt.union(tblStmt);
                }
            }
            if (clsMapping != null)
            {
                clsMapping.setNucleusTypeColumnName(UnionStatementGenerator.NUC_TYPE_COLUMN);
            }
        }
        else
        {
            // "new-table", "superclass-table", "subclass-table"
            List<Class> candidateClasses = new ArrayList<Class>();
            if (ClassUtils.isReferenceType(candidateCls))
            {
                // Persistent interface, so find all persistent implementations
                String[] clsNames =
                    storeMgr.getNucleusContext().getMetaDataManager().getClassesImplementingInterface(candidateCls.getName(), clr);
                for (int i=0;i<clsNames.length;i++)
                {
                    Class cls = clr.classForName(clsNames[i]);
                    DatastoreClass table = storeMgr.getDatastoreClass(clsNames[i], clr);
                    candidateClasses.add(cls);
                    candidateTables.add(table);
                    AbstractClassMetaData implCmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(cls, clr);
                    if (implCmd.getIdentityType() != cmd.getIdentityType())
                    {
                        throw new NucleusUserException("You are querying an interface (" + cmd.getFullClassName() + ") " +
                            "yet one of its implementations (" + implCmd.getFullClassName() + ") " +
                            " uses a different identity type!");
                    }
                    else if (cmd.getIdentityType() == IdentityType.APPLICATION)
                    {
                        if (cmd.getPKMemberPositions().length != implCmd.getPKMemberPositions().length)
                        {
                            throw new NucleusUserException("You are querying an interface (" + cmd.getFullClassName() + ") " +
                                "yet one of its implementations (" + implCmd.getFullClassName() + ") " +
                                " has a different number of PK members!");
                        }
                    }
                }
            }
            else
            {
                DatastoreClass candidateTable = storeMgr.getDatastoreClass(cmd.getFullClassName(), clr);
                if (candidateTable != null)
                {
                    // Candidate has own table
                    candidateClasses.add(candidateCls);
                    candidateTables.add(candidateTable);
                }
                else
                {
                    // Candidate stored in subclass tables
                    AbstractClassMetaData[] cmds = storeMgr.getClassesManagingTableForClass(cmd, clr);
                    if (cmds != null && cmds.length > 0)
                    {
                        for (int i=0;i<cmds.length;i++)
                        {
                            DatastoreClass table = storeMgr.getDatastoreClass(cmds[i].getFullClassName(), clr);
                            Class cls = clr.classForName(cmds[i].getFullClassName());
                            candidateClasses.add(cls);
                            candidateTables.add(table);
                        }
                    }
                    else
                    {
                        throw new UnsupportedOperationException("No tables for query of " + cmd.getFullClassName());
                    }
                }
            }

            for (int i=0;i<candidateTables.size();i++)
            {
                DatastoreClass tbl = candidateTables.get(i);
                Class cls = candidateClasses.get(i);
                StatementGenerator stmtGen = null;
                if (tbl.getDiscriminatorMapping(true) != null || QueryUtils.resultHasOnlyAggregates(result))
                {
                    // Either has a discriminator, or only selecting aggregates so need single select
                    stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, cls, subclasses,
                        candidateAliasId, candidateTableGroupName);
                    stmtGen.setOption(StatementGenerator.OPTION_RESTRICT_DISCRIM);
                }
                else
                {
                    stmtGen = new UnionStatementGenerator(storeMgr, clr, cls, subclasses,
                        candidateAliasId, candidateTableGroupName);
                    if (result == null)
                    {
                        // Returning one row per candidate so include distinguisher column
                        stmtGen.setOption(StatementGenerator.OPTION_SELECT_NUCLEUS_TYPE);
                        clsMapping.setNucleusTypeColumnName(UnionStatementGenerator.NUC_TYPE_COLUMN);
                    }
                }
                stmtGen.setParentStatement(parentStmt);
                SQLStatement tblStmt = stmtGen.getStatement();

                if (stmt == null)
                {
                    stmt = tblStmt;
                }
View Full Code Here

        if (iteratorStmtLocked == null)
        {
            synchronized (this) // Make sure this completes in case another thread needs the same info
            {
                // Generate the statement, and statement mapping/parameter information
                SQLStatement sqlStmt = getSQLStatementForIterator(ownerSM);
                iteratorStmtUnlocked = sqlStmt.getSelectStatement().toSQL();
                sqlStmt.addExtension("lock-for-update", true);
                iteratorStmtLocked = sqlStmt.getSelectStatement().toSQL();
            }
        }

        Transaction tx = ec.getTransaction();
        String stmt = (tx.lockReadObjects() ? iteratorStmtLocked : iteratorStmtUnlocked);
View Full Code Here

        if (elementInfo == null || elementInfo.length == 0)
        {
            return null;
        }

        SQLStatement sqlStmt = null;

        RDBMSStoreManager storeMgr = (RDBMSStoreManager)this.storeMgr;
        SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
        final ClassLoaderResolver clr = ownerSM.getExecutionContext().getClassLoaderResolver();
        iteratorMappingDef = new StatementClassMapping();
        if (elementInfo[0].getDatastoreClass().getDiscriminatorMetaData() != null &&
            elementInfo[0].getDatastoreClass().getDiscriminatorMetaData().getStrategy() != DiscriminatorStrategy.NONE)
        {
            // TODO Only caters for one elementInfo, but with subclass-table we can have multiple
            String elementType = ownerMemberMetaData.getCollection().getElementType();
            if (ClassUtils.isReferenceType(clr.classForName(elementType)))
            {
                String[] clsNames =
                    storeMgr.getNucleusContext().getMetaDataManager().getClassesImplementingInterface(elementType, clr);
                Class[] cls = new Class[clsNames.length];
                for (int i=0; i<clsNames.length; i++)
                {
                    cls[i] = clr.classForName(clsNames[i]);
                }
                sqlStmt = new DiscriminatorStatementGenerator(storeMgr, clr, cls, true, null, null).getStatement();
            }
            else
            {
                sqlStmt = new DiscriminatorStatementGenerator(storeMgr, clr,
                    clr.classForName(elementInfo[0].getClassName()), true, null, null).getStatement();
            }
            iterateUsingDiscriminator = true;

            // Select the required fields (of the element class)
            SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef,
                ownerSM.getExecutionContext().getFetchPlan(), sqlStmt.getPrimaryTable(), emd, 0);
        }
        else
        {
            for (int i=0;i<elementInfo.length;i++)
            {
                final Class elementCls = clr.classForName(this.elementInfo[i].getClassName());
                UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, elementCls, true, null, null);
                stmtGen.setOption(StatementGenerator.OPTION_SELECT_NUCLEUS_TYPE);
                iteratorMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.NUC_TYPE_COLUMN);
                SQLStatement subStmt = stmtGen.getStatement();

                // Select the required fields (of the element class)
                if (sqlStmt == null)
                {
                    SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(subStmt, iteratorMappingDef,
                        ownerSM.getExecutionContext().getFetchPlan(), subStmt.getPrimaryTable(), emd, 0);
                }
                else
                {
                    SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(subStmt, null,
                        ownerSM.getExecutionContext().getFetchPlan(), subStmt.getPrimaryTable(), emd, 0);
                }

                if (sqlStmt == null)
                {
                    sqlStmt = subStmt;
View Full Code Here

                throw new UnsupportedOperationException();
            }
        }

        // Use SQLOperation().getExpression(SQLExpression, SQLExpression)
        SQLStatement stmt = expr.getSQLStatement();
        try
        {
            operation = (SQLOperation)stmt.getClassLoaderResolver().classForName(sqlOperationClassName).newInstance();
            operation.setExpressionFactory(this);
            operationByOperationName.put(name, operation);

            return operation.getExpression(expr, expr2);
        }
View Full Code Here

        RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
        MetaDataManager mmgr = storeMgr.getMetaDataManager();
        AbstractMemberMetaData mmd = mapExpr.getJavaTypeMapping().getMemberMetaData();
        AbstractClassMetaData valCmd = mmd.getMap().getValueClassMetaData(clr, mmgr);
        MapTable joinTbl = (MapTable)storeMgr.getDatastoreContainerObject(mmd);
        SQLStatement subStmt = null;
        if (mmd.getMap().getMapType() == MapType.MAP_TYPE_JOIN)
        {
            // JoinTable Map
            if (valCmd == null)
            {
                // Map<?, Non-PC>
                subStmt = new SQLStatement(stmt, storeMgr, joinTbl, null, null);
                subStmt.setClassLoaderResolver(clr);
                JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
                subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);

                // Restrict to map owner
                JavaTypeMapping ownerMapping = ((JoinTable)joinTbl).getOwnerMapping();
                SQLExpression ownerExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), ownerMapping);
                SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, mapExpr.getSQLTable(),
                    mapExpr.getSQLTable().getTable().getIdMapping());
                subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);

                if (valIsUnbound)
                {
                    // Bind the variable in the QueryGenerator
                    valExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), joinTbl.getValueMapping());
                    stmt.getQueryGenerator().bindVariable(varName, valCmd, valExpr.getSQLTable(),
                        valExpr.getJavaTypeMapping());
                }
                else
                {
                    // Add restrict to value
                    SQLExpression valIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(),
                        joinTbl.getValueMapping());
                    subStmt.whereAnd(valIdExpr.eq(valExpr), true);
                }
            }
            else
            {
                // Map<?, PC>
                DatastoreClass valTbl = storeMgr.getDatastoreClass(mmd.getMap().getValueType(), clr);
                subStmt = new SQLStatement(stmt, storeMgr, valTbl, null, null);
                subStmt.setClassLoaderResolver(clr);
                JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
                subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);

                // Join to join table
                SQLTable joinSqlTbl = subStmt.innerJoin(subStmt.getPrimaryTable(), valTbl.getIdMapping(),
                    joinTbl, null, joinTbl.getValueMapping(), null, null);

                // Restrict to map owner
                JavaTypeMapping ownerMapping = joinTbl.getOwnerMapping();
                SQLExpression ownerExpr = exprFactory.newExpression(subStmt, joinSqlTbl, ownerMapping);
                SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, mapExpr.getSQLTable(),
                    mapExpr.getSQLTable().getTable().getIdMapping());
                subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);

                if (valIsUnbound)
                {
                    // Bind the variable in the QueryGenerator
                    valExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), valTbl.getIdMapping());
                    stmt.getQueryGenerator().bindVariable(varName, valCmd, valExpr.getSQLTable(),
                        valExpr.getJavaTypeMapping());
                }
                else
                {
                    // Add restrict to value
                    SQLExpression valIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(),
                        valTbl.getIdMapping());
                    subStmt.whereAnd(valIdExpr.eq(valExpr), true);
                }
            }
        }
        else if (mmd.getMap().getMapType() == MapType.MAP_TYPE_KEY_IN_VALUE)
        {
            // Key stored in value table
            DatastoreClass valTbl = storeMgr.getDatastoreClass(mmd.getMap().getValueType(), clr);
            JavaTypeMapping ownerMapping = null;
            if (mmd.getMappedBy() != null)
            {
                ownerMapping = valTbl.getMemberMapping(valCmd.getMetaDataForMember(mmd.getMappedBy()));
            }
            else
            {
                ownerMapping = valTbl.getExternalMapping(mmd, MappingConsumer.MAPPING_TYPE_EXTERNAL_FK);
            }

            subStmt = new SQLStatement(stmt, storeMgr, valTbl, null, null);
            subStmt.setClassLoaderResolver(clr);
            JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
            subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);

            // Restrict to map owner (on value table)
            SQLExpression ownerExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), ownerMapping);
            SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, mapExpr.getSQLTable(),
                mapExpr.getSQLTable().getTable().getIdMapping());
            subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);

            if (valIsUnbound)
            {
                // Bind the variable in the QueryGenerator
                valExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), valTbl.getIdMapping());
                stmt.getQueryGenerator().bindVariable(varName, valCmd, valExpr.getSQLTable(),
                    valExpr.getJavaTypeMapping());
            }
            else
            {
                // Add restrict to value
                JavaTypeMapping valMapping = valTbl.getIdMapping();
                SQLExpression valIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), valMapping);
                subStmt.whereAnd(valIdExpr.eq(valExpr), true);
            }
        }
        else if (mmd.getMap().getMapType() == MapType.MAP_TYPE_VALUE_IN_KEY)
        {
            AbstractClassMetaData keyCmd = mmd.getMap().getKeyClassMetaData(clr, mmgr);
            DatastoreClass keyTbl = storeMgr.getDatastoreClass(mmd.getMap().getKeyType(), clr);
            JavaTypeMapping ownerMapping = null;
            if (mmd.getMappedBy() != null)
            {
                ownerMapping = keyTbl.getMemberMapping(keyCmd.getMetaDataForMember(mmd.getMappedBy()));
            }
            else
            {
                ownerMapping = keyTbl.getExternalMapping(mmd, MappingConsumer.MAPPING_TYPE_EXTERNAL_FK);
            }

            AbstractMemberMetaData keyValMmd =
                keyCmd.getMetaDataForMember(mmd.getValueMetaData().getMappedBy());
            if (valCmd == null)
            {
                subStmt = new SQLStatement(stmt, storeMgr, keyTbl, null, null);
                subStmt.setClassLoaderResolver(clr);
                JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
                subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);

                // Restrict to map owner (on key table)
                SQLExpression ownerExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), ownerMapping);
                SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, mapExpr.getSQLTable(),
                    mapExpr.getSQLTable().getTable().getIdMapping());
                subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);

                if (valIsUnbound)
                {
                    // Bind the variable in the QueryGenerator
                    valExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(),
                        keyTbl.getMemberMapping(keyValMmd));
                    stmt.getQueryGenerator().bindVariable(varName, valCmd, valExpr.getSQLTable(),
                        valExpr.getJavaTypeMapping());
                }
                else
                {
                    // Add restrict to value
                    JavaTypeMapping valMapping = keyTbl.getMemberMapping(keyValMmd);
                    SQLExpression valIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), valMapping);
                    subStmt.whereAnd(valIdExpr.eq(valExpr), true);
                }
            }
            else
            {
                DatastoreClass valTbl = storeMgr.getDatastoreClass(mmd.getMap().getValueType(), clr);
                subStmt = new SQLStatement(stmt, storeMgr, valTbl, null, null);
                subStmt.setClassLoaderResolver(clr);
                JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
                subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);

                // Join to key table
                SQLTable keySqlTbl = subStmt.innerJoin(subStmt.getPrimaryTable(), valTbl.getIdMapping(),
                    keyTbl, null, keyTbl.getMemberMapping(keyValMmd), null, null);

                // Restrict to map owner (on key table)
                SQLExpression ownerExpr = exprFactory.newExpression(subStmt, keySqlTbl, ownerMapping);
                SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, mapExpr.getSQLTable(),
                    mapExpr.getSQLTable().getTable().getIdMapping());
                subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);

                if (valIsUnbound)
                {
                    // Bind the variable in the QueryGenerator
                    valExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), valTbl.getIdMapping());
                    stmt.getQueryGenerator().bindVariable(varName, valCmd, valExpr.getSQLTable(),
                        valExpr.getJavaTypeMapping());
                }
                else
                {
                    // Add restrict to value
                    SQLExpression valIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(),
                        valTbl.getIdMapping());
                    subStmt.whereAnd(valIdExpr.eq(valExpr), true);
                }
            }
        }

        return new BooleanSubqueryExpression(stmt, "EXISTS", subStmt);
View Full Code Here

        else
        {
            throw new NucleusException("Invalid map for " + mapExpr + " in get() call");
        }

        SQLStatement subStmt = new SQLStatement(stmt, storeMgr, mapTbl, null, null);
        subStmt.setClassLoaderResolver(clr);
        SQLExpression valExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), valMapping);
        subStmt.select(valExpr, null);

        // Link to primary statement
        SQLExpression elementOwnerExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(),
            ownerMapping);
        SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, mapExpr.getSQLTable(),
            mapExpr.getSQLTable().getTable().getIdMapping());
        subStmt.whereAnd(elementOwnerExpr.eq(ownerIdExpr), true);

        // Condition on key
        SQLExpression keyExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), keyMapping);
        subStmt.whereAnd(keyExpr.eq(keyValExpr), true);

        SubqueryExpression subExpr = new SubqueryExpression(stmt, subStmt);
        subExpr.setJavaTypeMapping(valMapping);
        return subExpr;
    }
View Full Code Here

TOP

Related Classes of org.datanucleus.store.rdbms.sql.SQLStatement

Copyright © 2018 www.massapicom. 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.