Search in sources :

Example 6 with TypeConverterMapping

use of org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping in project datanucleus-rdbms by datanucleus.

the class QueryToSQLMapper method processParameterExpression.

/**
 * Method to process a parameter expression.
 * The optional argument controls whether we should create this as a parameter or as a literal (i.e the param value is known etc).
 * If the parameter doesn't have its value defined then returns ParameterLiteral otherwise we get an XXXLiteral of the (declared) type of the parameter
 * @param expr The ParameterExpression
 * @param asLiteral Whether to create a SQLLiteral rather than a parameter literal
 * @return The processed expression
 */
protected Object processParameterExpression(ParameterExpression expr, boolean asLiteral) {
    if (compileComponent == CompilationComponent.ORDERING || compileComponent == CompilationComponent.RESULT) {
        // All JDBC drivers I know don't allow parameters in the order-by, or update clause
        // Note that we also don't allow parameters in result clause since SQLStatement squashes all SELECT expression to a String so losing info about params
        asLiteral = true;
    } else if (compileComponent == CompilationComponent.UPDATE && processingCase && !storeMgr.getDatastoreAdapter().supportsOption(DatastoreAdapter.PARAMETER_IN_CASE_IN_UPDATE_CLAUSE)) {
        // This database doesn't support parameters within a CASE expression in the UPDATE clause, so process as a literal
        asLiteral = true;
    }
    if (expr.getPosition() >= 0) {
        if (paramNameByPosition == null) {
            paramNameByPosition = new HashMap<>();
        }
        paramNameByPosition.put(Integer.valueOf(expr.getPosition()), expr.getId());
    }
    // Find the parameter value if supplied
    Object paramValue = null;
    boolean paramValueSet = false;
    if (parameters != null && parameters.size() > 0) {
        // Check if the parameter has a value
        if (parameters.containsKey(expr.getId())) {
            // Named parameter
            paramValue = parameters.get(expr.getId());
            paramValueSet = true;
        } else if (parameterValueByName != null && parameterValueByName.containsKey(expr.getId())) {
            // Positional parameter, but already encountered
            paramValue = parameterValueByName.get(expr.getId());
            paramValueSet = true;
        } else {
            // Positional parameter, not yet encountered
            int position = positionalParamNumber;
            if (positionalParamNumber < 0) {
                position = 0;
            }
            if (parameters.containsKey(Integer.valueOf(position))) {
                paramValue = parameters.get(Integer.valueOf(position));
                paramValueSet = true;
                positionalParamNumber = position + 1;
                if (parameterValueByName == null) {
                    parameterValueByName = new HashMap<>();
                }
                parameterValueByName.put(expr.getId(), paramValue);
            }
        }
    }
    // Find the type to use for the parameter
    JavaTypeMapping m = paramMappingForName.get(expr.getId());
    if (m == null) {
        // Try to determine from provided parameter value or from symbol table (declared type)
        if (paramValue != null) {
            if (!storeMgr.getMetaDataManager().isClassPersistable(paramValue.getClass().getName()) && !paramValue.getClass().isArray() && !paramValue.getClass().isInterface() && !Collection.class.isAssignableFrom(paramValue.getClass()) && !Map.class.isAssignableFrom(paramValue.getClass()) && !storeMgr.getNucleusContext().getTypeManager().isSupportedSecondClassType(paramValue.getClass().getName())) {
                // Test for this being the "id" of a persistable object
                // Persistable/array/interface/collection/map/simple cannot be an object "id"
                String className = storeMgr.getClassNameForObjectID(paramValue, clr, ec);
                if (className != null) {
                    // Identity for persistable class
                    AbstractClassMetaData cmd = storeMgr.getMetaDataManager().getMetaDataForClass(className, clr);
                    if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        Class cls = clr.classForName(className);
                        m = exprFactory.getMappingForType(cls, false);
                        m = new PersistableIdMapping((PersistableMapping) m);
                    }
                }
            }
            if (m == null) {
                // Use the type of the input parameter value
                try {
                    m = exprFactory.getMappingForType(paramValue.getClass(), false);
                    if (m instanceof TypeConverterMapping && expr.getSymbol().getValueType() != null && expr.getSymbol().getValueType() != m.getJavaType()) {
                        // This is because if we have a parameter of type "ZoneInfo" it needs to use TimeZone since we have the TypeConverter for that
                        try {
                            m = exprFactory.getMappingForType(expr.getSymbol().getValueType(), false);
                        } catch (NucleusUserException nue) {
                        }
                    }
                } catch (NucleusUserException nue) {
                    // Maybe it needs a TypeConverter so try with the (declared) symbol type of this parameter
                    m = exprFactory.getMappingForType(expr.getSymbol().getValueType(), false);
                }
            }
            if (expr.getSymbol() != null && expr.getSymbol().getValueType() != null) {
                if (!QueryUtils.queryParameterTypesAreCompatible(expr.getSymbol().getValueType(), paramValue.getClass())) {
                    throw new QueryCompilerSyntaxException(Localiser.msg("021118", expr.getId(), expr.getSymbol().getValueType().getName(), paramValue.getClass().getName()));
                }
                if (expr.getSymbol().getValueType() != paramValue.getClass()) {
                    // Mark as not precompilable since the supplied type implies a subclass of the declared type
                    setNotPrecompilable();
                }
            }
        } else if (expr.getSymbol() != null && expr.getSymbol().getValueType() != null) {
            Class valueType = expr.getSymbol().getValueType();
            if (!paramValueSet) {
                if (valueType.isInterface()) {
                    // Special case where we have an interface parameter (not set), and don't know the type, so we pick the first implementation just to get something that works
                    // This is recompiled when the parameter is provided so is just for use in "compile()"
                    String[] implNames = storeMgr.getMetaDataManager().getClassesImplementingInterface(valueType.getName(), clr);
                    if (implNames != null && implNames.length > 0) {
                        valueType = clr.classForName(implNames[0]);
                        setNotPrecompilable();
                    }
                }
            }
            // Use the declared type of the parameter (explicit params)
            m = exprFactory.getMappingForType(valueType, false);
        }
    }
    if (asLiteral && m != null && !m.representableAsStringLiteralInStatement()) {
        // Must keep this as a parameter since its String form is no good in statements
        asLiteral = false;
    }
    if (asLiteral) {
        // Parameter being represented as a literal (for whatever reason), so no longer precompilable
        if (isPrecompilable()) {
            NucleusLogger.QUERY.debug("Parameter " + expr + " is being resolved as a literal, so the query is no longer precompilable");
        }
        setNotPrecompilable();
    } else if (paramValue == null && expr.getSymbol() != null) {
        if (isPrecompilable()) {
            NucleusLogger.QUERY.debug("Parameter " + expr + " is set to null so this has to be resolved as a NullLiteral, and the query is no longer precompilable");
        }
        setNotPrecompilable();
    }
    // Create the SQLExpression for this parameter, either as value-literal or as parameter-literal
    SQLExpression sqlExpr = null;
    if (paramValueSet && paramValue == null && options.contains(OPTION_NULL_PARAM_USE_IS_NULL)) {
        // Value is set to null, but we enforce a NullLiteral for the case of null comparisons e.g we don't want "field = ?", but instead "field IS NULL"
        sqlExpr = exprFactory.newLiteral(stmt, null, null);
    } else if (asLiteral) {
        // Create a value-literal as requested
        sqlExpr = exprFactory.newLiteral(stmt, m, paramValue);
    } else {
        // Create a parameter-literal with it tied to the parameter name for later replacement in the statement
        sqlExpr = exprFactory.newLiteralParameter(stmt, m, paramValue, expr.getId());
        if (sqlExpr instanceof ParameterLiteral) {
            ((ParameterLiteral) sqlExpr).setName(expr.getId());
        }
        if (expressionForParameter == null) {
            expressionForParameter = new HashMap<>();
        }
        expressionForParameter.put(expr.getId(), sqlExpr);
        paramMappingForName.put(expr.getId(), m);
    }
    stack.push(sqlExpr);
    return sqlExpr;
}
Also used : ParameterLiteral(org.datanucleus.store.rdbms.sql.expression.ParameterLiteral) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) HashMap(java.util.HashMap) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) PersistableIdMapping(org.datanucleus.store.rdbms.mapping.java.PersistableIdMapping) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) TypeConverterMapping(org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping) QueryCompilerSyntaxException(org.datanucleus.store.query.QueryCompilerSyntaxException) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) FetchPlanForClass(org.datanucleus.FetchPlanForClass) Map(java.util.Map) HashMap(java.util.HashMap)

