Search in sources :

Example 71 with NucleusException

use of org.datanucleus.exceptions.NucleusException in project datanucleus-rdbms by datanucleus.

the class ObjectExpression method is.

/**
 * An "is" (instanceOf) expression, providing a BooleanExpression whether this expression is an instanceof the provided type.
 * @param expr The expression representing the type
 * @param not Whether the operator is "!instanceof"
 * @return Whether this expression is an instance of the provided type
 */
public BooleanExpression is(SQLExpression expr, boolean not) {
    RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
    ClassLoaderResolver clr = stmt.getClassLoaderResolver();
    // Extract instanceOf type
    String instanceofClassName = null;
    SQLExpression classExpr = expr;
    if (expr instanceof TypeConverterLiteral) {
        // For some reason the user has input "TYPE(field) = :param" and param is a type-converted value
        classExpr = ((TypeConverterLiteral) expr).getDelegate();
    }
    if (classExpr instanceof StringLiteral) {
        instanceofClassName = (String) ((StringLiteral) classExpr).getValue();
    } else if (classExpr instanceof CollectionLiteral) {
        // "a instanceof (b1,b2,b3)"
        CollectionLiteral typesLiteral = (CollectionLiteral) classExpr;
        Collection values = (Collection) typesLiteral.getValue();
        if (values.size() == 1) {
            Object value = values.iterator().next();
            String valueStr = null;
            if (value instanceof Class) {
                valueStr = ((Class) value).getCanonicalName();
            } else if (value instanceof String) {
                valueStr = (String) value;
            } else {
                throw new NucleusUserException("Do not support CollectionLiteral of element type " + value.getClass().getName());
            }
            return is(new StringLiteral(stmt, typesLiteral.getJavaTypeMapping(), valueStr, typesLiteral.getParameterName()), not);
        }
        List<BooleanExpression> listExp = new LinkedList<>();
        for (Object value : values) {
            String valueStr = null;
            if (value instanceof Class) {
                valueStr = ((Class) value).getCanonicalName();
            } else if (value instanceof String) {
                valueStr = (String) value;
            } else {
                throw new NucleusUserException("Do not support CollectionLiteral of element type " + value.getClass().getName());
            }
            listExp.add(is(new StringLiteral(stmt, typesLiteral.getJavaTypeMapping(), valueStr, typesLiteral.getParameterName()), false));
        }
        BooleanExpression result = null;
        for (BooleanExpression sqlExpression : listExp) {
            result = result == null ? sqlExpression : result.ior(sqlExpression);
        }
        if (result != null) {
            return not ? result.not() : result;
        }
    } else {
        throw new NucleusUserException("Do not currently support `instanceof` with class expression of type " + classExpr);
    }
    Class type = null;
    try {
        type = stmt.getQueryGenerator().resolveClass(instanceofClassName);
    } catch (ClassNotResolvedException cnre) {
        type = null;
    }
    if (type == null) {
        throw new NucleusUserException(Localiser.msg("037016", instanceofClassName));
    }
    // Extract type of member and check obvious conditions
    SQLExpressionFactory exprFactory = stmt.getSQLExpressionFactory();
    Class memberType = clr.classForName(mapping.getType());
    if (!memberType.isAssignableFrom(type) && !type.isAssignableFrom(memberType)) {
        // Member type and instanceof type are totally incompatible, so just return false
        JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
        return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, not));
    } else if (memberType == type) {
        // instanceof type is the same as the member type therefore must comply (can't store supertypes)
        JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
        return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, !not));
    }
    if (mapping instanceof EmbeddedMapping) {
        // Don't support embedded instanceof expressions
        AbstractClassMetaData fieldCmd = storeMgr.getMetaDataManager().getMetaDataForClass(mapping.getType(), clr);
        if (fieldCmd.hasDiscriminatorStrategy()) {
            // Embedded field with inheritance so add discriminator restriction
            JavaTypeMapping discMapping = ((EmbeddedMapping) mapping).getDiscriminatorMapping();
            AbstractClassMetaData typeCmd = storeMgr.getMetaDataManager().getMetaDataForClass(type, clr);
            SQLExpression discExpr = stmt.getSQLExpressionFactory().newExpression(stmt, table, discMapping);
            SQLExpression discValExpr = stmt.getSQLExpressionFactory().newLiteral(stmt, discMapping, typeCmd.getDiscriminatorValue());
            BooleanExpression typeExpr = (not ? discExpr.ne(discValExpr) : discExpr.eq(discValExpr));
            Iterator<String> subclassIter = storeMgr.getSubClassesForClass(type.getName(), true, clr).iterator();
            while (subclassIter.hasNext()) {
                String subclassName = subclassIter.next();
                AbstractClassMetaData subtypeCmd = storeMgr.getMetaDataManager().getMetaDataForClass(subclassName, clr);
                Object subtypeDiscVal = subtypeCmd.getDiscriminatorValue();
                discValExpr = stmt.getSQLExpressionFactory().newLiteral(stmt, discMapping, subtypeDiscVal);
                BooleanExpression subtypeExpr = (not ? discExpr.ne(discValExpr) : discExpr.eq(discValExpr));
                if (not) {
                    typeExpr = typeExpr.and(subtypeExpr);
                } else {
                    typeExpr = typeExpr.ior(subtypeExpr);
                }
            }
            return typeExpr;
        }
        JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
        return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, not));
    } else if (mapping instanceof PersistableMapping || mapping instanceof ReferenceMapping) {
        // Field has its own table, so join to it
        AbstractClassMetaData memberCmd = storeMgr.getMetaDataManager().getMetaDataForClass(mapping.getType(), clr);
        DatastoreClass memberTable = null;
        if (memberCmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.SUBCLASS_TABLE) {
            // Field is a PC class that uses "subclass-table" inheritance strategy (and so has multiple possible tables to join to)
            AbstractClassMetaData[] cmds = storeMgr.getClassesManagingTableForClass(memberCmd, clr);
            if (cmds != null) {
                // TODO Allow for all possible tables. Can we do an OR of the tables ? How ?
                if (cmds.length > 1) {
                    NucleusLogger.QUERY.warn(Localiser.msg("037006", mapping.getMemberMetaData().getFullFieldName(), cmds[0].getFullClassName()));
                }
                memberTable = storeMgr.getDatastoreClass(cmds[0].getFullClassName(), clr);
            } else {
                // No subclasses with tables to join to, so throw a user error
                throw new NucleusUserException(Localiser.msg("037005", mapping.getMemberMetaData().getFullFieldName()));
            }
        } else {
            // Class of the field will have its own table
            memberTable = storeMgr.getDatastoreClass(mapping.getType(), clr);
        }
        DiscriminatorMetaData dismd = memberTable.getDiscriminatorMetaData();
        DiscriminatorMapping discMapping = (DiscriminatorMapping) memberTable.getSurrogateMapping(SurrogateColumnType.DISCRIMINATOR, false);
        if (discMapping != null) {
            SQLTable targetSqlTbl = null;
            if (mapping.getTable() != memberTable) {
                // FK is on source table so inner join to target table (holding the discriminator)
                targetSqlTbl = stmt.getTable(memberTable, null);
                if (targetSqlTbl == null) {
                    targetSqlTbl = stmt.join(JoinType.INNER_JOIN, getSQLTable(), mapping, memberTable, null, memberTable.getIdMapping(), null, null);
                }
            } else {
                // FK is on target side and already joined
                targetSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(stmt, getSQLTable(), discMapping);
            }
            // Add restrict to discriminator for the instanceOf type and subclasses
            SQLTable discSqlTbl = targetSqlTbl;
            BooleanExpression discExpr = null;
            if (!Modifier.isAbstract(type.getModifiers())) {
                discExpr = SQLStatementHelper.getExpressionForDiscriminatorForClass(stmt, type.getName(), dismd, discMapping, discSqlTbl, clr);
            }
            Iterator<String> subclassIter = storeMgr.getSubClassesForClass(type.getName(), true, clr).iterator();
            boolean multiplePossibles = false;
            while (subclassIter.hasNext()) {
                String subclassName = subclassIter.next();
                Class subclass = clr.classForName(subclassName);
                if (Modifier.isAbstract(subclass.getModifiers())) {
                    continue;
                }
                BooleanExpression discExprSub = SQLStatementHelper.getExpressionForDiscriminatorForClass(stmt, subclassName, dismd, discMapping, discSqlTbl, clr);
                if (discExpr != null) {
                    multiplePossibles = true;
                    discExpr = discExpr.ior(discExprSub);
                } else {
                    discExpr = discExprSub;
                }
            }
            if (multiplePossibles && discExpr != null) {
                discExpr.encloseInParentheses();
            }
            return ((not && discExpr != null) ? discExpr.not() : discExpr);
        }
        // No discriminator, so the following is likely incomplete.
        // Join to member table
        DatastoreClass table = null;
        if (memberCmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.SUBCLASS_TABLE) {
            // Field is a PC class that uses "subclass-table" inheritance strategy (and so has multiple possible tables to join to)
            AbstractClassMetaData[] cmds = storeMgr.getClassesManagingTableForClass(memberCmd, clr);
            if (cmds != null) {
                // TODO Allow for all possible tables. Can we do an OR of the tables ? How ?
                if (cmds.length > 1) {
                    NucleusLogger.QUERY.warn(Localiser.msg("037006", mapping.getMemberMetaData().getFullFieldName(), cmds[0].getFullClassName()));
                }
                table = storeMgr.getDatastoreClass(cmds[0].getFullClassName(), clr);
            } else {
                // No subclasses with tables to join to, so throw a user error
                throw new NucleusUserException(Localiser.msg("037005", mapping.getMemberMetaData().getFullFieldName()));
            }
        } else {
            // Class of the field will have its own table
            table = storeMgr.getDatastoreClass(mapping.getType(), clr);
        }
        if (table.managesClass(type.getName())) {
            // This type is managed in this table so must be an instance TODO Is this correct, what if member is using discrim?
            JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
            return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, !not));
        }
        if (table == stmt.getPrimaryTable().getTable()) {
            // This is member table, so just need to restrict to the instanceof type now
            JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
            if (stmt instanceof SelectStatement) {
                SelectStatement selectStmt = (SelectStatement) stmt;
                if (selectStmt.getNumberOfUnions() == 0) {
                    // No UNIONs so just check the main statement and return according to whether it is allowed
                    Class mainCandidateCls = clr.classForName(stmt.getCandidateClassName());
                    if (type.isAssignableFrom(mainCandidateCls) == not) {
                        SQLExpression returnExpr = exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, false));
                        return (BooleanExpression) returnExpr;
                    }
                    SQLExpression returnExpr = exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, true));
                    return (BooleanExpression) returnExpr;
                }
                NucleusLogger.QUERY.warn("TYPE/INSTANCEOF operator for class=" + memberCmd.getFullClassName() + " on table=" + memberTable + " for type=" + instanceofClassName + " but there is no discriminator and using UNIONs. Any subsequent handling is likely incorrect TODO");
                // a). we have unions for the member, so restrict to just the applicable unions
                // Note that this is only really valid is wanting "a instanceof SUB1".
                // It fails when we want to do "a instanceof SUB1 || a instanceof SUB2"
                // TODO What if this "OP_IS" is in the SELECT clause??? Need to update QueryToSQLMapper.compileResult
                Class mainCandidateCls = clr.classForName(stmt.getCandidateClassName());
                if (type.isAssignableFrom(mainCandidateCls) == not) {
                    SQLExpression unionClauseExpr = exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, false));
                    stmt.whereAnd((BooleanExpression) unionClauseExpr, false);
                }
                List<SelectStatement> unionStmts = selectStmt.getUnions();
                for (SelectStatement unionStmt : unionStmts) {
                    Class unionCandidateCls = clr.classForName(unionStmt.getCandidateClassName());
                    if (type.isAssignableFrom(unionCandidateCls) == not) {
                        SQLExpression unionClauseExpr = exprFactory.newLiteral(unionStmt, m, true).eq(exprFactory.newLiteral(unionStmt, m, false));
                        // TODO Avoid using whereAnd
                        unionStmt.whereAnd((BooleanExpression) unionClauseExpr, false);
                    }
                }
                // Just return true since we applied the condition direct to the unions
                SQLExpression returnExpr = exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, true));
                return (BooleanExpression) returnExpr;
            }
            // b). The member table doesn't manage the instanceof type, so do inner join to
            // the table of the instanceof to impose the instanceof condition
            DatastoreClass instanceofTable = storeMgr.getDatastoreClass(type.getName(), clr);
            stmt.join(JoinType.INNER_JOIN, this.table, this.table.getTable().getIdMapping(), instanceofTable, null, instanceofTable.getIdMapping(), null, this.table.getGroupName());
            return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, !not));
        }
        // Do inner join to this table to impose the instanceOf
        DatastoreClass instanceofTable = storeMgr.getDatastoreClass(type.getName(), clr);
        stmt.join(JoinType.INNER_JOIN, this.table, this.table.getTable().getIdMapping(), instanceofTable, null, instanceofTable.getIdMapping(), null, this.table.getGroupName());
        JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
        return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, !not));
    } else {
        // TODO Implement instanceof for other types
        throw new NucleusException("Dont currently support " + this + " instanceof " + type.getName());
    }
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) Iterator(java.util.Iterator) LinkedList(java.util.LinkedList) List(java.util.List) DiscriminatorMapping(org.datanucleus.store.rdbms.mapping.java.DiscriminatorMapping) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) DiscriminatorMetaData(org.datanucleus.metadata.DiscriminatorMetaData) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) EmbeddedMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedMapping) Collection(java.util.Collection) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) NucleusException(org.datanucleus.exceptions.NucleusException)

