Search in sources :

Example 6 with SQLStatement

use of org.datanucleus.store.rdbms.sql.SQLStatement in project datanucleus-rdbms by datanucleus.

the class FKMapStore method getValue.

/**
 * Method to retrieve a value from the Map given the key.
 * @param ownerOP ObjectProvider for the owner of the map.
 * @param key The key to retrieve the value for.
 * @return The value for this key
 * @throws NoSuchElementException if the key was not found
 */
protected V getValue(ObjectProvider ownerOP, Object key) throws NoSuchElementException {
    if (!validateKeyForReading(ownerOP, key)) {
        return null;
    }
    ExecutionContext ec = ownerOP.getExecutionContext();
    if (getStmtLocked == null) {
        synchronized (// Make sure this completes in case another thread needs the same info
        this) {
            // Generate the statement, and statement mapping/parameter information
            SQLStatement sqlStmt = getSQLStatementForGet(ownerOP);
            getStmtUnlocked = sqlStmt.getSQLText().toSQL();
            sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
            getStmtLocked = sqlStmt.getSQLText().toSQL();
        }
    }
    Transaction tx = ec.getTransaction();
    String stmt = (tx.getSerializeRead() != null && tx.getSerializeRead() ? getStmtLocked : getStmtUnlocked);
    Object value = null;
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement and supply owner/key params
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            StatementMappingIndex ownerIdx = getMappingParams.getMappingForParameter("owner");
            int numParams = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerOP.getObject());
            }
            StatementMappingIndex keyIdx = getMappingParams.getMappingForParameter("key");
            numParams = keyIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                keyIdx.getMapping().setObject(ec, ps, keyIdx.getParameterPositionsForOccurrence(paramInstance), key);
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    boolean found = rs.next();
                    if (!found) {
                        throw new NoSuchElementException();
                    }
                    if (valuesAreEmbedded || valuesAreSerialised) {
                        int[] param = new int[valueMapping.getNumberOfDatastoreMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        if (valueMapping instanceof SerialisedPCMapping || valueMapping instanceof SerialisedReferenceMapping || valueMapping instanceof EmbeddedKeyPCMapping) {
                            // Value = Serialised
                            value = valueMapping.getObject(ec, rs, param, ownerOP, ((JoinTable) mapTable).getOwnerMemberMetaData().getAbsoluteFieldNumber());
                        } else {
                            // Value = Non-PC
                            value = valueMapping.getObject(ec, rs, param);
                        }
                    } else if (valueMapping instanceof ReferenceMapping) {
                        // Value = Reference (Interface/Object)
                        int[] param = new int[valueMapping.getNumberOfDatastoreMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        value = valueMapping.getObject(ec, rs, param);
                    } else {
                        // Value = PC
                        ResultObjectFactory rof = new PersistentClassROF(ec, rs, false, getMappingDef, valueCmd, clr.classForName(valueType));
                        value = rof.getObject();
                    }
                    JDBCUtils.logWarnings(rs);
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056014", stmt), e);
    }
    return (V) value;
}
Also used : SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) SQLException(java.sql.SQLException) ResultObjectFactory(org.datanucleus.store.rdbms.query.ResultObjectFactory) PreparedStatement(java.sql.PreparedStatement) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) Transaction(org.datanucleus.Transaction) PersistentClassROF(org.datanucleus.store.rdbms.query.PersistentClassROF) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) SerialisedPCMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedPCMapping) NoSuchElementException(java.util.NoSuchElementException) EmbeddedKeyPCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedKeyPCMapping)

Example 7 with SQLStatement

use of org.datanucleus.store.rdbms.sql.SQLStatement in project datanucleus-rdbms by datanucleus.

the class JoinMapStore method getValue.

/**
 * Method to retrieve a value from the Map given the key.
 * @param ownerOP ObjectProvider for the owner of the map.
 * @param key The key to retrieve the value for.
 * @return The value for this key
 * @throws NoSuchElementException if the value for the key was not found
 */