Example 7 with TypeConverterMapping

use of org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping in project tests by datanucleus.

the class ConvertersTest method testUseOfPersistentConverter.

/**
 * Test the use of "@Persistent(converter="...")" annotation on a field.
 */
public void testUseOfPersistentConverter() {
    try {
        PersistenceNucleusContext nucCtx = ((JDOPersistenceManagerFactory) pmf).getNucleusContext();
        ClassLoaderResolver clr = nucCtx.getClassLoaderResolver(null);
        AbstractClassMetaData cmd = nucCtx.getMetaDataManager().getMetaDataForClass(PersonWithConverters.class, clr);
        // Check the converter is registered with metadata
        AbstractMemberMetaData mmd = cmd.getMetaDataForMember("myBool1");
        assertNotNull(mmd);
        assertTrue(mmd.hasExtension("type-converter-name"));
        String converterName = mmd.getValueForExtension("type-converter-name");
        assertEquals("org.datanucleus.samples.converters.Boolean10Converter", converterName);
        // Check the correct mapping is chosen for this field
        RDBMSStoreManager storeMgr = (RDBMSStoreManager) nucCtx.getStoreManager();
        DatastoreClass tbl = storeMgr.getDatastoreClass(PersonWithConverters.class.getName(), clr);
        JavaTypeMapping mapping = tbl.getMemberMapping(mmd);
        assertTrue(mapping instanceof TypeConverterMapping);
    } catch (Exception e) {
        LOG.error("Exception during test", e);
        fail("Exception was thrown : " + e.getMessage());
    } finally {
    }
}
Also used : TypeConverterMapping(org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) PersonWithConverters(org.datanucleus.samples.converters.PersonWithConverters) PersistenceNucleusContext(org.datanucleus.PersistenceNucleusContext) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) JDOPersistenceManagerFactory(org.datanucleus.api.jdo.JDOPersistenceManagerFactory) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager)