Example 72 with NucleusException

use of org.datanucleus.exceptions.NucleusException in project datanucleus-rdbms by datanucleus.

the class SelectStatement method select.

/**
 * Add a select clause for the specified column.
 * @param table The SQLTable to select from (null implies the primary table)
 * @param column The column
 * @param alias Optional alias
 * @return The column index in the statement for the specified column (1 is first).
 */
public int select(SQLTable table, Column column, String alias) {
    if (column == null) {
        throw new NucleusException("Column to select is null");
    } else if (table == null) {
        // Default to the primary table if not specified
        table = primaryTable;
    }
    if (column.getTable() != table.getTable()) {
        throw new NucleusException("Table being selected from (\"" + table.getTable() + "\") is inconsistent with the column selected (\"" + column.getTable() + "\")");
    }
    invalidateStatement();
    DatastoreIdentifier colAlias = null;
    if (alias != null) {
        colAlias = rdbmsMgr.getIdentifierFactory().newColumnIdentifier(alias);
    }
    SQLColumn col = new SQLColumn(table, column, colAlias);
    int position = selectItem(new SQLText(col.getColumnSelectString()), alias != null ? colAlias.toString() : null, true);
    if (unions != null && allowUnions) {
        // Apply the select to all unions
        Iterator<SelectStatement> unionIter = unions.iterator();
        while (unionIter.hasNext()) {
            SelectStatement stmt = unionIter.next();
            stmt.select(table, column, alias);
        }
    }
    return position;
}
Also used : DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) NucleusException(org.datanucleus.exceptions.NucleusException)

