Search in sources :

Example 26 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class MapValueCollectionStore method getSQLStatementForIterator.

/**
 * Method to generate an SQLStatement for iterating through values of the map.
 * Populates the iteratorMappingDef and iteratorMappingParams.
 * Creates a statement that selects the value table(s), and adds any necessary join to the containerTable
 * if that is not the value table. If the value is embedded then selects the table it is embedded in.
 * Adds a restriction on the ownerMapping of the containerTable so we can restrict to the owner object.
 * @param ownerOP ObjectProvider for the owner object
 * @return The SQLStatement
 */
protected SelectStatement getSQLStatementForIterator(ObjectProvider ownerOP) {
    SelectStatement sqlStmt = null;
    ExecutionContext ec = ownerOP.getExecutionContext();
    final ClassLoaderResolver clr = ec.getClassLoaderResolver();
    final Class valueCls = clr.classForName(elementType);
    SQLTable containerSqlTbl = null;
    MapType mapType = getOwnerMemberMetaData().getMap().getMapType();
    FetchPlan fp = ec.getFetchPlan();
    if (elementCmd != null && elementCmd.getDiscriminatorStrategyForTable() != null && elementCmd.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]);
            }
            SelectStatementGenerator stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, cls, true, null, null);
            sqlStmt = stmtGen.getStatement(ec);
        } else {
            SelectStatementGenerator stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, valueCls, true, null, null);
            sqlStmt = stmtGen.getStatement(ec);
        }
        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.join(JoinType.INNER_JOIN, sqlStmt.getPrimaryTable(), valueIdMapping, containerTable, null, elementMapping, null, null, true);
            iteratorMappingDef = new StatementClassMapping();
            SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef, fp, sqlStmt.getPrimaryTable(), elementCmd, fp.getMaxFetchDepth());
        } else if (mapType == MapType.MAP_TYPE_KEY_IN_VALUE) {
            // Select value fields
            containerSqlTbl = sqlStmt.getPrimaryTable();
            iteratorMappingDef = new StatementClassMapping();
            SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef, fp, sqlStmt.getPrimaryTable(), elementCmd, fp.getMaxFetchDepth());
        } else {
            // Join to join table and select value fields
            JavaTypeMapping valueIdMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
            containerSqlTbl = sqlStmt.join(JoinType.INNER_JOIN, sqlStmt.getPrimaryTable(), valueIdMapping, containerTable, null, elementMapping, null, null, true);
            iteratorMappingDef = new StatementClassMapping();
            SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef, fp, sqlStmt.getPrimaryTable(), elementCmd, fp.getMaxFetchDepth());
        }
    } else {
        if (mapType == MapType.MAP_TYPE_VALUE_IN_KEY) {
            if (elementCmd != 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(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
                iteratorMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.DN_TYPE_COLUMN);
                sqlStmt = stmtGen.getStatement(ec);
                JavaTypeMapping valueIdMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
                containerSqlTbl = sqlStmt.join(JoinType.INNER_JOIN, sqlStmt.getPrimaryTable(), valueIdMapping, containerTable, null, elementMapping, null, null, true);
                SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef, fp, sqlStmt.getPrimaryTable(), elementCmd, fp.getMaxFetchDepth());
            } else {
                // Select of value in key table
                sqlStmt = new SelectStatement(storeMgr, containerTable, null, null);
                sqlStmt.setClassLoaderResolver(clr);
                containerSqlTbl = sqlStmt.getPrimaryTable();
                SQLTable elemSqlTblForValue = containerSqlTbl;
                if (elementMapping.getTable() != containerSqlTbl.getTable()) {
                    elemSqlTblForValue = sqlStmt.getTableForDatastoreContainer(elementMapping.getTable());
                    if (elemSqlTblForValue == null) {
                        // Add join to key table holding value
                        elemSqlTblForValue = sqlStmt.join(JoinType.INNER_JOIN, sqlStmt.getPrimaryTable(), sqlStmt.getPrimaryTable().getTable().getIdMapping(), elementMapping.getTable(), null, elementMapping.getTable().getIdMapping(), null, null, true);
                    }
                }
                sqlStmt.select(elemSqlTblForValue, 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(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
            iteratorMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.DN_TYPE_COLUMN);
            sqlStmt = stmtGen.getStatement(ec);
            containerSqlTbl = sqlStmt.getPrimaryTable();
            SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef, fp, sqlStmt.getPrimaryTable(), elementCmd, fp.getMaxFetchDepth());
        } else {
            if (elementCmd != 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(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
                iteratorMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.DN_TYPE_COLUMN);
                sqlStmt = stmtGen.getStatement(ec);
                JavaTypeMapping valueIdMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
                containerSqlTbl = sqlStmt.join(JoinType.INNER_JOIN, sqlStmt.getPrimaryTable(), valueIdMapping, containerTable, null, elementMapping, null, null, true);
                SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, iteratorMappingDef, fp, sqlStmt.getPrimaryTable(), elementCmd, fp.getMaxFetchDepth());
            } else {
                // Select of value in join table
                sqlStmt = new SelectStatement(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++;
            }
            ownerIdx.addParameterOccurrence(paramPositions);
        }
    } else {
        int[] paramPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
        for (int k = 0; k < ownerMapping.getNumberOfDatastoreMappings(); k++) {
            paramPositions[k] = inputParamNum++;
        }
        ownerIdx.addParameterOccurrence(paramPositions);
    }
    iteratorMappingParams = new StatementParameterMapping();
    iteratorMappingParams.addMappingForParameter("owner", ownerIdx);
    return sqlStmt;
}
Also used : StatementParameterMapping(org.datanucleus.store.rdbms.query.StatementParameterMapping) SQLExpressionFactory(org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) FetchPlan(org.datanucleus.FetchPlan) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) MapType(org.datanucleus.metadata.MapMetaData.MapType) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) UnionStatementGenerator(org.datanucleus.store.rdbms.sql.UnionStatementGenerator) SelectStatementGenerator(org.datanucleus.store.rdbms.sql.SelectStatementGenerator) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) ExecutionContext(org.datanucleus.ExecutionContext) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) DiscriminatorStatementGenerator(org.datanucleus.store.rdbms.sql.DiscriminatorStatementGenerator) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass)