protected V getValue(ObjectProvider ownerOP, Object key) throws NoSuchElementException {
    if (!validateKeyForReading(ownerOP, key)) {
        return null;
    }
    ExecutionContext ec = ownerOP.getExecutionContext();
    if (getStmtLocked == null) {
        synchronized (// Make sure this completes in case another thread needs the same info
        this) {
            // Generate the statement, and statement mapping/parameter information
            SQLStatement sqlStmt = getSQLStatementForGet(ownerOP);
            getStmtUnlocked = sqlStmt.getSQLText().toSQL();
            sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
            getStmtLocked = sqlStmt.getSQLText().toSQL();
        }
    }
    Transaction tx = ec.getTransaction();
    String stmt = (tx.getSerializeRead() != null && tx.getSerializeRead() ? getStmtLocked : getStmtUnlocked);
    Object value = null;
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement and supply owner/key params
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            StatementMappingIndex ownerIdx = getMappingParams.getMappingForParameter("owner");
            int numParams = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerOP.getObject());
            }
            StatementMappingIndex keyIdx = getMappingParams.getMappingForParameter("key");
            numParams = keyIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                keyIdx.getMapping().setObject(ec, ps, keyIdx.getParameterPositionsForOccurrence(paramInstance), key);
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    boolean found = rs.next();
                    if (!found) {
                        throw new NoSuchElementException();
                    }
                    if (valuesAreEmbedded || valuesAreSerialised) {
                        int[] param = new int[valueMapping.getNumberOfDatastoreMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        if (valueMapping instanceof SerialisedPCMapping || valueMapping instanceof SerialisedReferenceMapping || valueMapping instanceof EmbeddedKeyPCMapping) {
                            // Value = Serialised
                            int ownerFieldNumber = ((JoinTable) mapTable).getOwnerMemberMetaData().getAbsoluteFieldNumber();
                            value = valueMapping.getObject(ec, rs, param, ownerOP, ownerFieldNumber);
                        } else {
                            // Value = Non-PC
                            value = valueMapping.getObject(ec, rs, param);
                        }
                    } else if (valueMapping instanceof ReferenceMapping) {
                        // Value = Reference (Interface/Object)
                        int[] param = new int[valueMapping.getNumberOfDatastoreMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        value = valueMapping.getObject(ec, rs, param);
                    } else {
                        // Value = PC
                        ResultObjectFactory rof = new PersistentClassROF(ec, rs, false, getMappingDef, valueCmd, clr.classForName(valueType));
                        value = rof.getObject();
                    }
                    JDBCUtils.logWarnings(rs);
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056014", stmt), e);
    }
    return (V) value;
}
Also used : SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) SQLException(java.sql.SQLException) ResultObjectFactory(org.datanucleus.store.rdbms.query.ResultObjectFactory) PreparedStatement(java.sql.PreparedStatement) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) Transaction(org.datanucleus.Transaction) PersistentClassROF(org.datanucleus.store.rdbms.query.PersistentClassROF) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) SerialisedPCMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedPCMapping) NoSuchElementException(java.util.NoSuchElementException) EmbeddedKeyPCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedKeyPCMapping)

Example 8 with SQLStatement

use of org.datanucleus.store.rdbms.sql.SQLStatement in project datanucleus-rdbms by datanucleus.

the class MapEntrySetStore method iterator.

/**
 * Method returning an iterator across the entries in the map for this owner object.
 * @param ownerOP ObjectProvider of the owning object
 * @return The iterator for the entries (<pre>map.entrySet().iterator()</pre>).
 */
public Iterator<Map.Entry<K, V>> iterator(ObjectProvider ownerOP) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    if (iteratorStmtLocked == null) {
        synchronized (// Make sure this completes in case another thread needs the same info
        this) {
            // Generate the statement, and statement mapping/parameter information
            SQLStatement sqlStmt = getSQLStatementForIterator(ownerOP);
            iteratorStmtUnlocked = sqlStmt.getSQLText().toSQL();
            sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
            iteratorStmtLocked = sqlStmt.getSQLText().toSQL();
        }
    }
    Transaction tx = ec.getTransaction();
    String stmt = (tx.getSerializeRead() != null && tx.getSerializeRead() ? iteratorStmtLocked : iteratorStmtUnlocked);
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement and set the owner
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            StatementMappingIndex ownerIdx = iteratorMappingParams.getMappingForParameter("owner");
            int numParams = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerOP.getObject());
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    return new SetIterator(ownerOP, this, ownerMemberMetaData, rs, iteratorKeyResultCols, iteratorValueResultCols) {

                        protected boolean next(Object rs) throws MappedDatastoreException {
                            try {
                                return ((ResultSet) rs).next();
                            } catch (SQLException e) {
                                throw new MappedDatastoreException("SQLException", e);
                            }
                        }
                    };
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException("Iteration request failed: " + stmt, e);
    } catch (MappedDatastoreException e) {
        throw new NucleusDataStoreException("Iteration request failed: " + stmt, e);
    }
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) Transaction(org.datanucleus.Transaction) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection)