Example 73 with NucleusException

use of org.datanucleus.exceptions.NucleusException in project datanucleus-rdbms by datanucleus.

the class UnionStatementGenerator method getStatement.

/**
 * Accessor for the SelectStatement for the candidate [+ subclasses].
 * @param ec ExecutionContext
 * @return The SelectStatement returning objects with a UNION statement.
 */
public SelectStatement getStatement(ExecutionContext ec) {
    // Find set of possible candidates (including subclasses of subclasses)
    Collection<String> candidateClassNames = new ArrayList<>();
    AbstractClassMetaData acmd = storeMgr.getMetaDataManager().getMetaDataForClass(candidateType, clr);
    candidateClassNames.add(acmd.getFullClassName());
    if (includeSubclasses) {
        Collection<String> subclasses = storeMgr.getSubClassesForClass(candidateType.getName(), true, clr);
        candidateClassNames.addAll(subclasses);
    }
    // Eliminate any classes that are not instantiable
    Iterator<String> iter = candidateClassNames.iterator();
    while (iter.hasNext()) {
        String className = iter.next();
        try {
            Class cls = clr.classForName(className);
            if (Modifier.isAbstract(cls.getModifiers())) {
                // Remove since abstract hence not instantiable
                iter.remove();
            }
        } catch (Exception e) {
            // Remove since class not found
            iter.remove();
        }
    }
    if (hasOption(OPTION_SELECT_DN_TYPE)) {
        // Get the length of the longest class name
        iter = candidateClassNames.iterator();
        while (iter.hasNext()) {
            String className = iter.next();
            if (className.length() > maxClassNameLength) {
                maxClassNameLength = className.length();
            }
        }
    }
    if (candidateClassNames.isEmpty()) {
        // Either passed invalid classes, or no concrete classes with available tables present!
        throw new NucleusException("Attempt to generate SQL statement using UNIONs for " + candidateType.getName() + " yet there are no concrete classes with their own table available");
    }
    SelectStatement stmt = null;
    for (String candidateClassName : candidateClassNames) {
        SelectStatement candidateStmt = null;
        if (joinTable == null) {
            // Select of candidate table
            candidateStmt = getSelectStatementForCandidate(candidateClassName, ec);
        } else {
            // Select of join table and join to element
            candidateStmt = getSQLStatementForCandidateViaJoin(candidateClassName);
        }
        if (candidateStmt != null) {
            if (stmt == null) {
                stmt = candidateStmt;
            } else {
                stmt.union(candidateStmt);
            }
        }
    }
    return stmt;
}
Also used : ArrayList(java.util.ArrayList) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) NucleusException(org.datanucleus.exceptions.NucleusException)