Example 27 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class BackingStoreHelper method populateEmbeddedKeyFieldsInStatement.

/**
 * Convenience method to populate the passed PreparedStatement with the field values from
 * the embedded map key starting at the specified jdbc position.
 * @param op ObjectProvider of the owning container
 * @param key The embedded key
 * @param ps The PreparedStatement
 * @param jdbcPosition JDBC position in the statement to start at
 * @param joinTable The Join table where the values are embedded
 * @param mapStore the map store
 * @return The next JDBC position
 */
public static int populateEmbeddedKeyFieldsInStatement(ObjectProvider op, Object key, PreparedStatement ps, int jdbcPosition, JoinTable joinTable, AbstractMapStore mapStore) {
    AbstractClassMetaData kmd = mapStore.getKeyClassMetaData();
    EmbeddedKeyPCMapping embeddedMapping = (EmbeddedKeyPCMapping) mapStore.getKeyMapping();
    StatementClassMapping mappingDefinition = new StatementClassMapping();
    int[] elementFieldNumbers = new int[embeddedMapping.getNumberOfJavaTypeMappings()];
    for (int i = 0; i < embeddedMapping.getNumberOfJavaTypeMappings(); i++) {
        JavaTypeMapping fieldMapping = embeddedMapping.getJavaTypeMapping(i);
        int absFieldNum = kmd.getAbsolutePositionOfMember(fieldMapping.getMemberMetaData().getName());
        elementFieldNumbers[i] = absFieldNum;
        StatementMappingIndex stmtMapping = new StatementMappingIndex(fieldMapping);
        int[] jdbcParamPositions = new int[fieldMapping.getNumberOfDatastoreMappings()];
        for (int j = 0; j < fieldMapping.getNumberOfDatastoreMappings(); j++) {
            jdbcParamPositions[j] = jdbcPosition++;
        }
        stmtMapping.addParameterOccurrence(jdbcParamPositions);
        mappingDefinition.addMappingForMember(absFieldNum, stmtMapping);
    }
    ObjectProvider elementOP = mapStore.getObjectProviderForEmbeddedPCObject(op, key, joinTable.getOwnerMemberMetaData(), ObjectProvider.EMBEDDED_MAP_KEY_PC);
    elementOP.provideFields(elementFieldNumbers, new ParameterSetter(elementOP, ps, mappingDefinition));
    return jdbcPosition;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ObjectProvider(org.datanucleus.state.ObjectProvider) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) EmbeddedKeyPCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedKeyPCMapping) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping)