Example 9 with SQLStatement

use of org.datanucleus.store.rdbms.sql.SQLStatement in project datanucleus-rdbms by datanucleus.

the class MapKeySetStore method iterator.

/**
 * Accessor for an iterator for the set.
 * @param ownerOP ObjectProvider for the set.
 * @return Iterator for the set.
 */
public Iterator<K> iterator(ObjectProvider ownerOP) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    if (iteratorStmtLocked == null) {
        synchronized (// Make sure this completes in case another thread needs the same info
        this) {
            // Generate the statement, and statement mapping/parameter information
            SQLStatement sqlStmt = getSQLStatementForIterator(ownerOP);
            iteratorStmtUnlocked = sqlStmt.getSQLText().toSQL();
            sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
            iteratorStmtLocked = sqlStmt.getSQLText().toSQL();
        }
    }
    Transaction tx = ec.getTransaction();
    String stmt = (tx.getSerializeRead() != null && tx.getSerializeRead() ? iteratorStmtLocked : iteratorStmtUnlocked);
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement and set the owner
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            StatementMappingIndex ownerIdx = iteratorMappingParams.getMappingForParameter("owner");
            int numParams = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerOP.getObject());
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    ResultObjectFactory rof = null;
                    if (elementsAreEmbedded || elementsAreSerialised) {
                        // No ResultObjectFactory needed - handled by SetStoreIterator
                        return new CollectionStoreIterator(ownerOP, rs, null, this);
                    }
                    rof = new PersistentClassROF(ec, rs, false, iteratorMappingDef, elementCmd, clr.classForName(elementType));
                    return new CollectionStoreIterator(ownerOP, rs, rof, this);
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056006", stmt), e);
    } catch (MappedDatastoreException e) {
        throw new NucleusDataStoreException(Localiser.msg("056006", stmt), e);
    }
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) SQLException(java.sql.SQLException) ResultObjectFactory(org.datanucleus.store.rdbms.query.ResultObjectFactory) PreparedStatement(java.sql.PreparedStatement) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) Transaction(org.datanucleus.Transaction) PersistentClassROF(org.datanucleus.store.rdbms.query.PersistentClassROF) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection)

Example 10 with SQLStatement

use of org.datanucleus.store.rdbms.sql.SQLStatement in project datanucleus-rdbms by datanucleus.

the class ExpressionUtils method getEqualityExpressionForObjectExpressions.

/**
 * Method to generate an equality/inequality expression between two ObjectExpressions.
 * Either or both of the expressions can be ObjectLiterals.
 * @param expr1 First expression
 * @param expr2 Second expression
 * @param equals Whether it is equality (otherwise inequality)
 * @return The expression
 */