Example 74 with NucleusException

use of org.datanucleus.exceptions.NucleusException in project datanucleus-rdbms by datanucleus.

the class SQLStatementHelper method getValueForPrimaryKeyIndexOfObjectUsingReflection.

/**
 * Convenience method to use reflection to extract the value of a PK field of the provided object.
 * @param value The value of the overall object
 * @param index Index of the PK field whose value we need to return
 * @param cmd Metadata for the class
 * @param storeMgr Store manager
 * @param clr ClassLoader resolver
 * @return Value of this index of the PK field
 */
public static Object getValueForPrimaryKeyIndexOfObjectUsingReflection(Object value, int index, AbstractClassMetaData cmd, RDBMSStoreManager storeMgr, ClassLoaderResolver clr) {
    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
        throw new NucleusException("This method does not support datastore-identity");
    }
    int position = 0;
    int[] pkPositions = cmd.getPKMemberPositions();
    for (int pkPosition : pkPositions) {
        AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkPosition);
        Object memberValue = null;
        if (mmd instanceof FieldMetaData) {
            memberValue = ClassUtils.getValueOfFieldByReflection(value, mmd.getName());
        } else {
            memberValue = ClassUtils.getValueOfMethodByReflection(value, ClassUtils.getJavaBeanGetterName(mmd.getName(), false));
        }
        if (storeMgr.getApiAdapter().isPersistable(mmd.getType())) {
            // Compound PK field, so recurse
            // TODO Cater for cases without own table ("subclass-table")
            AbstractClassMetaData subCmd = storeMgr.getMetaDataManager().getMetaDataForClass(mmd.getType(), clr);
            DatastoreClass subTable = storeMgr.getDatastoreClass(mmd.getTypeName(), clr);
            JavaTypeMapping subMapping = subTable.getIdMapping();
            Object subValue = getValueForPrimaryKeyIndexOfObjectUsingReflection(memberValue, index - position, subCmd, storeMgr, clr);
            if (index < position + subMapping.getNumberOfColumnMappings()) {
                return subValue;
            }
            position = position + subMapping.getNumberOfColumnMappings();
        } else {
            // Normal PK field
            if (position == index) {
                if (mmd instanceof FieldMetaData) {
                    return ClassUtils.getValueOfFieldByReflection(value, mmd.getName());
                }
                return ClassUtils.getValueOfMethodByReflection(value, ClassUtils.getJavaBeanGetterName(mmd.getName(), false));
            }
            position++;
        }
    }
    return null;
}
Also used : FieldMetaData(org.datanucleus.metadata.FieldMetaData) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SecondaryDatastoreClass(org.datanucleus.store.rdbms.table.SecondaryDatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData)