Example 28 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class BackingStoreHelper method populateEmbeddedValueFieldsInStatement.

/**
 * Convenience method to populate the passed PreparedStatement with the field values from
 * the embedded map value starting at the specified jdbc position.
 * @param op ObjectProvider of the owning container
 * @param value The embedded value
 * @param ps The PreparedStatement
 * @param jdbcPosition JDBC position in the statement to start at
 * @param joinTable The Join table where the values are embedded
 * @param mapStore The map store
 * @return The next JDBC position
 */
public static int populateEmbeddedValueFieldsInStatement(ObjectProvider op, Object value, PreparedStatement ps, int jdbcPosition, JoinTable joinTable, AbstractMapStore mapStore) {
    AbstractClassMetaData vmd = mapStore.getValueClassMetaData();
    EmbeddedValuePCMapping embeddedMapping = (EmbeddedValuePCMapping) mapStore.getValueMapping();
    StatementClassMapping mappingDefinition = new StatementClassMapping();
    int[] elementFieldNumbers = new int[embeddedMapping.getNumberOfJavaTypeMappings()];
    for (int i = 0; i < embeddedMapping.getNumberOfJavaTypeMappings(); i++) {
        JavaTypeMapping fieldMapping = embeddedMapping.getJavaTypeMapping(i);
        int absFieldNum = vmd.getAbsolutePositionOfMember(fieldMapping.getMemberMetaData().getName());
        elementFieldNumbers[i] = absFieldNum;
        StatementMappingIndex stmtMapping = new StatementMappingIndex(fieldMapping);
        int[] jdbcParamPositions = new int[fieldMapping.getNumberOfDatastoreMappings()];
        for (int j = 0; j < fieldMapping.getNumberOfDatastoreMappings(); j++) {
            jdbcParamPositions[j] = jdbcPosition++;
        }
        stmtMapping.addParameterOccurrence(jdbcParamPositions);
        mappingDefinition.addMappingForMember(absFieldNum, stmtMapping);
    }
    ObjectProvider elementOP = mapStore.getObjectProviderForEmbeddedPCObject(op, value, joinTable.getOwnerMemberMetaData(), ObjectProvider.EMBEDDED_MAP_VALUE_PC);
    elementOP.provideFields(elementFieldNumbers, new ParameterSetter(elementOP, ps, mappingDefinition));
    return jdbcPosition;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ObjectProvider(org.datanucleus.state.ObjectProvider) EmbeddedValuePCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedValuePCMapping) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping)

Example 29 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class SQLStatementHelper method selectMemberOfSourceInStatement.

/**
 * Method to select the specified member (field/property) of the source table in the passed SQL
 * statement. This populates the mappingDefinition with the column details for this member.
 * @param stmt The SQL statement
 * @param mappingDefinition Mapping definition for the results (will be populated by any
 *                          selected mappings if provided as input)
 * @param fetchPlan FetchPlan
 * @param sourceSqlTbl Table that has the member (or a super-table/secondary-table of this table)
 * @param mmd Meta-data for the field/property in the source that we are selecting
 * @param clr ClassLoader resolver
 * @param maxFetchPlanLimit Max fetch depth from this point to select (0 implies no other objects)
 * @param inputJoinType Optional join type to use for subobjects (otherwise decide join type internally)
 */