Example 8 with TypeConverterMapping

use of org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping in project tests by datanucleus.

the class ConvertersTest method testUseOfConvert.

/**
 * Test the use of "@Convert" annotation on a field.
 */
public void testUseOfConvert() {
    try {
        PersistenceNucleusContext nucCtx = ((JDOPersistenceManagerFactory) pmf).getNucleusContext();
        ClassLoaderResolver clr = nucCtx.getClassLoaderResolver(null);
        AbstractClassMetaData cmd = nucCtx.getMetaDataManager().getMetaDataForClass(PersonWithConverters.class, clr);
        // Check the converter is registered with metadata
        AbstractMemberMetaData mmd = cmd.getMetaDataForMember("myBool2");
        assertNotNull(mmd);
        assertTrue(mmd.hasExtension("type-converter-name"));
        String converterName = mmd.getValueForExtension("type-converter-name");
        assertEquals("org.datanucleus.samples.converters.BooleanYNConverter", converterName);
        // Check the correct mapping is chosen for this field
        RDBMSStoreManager storeMgr = (RDBMSStoreManager) nucCtx.getStoreManager();
        DatastoreClass tbl = storeMgr.getDatastoreClass(PersonWithConverters.class.getName(), clr);
        JavaTypeMapping mapping = tbl.getMemberMapping(mmd);
        assertTrue(mapping instanceof TypeConverterMapping);
    } catch (Exception e) {
        LOG.error("Exception during test", e);
        fail("Exception was thrown : " + e.getMessage());
    } finally {
    }
}
Also used : TypeConverterMapping(org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) PersonWithConverters(org.datanucleus.samples.converters.PersonWithConverters) PersistenceNucleusContext(org.datanucleus.PersistenceNucleusContext) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) JDOPersistenceManagerFactory(org.datanucleus.api.jdo.JDOPersistenceManagerFactory) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager)

Aggregations

TypeConverterMapping (org.datanucleus.store.rdbms.mapping.java.TypeConverterMapping)8 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)7 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)7 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)5 TypeConverter (org.datanucleus.store.types.converters.TypeConverter)5 NucleusException (org.datanucleus.exceptions.NucleusException)4 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)4 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)4 NoTableManagedException (org.datanucleus.store.rdbms.exceptions.NoTableManagedException)4 PersistableMapping (org.datanucleus.store.rdbms.mapping.java.PersistableMapping)4 TypeConverterMultiMapping (org.datanucleus.store.rdbms.mapping.java.TypeConverterMultiMapping)4 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)2 PersistenceNucleusContext (org.datanucleus.PersistenceNucleusContext)2 JDOPersistenceManagerFactory (org.datanucleus.api.jdo.JDOPersistenceManagerFactory)2 PersonWithConverters (org.datanucleus.samples.converters.PersonWithConverters)2 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 Serializable (java.io.Serializable)1 BigDecimal (java.math.BigDecimal)1