Example 75 with NucleusException

use of org.datanucleus.exceptions.NucleusException in project datanucleus-rdbms by datanucleus.

the class SQLExpressionFactory method getMethod.

/**
 * Accessor for the method defined by the class/method names and supplied args.
 * Throws a NucleusException is the method is not supported.
 * Note that if the class name passed in is not for a listed class with that method defined then will check all remaining defined methods for a superclass.
 * @param className Class we are invoking the method on
 * @param methodName Name of the method
 * @param args Any arguments to the method call (ignored currently) TODO Check the arguments
 * @return The method
 */
protected SQLMethod getMethod(String className, String methodName, List args) {
    String datastoreId = storeMgr.getDatastoreAdapter().getVendorID();
    // Try to find datastore-dependent evaluator for class+method
    MethodKey methodKey1 = getSQLMethodKey(datastoreId, className, methodName);
    MethodKey methodKey2 = null;
    SQLMethod method = sqlMethodsByKey.get(methodKey1);
    if (method == null) {
        // Try to find datastore-independent evaluator for class+method
        methodKey2 = getSQLMethodKey(null, className, methodName);
        method = sqlMethodsByKey.get(methodKey2);
    }
    if (method != null) {
        return method;
    }
    // No existing instance, so check the built-in SQLMethods from DatastoreAdapter
    Class sqlMethodCls = storeMgr.getDatastoreAdapter().getSQLMethodClass(className, methodName, clr);
    if (sqlMethodCls != null) {
        // Built-in SQLMethod found, so instantiate it, cache it and return it
        try {
            method = (SQLMethod) sqlMethodCls.getDeclaredConstructor().newInstance();
            MethodKey key = getSQLMethodKey(datastoreId, className, methodName);
            sqlMethodsByKey.put(key, method);
            return method;
        } catch (Exception e) {
            throw new NucleusException("Error creating SQLMethod of type " + sqlMethodCls.getName() + " for class=" + className + " method=" + methodName);
        }
    }
    // Check the plugin mechanism
    // 1). Try datastore-dependent key
    boolean datastoreDependent = true;
    if (!pluginSqlMethodsKeysSupported.contains(methodKey1)) {
        // 2). No datastore-dependent method, so try a datastore-independent key
        datastoreDependent = false;
        if (!pluginSqlMethodsKeysSupported.contains(methodKey2)) {
            // Not listed as supported for this particular class+method, so maybe is for a superclass
            boolean unsupported = true;
            if (!StringUtils.isWhitespace(className)) {
                Class cls = clr.classForName(className);
                // Try datastore-dependent
                for (MethodKey methodKey : pluginSqlMethodsKeysSupported) {
                    if (methodKey.methodName.equals(methodName) && methodKey.datastoreName.equals(datastoreId)) {
                        Class methodCls = null;
                        try {
                            methodCls = clr.classForName(methodKey.clsName);
                        } catch (ClassNotResolvedException cnre) {
                        // Maybe generic array support?
                        }
                        if (methodCls != null && methodCls.isAssignableFrom(cls)) {
                            // This one is usable here, for superclass
                            method = sqlMethodsByKey.get(methodKey);
                            if (method != null) {
                                MethodKey superMethodKey = new MethodKey();
                                superMethodKey.clsName = className;
                                superMethodKey.methodName = methodKey.methodName;
                                superMethodKey.datastoreName = methodKey.datastoreName;
                                // Cache the same method under this class also
                                sqlMethodsByKey.put(superMethodKey, method);
                                return method;
                            }
                            className = methodKey.clsName;
                            datastoreId = methodKey.datastoreName;
                            datastoreDependent = true;
                            unsupported = false;
                            break;
                        }
                    }
                }
                if (unsupported) {
                    // Try datastore-independent
                    for (MethodKey methodKey : pluginSqlMethodsKeysSupported) {
                        if (methodKey.methodName.equals(methodName) && methodKey.datastoreName.equals("ALL")) {
                            Class methodCls = null;
                            try {
                                methodCls = clr.classForName(methodKey.clsName);
                            } catch (ClassNotResolvedException cnre) {
                            // Maybe generic array support?
                            }
                            if (methodCls != null && methodCls.isAssignableFrom(cls)) {
                                // This one is usable here, for superclass
                                method = sqlMethodsByKey.get(methodKey);
                                if (method != null) {
                                    MethodKey superMethodKey = new MethodKey();
                                    superMethodKey.clsName = className;
                                    superMethodKey.methodName = methodKey.methodName;
                                    superMethodKey.datastoreName = methodKey.datastoreName;
                                    // Cache the same method under this class also
                                    sqlMethodsByKey.put(superMethodKey, method);
                                    return method;
                                }
                                className = methodKey.clsName;
                                datastoreId = methodKey.datastoreName;
                                datastoreDependent = false;
                                unsupported = false;
                                break;
                            }
                        }
                    }
                }
            }
            if (unsupported) {
                if (className != null) {
                    throw new NucleusUserException(Localiser.msg("060008", methodName, className));
                }
                throw new NucleusUserException(Localiser.msg("060009", methodName));
            }
        }
    }
    // Fallback to plugin lookup of class+method[+datastore]
    PluginManager pluginMgr = storeMgr.getNucleusContext().getPluginManager();
    String[] attrNames = (datastoreDependent ? new String[] { "class", "method", "datastore" } : new String[] { "class", "method" });
    String[] attrValues = (datastoreDependent ? new String[] { className, methodName, datastoreId } : new String[] { className, methodName });
    try {
        method = (SQLMethod) pluginMgr.createExecutableExtension("org.datanucleus.store.rdbms.sql_method", attrNames, attrValues, "evaluator", new Class[] {}, new Object[] {});
        // Register the method
        sqlMethodsByKey.put(getSQLMethodKey(datastoreDependent ? datastoreId : null, className, methodName), method);
        return method;
    } catch (Exception e) {
        throw new NucleusUserException(Localiser.msg("060011", "class=" + className + " method=" + methodName), e);
    }
}
Also used : PluginManager(org.datanucleus.plugin.PluginManager) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) SQLMethod(org.datanucleus.store.rdbms.sql.method.SQLMethod) NucleusException(org.datanucleus.exceptions.NucleusException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) NucleusException(org.datanucleus.exceptions.NucleusException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException)

Aggregations

NucleusException (org.datanucleus.exceptions.NucleusException)326 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)71 SQLExpression (org.datanucleus.store.rdbms.sql.expression.SQLExpression)67 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)62 ParameterExpression (org.datanucleus.query.expression.ParameterExpression)53 PrimaryExpression (org.datanucleus.query.expression.PrimaryExpression)52 ArrayList (java.util.ArrayList)48 Literal (org.datanucleus.query.expression.Literal)47 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)44 SQLExpressionFactory (org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory)43 InvokeExpression (org.datanucleus.query.expression.InvokeExpression)40 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)37 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)36 StringExpression (org.datanucleus.store.rdbms.sql.expression.StringExpression)35 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)35 Expression (org.datanucleus.query.expression.Expression)32 HashMap (java.util.HashMap)31 SelectStatement (org.datanucleus.store.rdbms.sql.SelectStatement)31 VariableExpression (org.datanucleus.query.expression.VariableExpression)26 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)26