public static void selectMemberOfSourceInStatement(SelectStatement stmt, StatementClassMapping mappingDefinition, FetchPlan fetchPlan, SQLTable sourceSqlTbl, AbstractMemberMetaData mmd, ClassLoaderResolver clr, int maxFetchPlanLimit, JoinType inputJoinType) {
    boolean selectSubobjects = false;
    if (maxFetchPlanLimit > 0) {
        selectSubobjects = true;
    }
    // Set table-group name for any related object we join to (naming based on member name)
    String tableGroupName = sourceSqlTbl.getGroupName() + "." + mmd.getName();
    JavaTypeMapping m = sourceSqlTbl.getTable().getMemberMapping(mmd);
    if (m != null && m.includeInFetchStatement()) {
        RelationType relationType = mmd.getRelationType(clr);
        RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
        DatastoreAdapter dba = storeMgr.getDatastoreAdapter();
        if (!dba.validToSelectMappingInStatement(stmt, m)) {
            // Not valid to select this mapping for this statement so return
            return;
        }
        MetaDataManager mmgr = storeMgr.getMetaDataManager();
        StatementMappingIndex stmtMapping = new StatementMappingIndex(m);
        if (m.getNumberOfDatastoreMappings() > 0) {
            // Select of fields with columns in source table(s)
            // Adds inner/outer join to any required superclass/secondary tables
            SQLTable sqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(stmt, sourceSqlTbl, m);
            boolean selectFK = true;
            if (selectSubobjects && (relationType == RelationType.ONE_TO_ONE_UNI || (relationType == RelationType.ONE_TO_ONE_BI && mmd.getMappedBy() == null)) && !mmd.isSerialized() && !mmd.isEmbedded()) {
                // Related object with FK at this side
                selectFK = selectFetchPlanFieldsOfFKRelatedObject(stmt, mappingDefinition, fetchPlan, sourceSqlTbl, mmd, clr, maxFetchPlanLimit, m, tableGroupName, stmtMapping, sqlTbl, inputJoinType);
            } else if (selectSubobjects && (!mmd.isEmbedded() && !mmd.isSerialized()) && relationType == RelationType.MANY_TO_ONE_BI) {
                AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                if (mmd.getJoinMetaData() != null || relatedMmds[0].getJoinMetaData() != null) {
                    // N-1 bidirectional join table relation
                    // TODO Add left outer join from {sourceTable}.ID to {joinTable}.ELEM_FK
                    Table joinTable = storeMgr.getTable(relatedMmds[0]);
                    DatastoreElementContainer collTable = (DatastoreElementContainer) joinTable;
                    JavaTypeMapping selectMapping = collTable.getOwnerMapping();
                    SQLTable joinSqlTbl = null;
                    if (stmt.getPrimaryTable().getTable() != joinTable) {
                        // Join to the join table
                        JavaTypeMapping referenceMapping = collTable.getElementMapping();
                        joinSqlTbl = stmt.join(JoinType.LEFT_OUTER_JOIN, sourceSqlTbl, sourceSqlTbl.getTable().getIdMapping(), collTable, null, referenceMapping, null, tableGroupName, true);
                    } else {
                        // Main table of the statement is the join table so no need to join
                        joinSqlTbl = stmt.getPrimaryTable();
                    }
                    // Select the owner mapping of the join table
                    int[] colNumbers = stmt.select(joinSqlTbl, selectMapping, null);
                    stmtMapping.setColumnPositions(colNumbers);
                // TODO Join to 1 side from join table?
                } else {
                    // N-1 bidirectional FK relation
                    // Related object with FK at this side, so join/select related object as required
                    selectFK = selectFetchPlanFieldsOfFKRelatedObject(stmt, mappingDefinition, fetchPlan, sourceSqlTbl, mmd, clr, maxFetchPlanLimit, m, tableGroupName, stmtMapping, sqlTbl, inputJoinType);
                }
            }
            if (selectFK) {
                int[] colNumbers = stmt.select(sqlTbl, m, null);
                stmtMapping.setColumnPositions(colNumbers);
            }
        } else {
            // Select of related objects with FK in other table
            if (relationType == RelationType.ONE_TO_ONE_BI && mmd.getMappedBy() != null) {
                // 1-1 bidirectional relation with FK in related table
                AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                AbstractMemberMetaData relatedMmd = relatedMmds[0];
                String[] clsNames = null;
                if (mmd.getType().isInterface()) {
                    if (mmd.getFieldTypes() != null && mmd.getFieldTypes().length == 1) {
                        // Use field-type since only one class specified
                        Class fldTypeCls = clr.classForName(mmd.getFieldTypes()[0]);
                        if (fldTypeCls.isInterface()) {
                            // User has specified an interface, so find its implementations
                            clsNames = mmgr.getClassesImplementingInterface(mmd.getFieldTypes()[0], clr);
                        } else {
                            // Use user-provided field-type
                            clsNames = new String[] { mmd.getFieldTypes()[0] };
                        }
                    }
                    if (clsNames == null) {
                        clsNames = mmgr.getClassesImplementingInterface(mmd.getTypeName(), clr);
                    }
                } else {
                    String typeName = mmd.isSingleCollection() ? mmd.getCollection().getElementType() : mmd.getTypeName();
                    clsNames = new String[] { typeName };
                }
                DatastoreClass relatedTbl = storeMgr.getDatastoreClass(clsNames[0], clr);
                JavaTypeMapping relatedMapping = relatedTbl.getMemberMapping(relatedMmd);
                JavaTypeMapping relatedDiscrimMapping = relatedTbl.getSurrogateMapping(SurrogateColumnType.DISCRIMINATOR, true);
                Object[] discrimValues = null;
                JavaTypeMapping relatedTypeMapping = null;
                AbstractClassMetaData relatedCmd = relatedMmd.getAbstractClassMetaData();
                if (relatedDiscrimMapping != null && (relatedCmd.getSuperAbstractClassMetaData() != null || !relatedCmd.getFullClassName().equals(mmd.getTypeName()))) {
                    // Related table has a discriminator and the field can store other types
                    List discValueList = null;
                    for (String clsName : clsNames) {
                        List values = getDiscriminatorValuesForMember(clsName, relatedDiscrimMapping, storeMgr, clr);
                        if (discValueList == null) {
                            discValueList = values;
                        } else {
                            discValueList.addAll(values);
                        }
                    }
                    if (discValueList != null) {
                        discrimValues = discValueList.toArray(new Object[discValueList.size()]);
                    }
                } else if (relatedTbl != relatedMapping.getTable()) {
                    // The relation is to a base class table, and the type stored is a sub-class
                    relatedTypeMapping = relatedTbl.getIdMapping();
                }
                SQLTable relatedSqlTbl = null;
                if (relatedTypeMapping == null) {
                    // Join the 1-1 relation
                    JoinType joinType = getJoinTypeForOneToOneRelationJoin(sourceSqlTbl.getTable().getIdMapping(), sourceSqlTbl, inputJoinType);
                    if (joinType == JoinType.LEFT_OUTER_JOIN || joinType == JoinType.RIGHT_OUTER_JOIN) {
                        inputJoinType = joinType;
                    }
                    relatedSqlTbl = addJoinForOneToOneRelation(stmt, sourceSqlTbl.getTable().getIdMapping(), sourceSqlTbl, relatedMapping, relatedTbl, null, discrimValues, tableGroupName, joinType);
                    // Select the id mapping in the related table
                    int[] colNumbers = stmt.select(relatedSqlTbl, relatedTbl.getIdMapping(), null);
                    stmtMapping.setColumnPositions(colNumbers);
                } else {
                    DatastoreClass relationTbl = (DatastoreClass) relatedMapping.getTable();
                    if (relatedTbl != relatedMapping.getTable()) {
                        if (relatedMapping.isNullable()) {
                            // Nullable - left outer join from {sourceTable}.ID to {relatedBaseTable}.FK
                            // and inner join from {relatedBaseTable}.ID to {relatedTable}.ID
                            // (joins the relation and restricts to the right type)
                            relatedSqlTbl = stmt.join(JoinType.LEFT_OUTER_JOIN, sourceSqlTbl, sourceSqlTbl.getTable().getIdMapping(), relatedMapping.getTable(), null, relatedMapping, null, tableGroupName, true);
                            relatedSqlTbl = stmt.join(JoinType.INNER_JOIN, relatedSqlTbl, relatedMapping.getTable().getIdMapping(), relatedTbl, null, relatedTbl.getIdMapping(), null, tableGroupName, true);
                        } else {
                            // Not nullable - inner join from {sourceTable}.ID to {relatedBaseTable}.FK
                            // and inner join from {relatedBaseTable}.ID to {relatedTable}.ID
                            // (joins the relation and restricts to the right type)
                            relatedSqlTbl = stmt.join(JoinType.INNER_JOIN, sourceSqlTbl, sourceSqlTbl.getTable().getIdMapping(), relatedMapping.getTable(), null, relatedMapping, null, tableGroupName, true);
                            relatedSqlTbl = stmt.join(JoinType.INNER_JOIN, relatedSqlTbl, relatedMapping.getTable().getIdMapping(), relatedTbl, null, relatedTbl.getIdMapping(), null, tableGroupName, true);
                        }
                    } else {
                        // Join the 1-1 relation
                        JoinType joinType = getJoinTypeForOneToOneRelationJoin(sourceSqlTbl.getTable().getIdMapping(), sourceSqlTbl, inputJoinType);
                        if (joinType == JoinType.LEFT_OUTER_JOIN || joinType == JoinType.RIGHT_OUTER_JOIN) {
                            inputJoinType = joinType;
                        }
                        relatedSqlTbl = addJoinForOneToOneRelation(stmt, sourceSqlTbl.getTable().getIdMapping(), sourceSqlTbl, relatedMapping, relationTbl, null, null, tableGroupName, joinType);
                    }
                    // Select the id mapping in the subclass of the related table
                    // Note this adds an inner join from relatedTable to its subclass
                    relatedSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(stmt, relatedSqlTbl, relatedTbl.getIdMapping());
                    int[] colNumbers = stmt.select(relatedSqlTbl, relatedTbl.getIdMapping(), null);
                    stmtMapping.setColumnPositions(colNumbers);
                }
                if (selectSubobjects && !mmd.isSerialized() && !mmd.isEmbedded()) {
                    // Select the fetch-plan fields of the related object
                    StatementClassMapping subMappingDefinition = new StatementClassMapping(null, mmd.getName());
                    selectFetchPlanOfSourceClassInStatement(stmt, subMappingDefinition, fetchPlan, relatedSqlTbl, relatedMmd.getAbstractClassMetaData(), maxFetchPlanLimit - 1, inputJoinType);
                    if (mappingDefinition != null) {
                        mappingDefinition.addMappingDefinitionForMember(mmd.getAbsoluteFieldNumber(), subMappingDefinition);
                    }
                }
            } else if (relationType == RelationType.MANY_TO_ONE_BI) {
                AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                if (mmd.getJoinMetaData() != null || relatedMmds[0].getJoinMetaData() != null) {
                    // N-1 bidirectional join table relation
                    // Add left outer join from {sourceTable}.ID to {joinTable}.ELEM_FK
                    Table joinTable = storeMgr.getTable(relatedMmds[0]);
                    DatastoreElementContainer collTable = (DatastoreElementContainer) joinTable;
                    JavaTypeMapping selectMapping = collTable.getOwnerMapping();
                    SQLTable joinSqlTbl = null;
                    if (stmt.getPrimaryTable().getTable() != joinTable) {
                        // Join to the join table
                        JavaTypeMapping referenceMapping = collTable.getElementMapping();
                        if (referenceMapping instanceof ReferenceMapping) {
                            // Join table has a reference mapping pointing to our table, so get the submapping for the implementation
                            ReferenceMapping refMap = (ReferenceMapping) referenceMapping;
                            Class implType = clr.classForName(mmd.getClassName(true));
                            referenceMapping = refMap.getJavaTypeMappingForType(implType);
                        }
                        joinSqlTbl = stmt.join(JoinType.LEFT_OUTER_JOIN, sourceSqlTbl, sourceSqlTbl.getTable().getIdMapping(), collTable, null, referenceMapping, null, tableGroupName + "_JOIN", true);
                    } else {
                        // Main table of the statement is the join table so no need to join
                        joinSqlTbl = stmt.getPrimaryTable();
                    }
                    // Select the owner mapping of the join table
                    int[] colNumbers = stmt.select(joinSqlTbl, selectMapping, null);
                    stmtMapping.setColumnPositions(colNumbers);
                }
            // TODO Select fetch plan fields of this related object
            } else if (relationType == RelationType.MANY_TO_ONE_UNI) {
                // Add left outer join from {sourceTable}.ID to {joinTable}.OWNER_FK
                PersistableJoinTable joinTable = (PersistableJoinTable) storeMgr.getTable(mmd);
                SQLTable joinSqlTbl = stmt.join(JoinType.LEFT_OUTER_JOIN, sourceSqlTbl, sourceSqlTbl.getTable().getIdMapping(), joinTable, null, joinTable.getOwnerMapping(), null, tableGroupName + "_JOIN", true);
                int[] colNumbers = stmt.select(joinSqlTbl, joinTable.getRelatedMapping(), null);
                stmtMapping.setColumnPositions(colNumbers);
            // TODO Select fetch plan fields of this related object
            }
        }
        if (mappingDefinition != null) {
            mappingDefinition.addMappingForMember(mmd.getAbsoluteFieldNumber(), stmtMapping);
        }
    }
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) RelationType(org.datanucleus.metadata.RelationType) List(java.util.List) ArrayList(java.util.ArrayList) PersistableJoinTable(org.datanucleus.store.rdbms.table.PersistableJoinTable) Table(org.datanucleus.store.rdbms.table.Table) JoinTable(org.datanucleus.store.rdbms.table.JoinTable) DatastoreElementContainer(org.datanucleus.store.rdbms.table.DatastoreElementContainer) MetaDataManager(org.datanucleus.metadata.MetaDataManager) JoinType(org.datanucleus.store.rdbms.sql.SQLJoin.JoinType) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter) SecondaryDatastoreClass(org.datanucleus.store.rdbms.table.SecondaryDatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) PersistableJoinTable(org.datanucleus.store.rdbms.table.PersistableJoinTable) SecondaryDatastoreClass(org.datanucleus.store.rdbms.table.SecondaryDatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 30 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class SQLStatementHelper method selectFetchPlanFieldsOfFKRelatedObject.

/**
 * Convenience method to join to and select all required FP fields of a related object where linked via an FK at this side.
 * @return Whether the caller should select the FK themselves (i.e we haven't selected anything)
 */
private static boolean selectFetchPlanFieldsOfFKRelatedObject(SelectStatement stmt, StatementClassMapping mappingDefinition, FetchPlan fetchPlan, SQLTable sourceSqlTbl, AbstractMemberMetaData mmd, ClassLoaderResolver clr, int maxFetchPlanLimit, JavaTypeMapping m, String tableGroupName, StatementMappingIndex stmtMapping, SQLTable sqlTbl, JoinType inputJoinType) {
    boolean selectFK = true;
    if (mmd.fetchFKOnly()) {
    // Only want FK fetching, and not the fields of the object (so avoid the join)
    } else {
        RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
        Class type = mmd.isSingleCollection() ? clr.classForName(mmd.getCollection().getElementType()) : mmd.getType();
        if (m instanceof ReferenceMapping) {
            ReferenceMapping refMapping = (ReferenceMapping) m;
            if (refMapping.getMappingStrategy() == ReferenceMapping.PER_IMPLEMENTATION_MAPPING && refMapping.getJavaTypeMapping().length == 1) {
                JavaTypeMapping[] subMappings = refMapping.getJavaTypeMapping();
                if (subMappings != null && subMappings.length == 1) {
                    // Special case of reference mapping with single FK implementation
                    type = clr.classForName(refMapping.getJavaTypeMapping()[0].getType());
                }
            }
        }
        // select fetch plan fields of this object
        AbstractClassMetaData relatedCmd = storeMgr.getMetaDataManager().getMetaDataForClass(type, clr);
        if (relatedCmd != null) {
            if (relatedCmd.isEmbeddedOnly()) {
                return true;
            }
            if (relatedCmd.getBaseAbstractClassMetaData().getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
                // Related object uses complete-table
                Collection<String> relSubclassNames = storeMgr.getSubClassesForClass(relatedCmd.getFullClassName(), true, clr);
                if (relatedCmd.isMappedSuperclass() && relSubclassNames.size() > 1) {
                    // Multiple possible related types and we don't have the FK so omit
                    return true;
                } else if (!relatedCmd.isMappedSuperclass() && relSubclassNames.size() > 0) {
                    // Multiple possible related types and we don't have the FK so omit
                    return true;
                }
            // TODO Maybe do a LEFT OUTER JOIN to each possible?
            }
            // Find the table of the related class
            DatastoreClass relatedTbl = storeMgr.getDatastoreClass(relatedCmd.getFullClassName(), clr);
            if (relatedTbl == null) {
                // Class doesn't have its own table (subclass-table) so find where it persists
                AbstractClassMetaData[] ownerParentCmds = storeMgr.getClassesManagingTableForClass(relatedCmd, clr);
                if (ownerParentCmds.length > 1) {
                    NucleusLogger.QUERY.info("Relation (" + mmd.getFullFieldName() + ") with multiple related tables (using subclass-table). Not supported so selecting FK of related object only");
                    return true;
                }
                relatedTbl = storeMgr.getDatastoreClass(ownerParentCmds[0].getFullClassName(), clr);
            }
            String requiredGroupName = null;
            if (sourceSqlTbl.getGroupName() != null) {
                // JPQL will have table groups defined already, named as per "alias.fieldName"
                requiredGroupName = sourceSqlTbl.getGroupName() + "." + mmd.getName();
            }
            SQLTable relatedSqlTbl = stmt.getTable(relatedTbl, requiredGroupName);
            if (relatedSqlTbl == null) {
                // Join the 1-1 relation
                JoinType joinType = getJoinTypeForOneToOneRelationJoin(m, sqlTbl, inputJoinType);
                if (joinType == JoinType.LEFT_OUTER_JOIN || joinType == JoinType.RIGHT_OUTER_JOIN) {
                    inputJoinType = joinType;
                }
                relatedSqlTbl = addJoinForOneToOneRelation(stmt, m, sqlTbl, relatedTbl.getIdMapping(), relatedTbl, null, null, tableGroupName, joinType);
            }
            StatementClassMapping subMappingDefinition = new StatementClassMapping(mmd.getClassName(), mmd.getName());
            selectFetchPlanOfSourceClassInStatement(stmt, subMappingDefinition, fetchPlan, relatedSqlTbl, relatedCmd, maxFetchPlanLimit - 1, inputJoinType);
            if (mappingDefinition != null) {
                if (relatedCmd.getIdentityType() == IdentityType.APPLICATION) {
                    int[] pkFields = relatedCmd.getPKMemberPositions();
                    int[] pkCols = new int[m.getNumberOfDatastoreMappings()];
                    int pkColNo = 0;
                    for (int pkField : pkFields) {
                        StatementMappingIndex pkIdx = subMappingDefinition.getMappingForMemberPosition(pkField);
                        int[] pkColNumbers = pkIdx.getColumnPositions();
                        for (int pkColNumber : pkColNumbers) {
                            pkCols[pkColNo] = pkColNumber;
                            pkColNo++;
                        }
                    }
                    selectFK = false;
                    stmtMapping.setColumnPositions(pkCols);
                } else if (relatedCmd.getIdentityType() == IdentityType.DATASTORE) {
                    StatementMappingIndex pkIdx = subMappingDefinition.getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
                    selectFK = false;
                    stmtMapping.setColumnPositions(pkIdx.getColumnPositions());
                }
                mappingDefinition.addMappingDefinitionForMember(mmd.getAbsoluteFieldNumber(), subMappingDefinition);
            }
        } else {
        // TODO 1-1 interface relation
        }
    }
    return selectFK;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) JoinType(org.datanucleus.store.rdbms.sql.SQLJoin.JoinType) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) SecondaryDatastoreClass(org.datanucleus.store.rdbms.table.SecondaryDatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) SecondaryDatastoreClass(org.datanucleus.store.rdbms.table.SecondaryDatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass)

Aggregations

StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)37 ExecutionContext (org.datanucleus.ExecutionContext)25 StatementClassMapping (org.datanucleus.store.rdbms.query.StatementClassMapping)24 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)21 PreparedStatement (java.sql.PreparedStatement)19 SQLException (java.sql.SQLException)19 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)19 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)19 SQLController (org.datanucleus.store.rdbms.SQLController)19 ResultSet (java.sql.ResultSet)16 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)14 ObjectProvider (org.datanucleus.state.ObjectProvider)14 SelectStatement (org.datanucleus.store.rdbms.sql.SelectStatement)14 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)11 ParameterSetter (org.datanucleus.store.rdbms.fieldmanager.ParameterSetter)11 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)11 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)10 PersistentClassROF (org.datanucleus.store.rdbms.query.PersistentClassROF)10 ResultObjectFactory (org.datanucleus.store.rdbms.query.ResultObjectFactory)10 MappedDatastoreException (org.datanucleus.store.rdbms.exceptions.MappedDatastoreException)9