public static BooleanExpression getEqualityExpressionForObjectExpressions(ObjectExpression expr1, ObjectExpression expr2, boolean equals) {
    SQLStatement stmt = expr1.stmt;
    RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
    SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
    ClassLoaderResolver clr = stmt.getClassLoaderResolver();
    ApiAdapter api = storeMgr.getApiAdapter();
    if (expr1 instanceof ObjectLiteral && expr2 instanceof ObjectLiteral) {
        // ObjectLiterall == ObjectLiteral
        ObjectLiteral lit1 = (ObjectLiteral) expr1;
        ObjectLiteral lit2 = (ObjectLiteral) expr2;
        return new BooleanLiteral(stmt, expr1.mapping, equals ? lit1.getValue().equals(lit2.getValue()) : !lit1.getValue().equals(lit2.getValue()));
    } else if (expr1 instanceof ObjectLiteral || expr2 instanceof ObjectLiteral) {
        // ObjectExpression == ObjectLiteral, ObjectLiteral == ObjectExpression
        BooleanExpression bExpr = null;
        boolean secondIsLiteral = (expr2 instanceof ObjectLiteral);
        Object value = (!secondIsLiteral ? ((ObjectLiteral) expr1).getValue() : ((ObjectLiteral) expr2).getValue());
        if (IdentityUtils.isDatastoreIdentity(value)) {
            // Object is an OID
            Object valueKey = IdentityUtils.getTargetKeyForDatastoreIdentity(value);
            JavaTypeMapping m = storeMgr.getSQLExpressionFactory().getMappingForType(valueKey.getClass(), false);
            SQLExpression oidLit = exprFactory.newLiteral(stmt, m, valueKey);
            if (equals) {
                return (secondIsLiteral ? expr1.subExprs.getExpression(0).eq(oidLit) : expr2.subExprs.getExpression(0).eq(oidLit));
            }
            return (secondIsLiteral ? expr1.subExprs.getExpression(0).ne(oidLit) : expr2.subExprs.getExpression(0).ne(oidLit));
        } else if (IdentityUtils.isSingleFieldIdentity(value)) {
            // Object is SingleFieldIdentity
            Object valueKey = IdentityUtils.getTargetKeyForSingleFieldIdentity(value);
            // This used to use ((SingleFieldId)value).getTargetClass() for some reason, which contradicts the above datastore id method
            JavaTypeMapping m = storeMgr.getSQLExpressionFactory().getMappingForType(valueKey.getClass(), false);
            SQLExpression oidLit = exprFactory.newLiteral(stmt, m, valueKey);
            if (equals) {
                return (secondIsLiteral ? expr1.subExprs.getExpression(0).eq(oidLit) : expr2.subExprs.getExpression(0).eq(oidLit));
            }
            return (secondIsLiteral ? expr1.subExprs.getExpression(0).ne(oidLit) : expr2.subExprs.getExpression(0).ne(oidLit));
        } else {
            AbstractClassMetaData cmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(value.getClass(), clr);
            if (cmd != null) {
                // Value is a persistable object
                if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                    // Application identity
                    if (api.getIdForObject(value) != null) {
                        // Persistent PC object (FCO)
                        // Cater for composite PKs and parts of PK being PC mappings, and recursion
                        ObjectExpression expr = (secondIsLiteral ? expr1 : expr2);
                        JavaTypeMapping[] pkMappingsApp = new JavaTypeMapping[expr.subExprs.size()];
                        Object[] pkFieldValues = new Object[expr.subExprs.size()];
                        int position = 0;
                        ExecutionContext ec = api.getExecutionContext(value);
                        JavaTypeMapping thisMapping = expr.mapping;
                        if (expr.mapping instanceof ReferenceMapping) {
                            // "InterfaceField == value", so pick an implementation mapping that is castable
                            thisMapping = null;
                            ReferenceMapping refMapping = (ReferenceMapping) expr.mapping;
                            JavaTypeMapping[] implMappings = refMapping.getJavaTypeMapping();
                            for (int i = 0; i < implMappings.length; i++) {
                                Class implType = clr.classForName(implMappings[i].getType());
                                if (implType.isAssignableFrom(value.getClass())) {
                                    thisMapping = implMappings[i];
                                    break;
                                }
                            }
                        }
                        if (thisMapping == null) {
                            // Just return a (1=0) since no implementation castable
                            return exprFactory.newLiteral(stmt, expr1.mapping, false).eq(exprFactory.newLiteral(stmt, expr1.mapping, true));
                        }
                        for (int i = 0; i < cmd.getNoOfPrimaryKeyMembers(); i++) {
                            AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(cmd.getPKMemberPositions()[i]);
                            Object fieldValue = ExpressionUtils.getValueForMemberOfObject(ec, mmd, value);
                            JavaTypeMapping mapping = ((PersistableMapping) thisMapping).getJavaTypeMapping()[i];
                            if (mapping instanceof PersistableMapping) {
                                position = ExpressionUtils.populatePrimaryKeyMappingsValuesForPCMapping(pkMappingsApp, pkFieldValues, position, (PersistableMapping) mapping, cmd, mmd, fieldValue, storeMgr, clr);
                            } else {
                                pkMappingsApp[position] = mapping;
                                pkFieldValues[position] = fieldValue;
                                position++;
                            }
                        }
                        for (int i = 0; i < expr.subExprs.size(); i++) {
                            SQLExpression source = expr.subExprs.getExpression(i);
                            SQLExpression target = exprFactory.newLiteral(stmt, pkMappingsApp[i], pkFieldValues[i]);
                            BooleanExpression subExpr = (secondIsLiteral ? source.eq(target) : target.eq(source));
                            if (bExpr == null) {
                                bExpr = subExpr;
                            } else {
                                bExpr = bExpr.and(subExpr);
                            }
                        }
                    } else {
                        // PC object with no id (embedded, or transient maybe)
                        if (secondIsLiteral) {
                            for (int i = 0; i < expr1.subExprs.size(); i++) {
                                // Query should return nothing (so just do "(1 = 0)")
                                NucleusLogger.QUERY.warn(Localiser.msg("037003", value));
                                bExpr = exprFactory.newLiteral(stmt, expr1.mapping, false).eq(exprFactory.newLiteral(stmt, expr1.mapping, true));
                            // It is arguable that we should compare the id with null (as below)
                            /*bExpr = expr.eq(new NullLiteral(qs));*/
                            }
                        } else {
                            for (int i = 0; i < expr2.subExprs.size(); i++) {
                                // Query should return nothing (so just do "(1 = 0)")
                                NucleusLogger.QUERY.warn(Localiser.msg("037003", value));
                                bExpr = exprFactory.newLiteral(stmt, expr2.mapping, false).eq(exprFactory.newLiteral(stmt, expr2.mapping, true));
                            // It is arguable that we should compare the id with null (as below)
                            /*bExpr = expr.eq(new NullLiteral(qs));*/
                            }
                        }
                    }
                    // TODO Allow for !equals
                    return bExpr;
                } else if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                    // Datastore identity
                    SQLExpression source = (secondIsLiteral ? expr1.subExprs.getExpression(0) : expr2.subExprs.getExpression(0));
                    JavaTypeMapping mapping = (secondIsLiteral ? expr1.mapping : expr2.mapping);
                    Object objectId = api.getIdForObject(value);
                    if (objectId == null) {
                        // PC object with no id (embedded, or transient maybe)
                        // Query should return nothing (so just do "(1 = 0)")
                        NucleusLogger.QUERY.warn(Localiser.msg("037003", value));
                        // TODO Allow for !equals
                        return exprFactory.newLiteral(stmt, mapping, false).eq(exprFactory.newLiteral(stmt, mapping, true));
                    // It is arguable that we should compare the id with null (as below)
                    /*bExpr = expr.eq(new NullLiteral(qs));*/
                    }
                    Object objectIdKey = IdentityUtils.getTargetKeyForDatastoreIdentity(objectId);
                    JavaTypeMapping m = storeMgr.getSQLExpressionFactory().getMappingForType(objectIdKey.getClass(), false);
                    SQLExpression oidExpr = exprFactory.newLiteral(stmt, m, objectIdKey);
                    if (equals) {
                        return source.eq(oidExpr);
                    }
                    return source.ne(oidExpr);
                }
            } else {
                // No metadata, so we either have an application identity, or any object
                String pcClassName = storeMgr.getClassNameForObjectID(value, clr, null);
                if (pcClassName != null) {
                    // Object is an application identity
                    cmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(pcClassName, clr);
                    return (secondIsLiteral ? ExpressionUtils.getAppIdEqualityExpression(value, expr1, storeMgr, clr, cmd, null, null) : ExpressionUtils.getAppIdEqualityExpression(value, expr2, storeMgr, clr, cmd, null, null));
                // TODO Allow for !equals
                }
                // Value not persistable nor an identity, so return nothing "(1 = 0)"
                return exprFactory.newLiteral(stmt, expr1.mapping, false).eq(exprFactory.newLiteral(stmt, expr1.mapping, true));
            // TODO Allow for !equals
            }
        }
    } else {
        // ObjectExpression == ObjectExpression
        BooleanExpression resultExpr = null;
        for (int i = 0; i < expr1.subExprs.size(); i++) {
            SQLExpression sourceExpr = expr1.subExprs.getExpression(i);
            SQLExpression targetExpr = expr2.subExprs.getExpression(i);
            if (resultExpr == null) {
                resultExpr = sourceExpr.eq(targetExpr);
            } else {
                resultExpr = resultExpr.and(sourceExpr.eq(targetExpr));
            }
        }
        if (!equals) {
            resultExpr = new BooleanExpression(Expression.OP_NOT, resultExpr != null ? resultExpr.encloseInParentheses() : null);
        }
        return resultExpr;
    }
    return null;
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) ExecutionContext(org.datanucleus.ExecutionContext) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Aggregations

SQLStatement (org.datanucleus.store.rdbms.sql.SQLStatement)16 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)10 SQLExpression (org.datanucleus.store.rdbms.sql.expression.SQLExpression)10 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)8 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)7 ArrayList (java.util.ArrayList)6 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)6 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)6 ExecutionContext (org.datanucleus.ExecutionContext)5 Expression (org.datanucleus.query.expression.Expression)5 BooleanExpression (org.datanucleus.store.rdbms.sql.expression.BooleanExpression)5 PreparedStatement (java.sql.PreparedStatement)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 HashSet (java.util.HashSet)4 Transaction (org.datanucleus.Transaction)4 SubqueryExpression (org.datanucleus.query.expression.SubqueryExpression)4 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)4 SQLController (org.datanucleus.store.rdbms.SQLController)4 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)4