Search in sources :

Example 71 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class SearchedCaseNode method getDataType.

@Override
public Type getDataType() {
    // option is used to hold each WHEN/ELSE in turn
    AST option = getFirstChild();
    while (option != null) {
        final AST result;
        if (option.getType() == HqlSqlTokenTypes.WHEN) {
            result = option.getFirstChild().getNextSibling();
        } else if (option.getType() == HqlSqlTokenTypes.ELSE) {
            result = option.getFirstChild();
        } else {
            throw new QueryException("Unexpected node type :" + ASTUtil.getTokenTypeName(HqlSqlTokenTypes.class, option.getType()) + "; expecting WHEN or ELSE");
        }
        if (SqlNode.class.isInstance(result)) {
            final Type nodeDataType = ((SqlNode) result).getDataType();
            if (nodeDataType != null) {
                return nodeDataType;
            }
        }
        option = option.getNextSibling();
    }
    return null;
}
Also used : AST(antlr.collections.AST) QueryException(org.hibernate.QueryException) Type(org.hibernate.type.Type)

Example 72 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class SelectClause method initializeExplicitSelectClause.

/**
	 * Prepares an explicitly defined select clause.
	 *
	 * @param fromClause The from clause linked to this select clause.
	 *
	 * @throws SemanticException indicates a semntic issue with the explicit select clause.
	 */
public void initializeExplicitSelectClause(FromClause fromClause) throws SemanticException {
    if (prepared) {
        throw new IllegalStateException("SelectClause was already prepared!");
    }
    //explicit = true;	// This is an explict Select.
    //ArrayList sqlResultTypeList = new ArrayList();
    ArrayList queryReturnTypeList = new ArrayList();
    // First, collect all of the select expressions.
    // NOTE: This must be done *beforeQuery* invoking setScalarColumnText() because setScalarColumnText()
    // changes the AST!!!
    SelectExpression[] selectExpressions = collectSelectExpressions();
    // we only support parameters in select in the case of INSERT...SELECT statements
    if (getParameterPositions().size() > 0 && getWalker().getStatementType() != HqlSqlTokenTypes.INSERT) {
        throw new QueryException("Parameters are only supported in SELECT clauses when used as part of a INSERT INTO DML statement");
    }
    for (SelectExpression selectExpression : selectExpressions) {
        if (AggregatedSelectExpression.class.isInstance(selectExpression)) {
            aggregatedSelectExpression = (AggregatedSelectExpression) selectExpression;
            queryReturnTypeList.addAll(aggregatedSelectExpression.getAggregatedSelectionTypeList());
            scalarSelect = true;
        } else {
            // we have no choice but to do this check here
            // this is not very elegant but the "right way" would most likely involve a bigger rewrite so as to
            // treat ParameterNodes in select clauses as SelectExpressions
            boolean inSubquery = selectExpression instanceof QueryNode && ((QueryNode) selectExpression).getFromClause().getParentFromClause() != null;
            if (getWalker().getStatementType() == HqlSqlTokenTypes.INSERT && inSubquery) {
                // we do not support parameters for subqueries in INSERT...SELECT
                if (((QueryNode) selectExpression).getSelectClause().getParameterPositions().size() > 0) {
                    throw new QueryException("Use of parameters in subqueries of INSERT INTO DML statements is not supported.");
                }
            }
            Type type = selectExpression.getDataType();
            if (type == null) {
                throw new QueryException("No data type for node: " + selectExpression.getClass().getName() + " " + new ASTPrinter(SqlTokenTypes.class).showAsString((AST) selectExpression, ""));
            }
            // If the data type is not an association type, it could not have been in the FROM clause.
            if (selectExpression.isScalar()) {
                scalarSelect = true;
            }
            if (isReturnableEntity(selectExpression)) {
                fromElementsForLoad.add(selectExpression.getFromElement());
            }
            // Always add the type to the return type list.
            queryReturnTypeList.add(type);
        }
    }
    //init the aliases, afterQuery initing the constructornode
    initAliases(selectExpressions);
    if (!getWalker().isShallowQuery()) {
        // add the fetched entities
        List fromElements = fromClause.getProjectionList();
        // Get ready to start adding nodes.
        ASTAppender appender = new ASTAppender(getASTFactory(), this);
        int size = fromElements.size();
        Iterator iterator = fromElements.iterator();
        for (int k = 0; iterator.hasNext(); k++) {
            FromElement fromElement = (FromElement) iterator.next();
            if (fromElement.isFetch()) {
                FromElement origin = null;
                if (fromElement.getRealOrigin() == null) {
                    // by FromElementFactory.createCollectionJoin()
                    if (fromElement.getOrigin() == null) {
                        throw new QueryException("Unable to determine origin of join fetch [" + fromElement.getDisplayText() + "]");
                    } else {
                        origin = fromElement.getOrigin();
                    }
                } else {
                    origin = fromElement.getRealOrigin();
                }
                if (!fromElementsForLoad.contains(origin) && // work around that fetch joins of element collections where their parent instead of the root is selected
                (!fromElement.isCollectionJoin() || !fromElementsForLoad.contains(fromElement.getFetchOrigin()))) {
                    throw new QueryException("query specified join fetching, but the owner " + "of the fetched association was not present in the select list " + "[" + fromElement.getDisplayText() + "]");
                }
                Type type = fromElement.getSelectType();
                addCollectionFromElement(fromElement);
                if (type != null) {
                    boolean collectionOfElements = fromElement.isCollectionOfValuesOrComponents();
                    if (!collectionOfElements) {
                        // Add the type to the list of returned sqlResultTypes.
                        fromElement.setIncludeSubclasses(true);
                        fromElementsForLoad.add(fromElement);
                        //sqlResultTypeList.add( type );
                        // Generate the select expression.
                        String text = fromElement.renderIdentifierSelect(size, k);
                        alreadyRenderedIdentifiers.add(text);
                        SelectExpressionImpl generatedExpr = (SelectExpressionImpl) appender.append(SqlTokenTypes.SELECT_EXPR, text, false);
                        if (generatedExpr != null) {
                            generatedExpr.setFromElement(fromElement);
                        }
                    }
                }
            }
        }
        // generate id select fragment and then property select fragment for
        // each expression, just like generateSelectFragments().
        renderNonScalarSelects(collectSelectExpressions(), fromClause);
    }
    if (scalarSelect || getWalker().isShallowQuery()) {
        // If there are any scalars (non-entities) selected, render the select column aliases.
        renderScalarSelects(selectExpressions, fromClause);
    }
    finishInitialization(/*sqlResultTypeList,*/
    queryReturnTypeList);
}
Also used : ArrayList(java.util.ArrayList) SqlTokenTypes(org.hibernate.hql.internal.antlr.SqlTokenTypes) HqlSqlTokenTypes(org.hibernate.hql.internal.antlr.HqlSqlTokenTypes) QueryException(org.hibernate.QueryException) Type(org.hibernate.type.Type) ASTAppender(org.hibernate.hql.internal.ast.util.ASTAppender) ASTPrinter(org.hibernate.hql.internal.ast.util.ASTPrinter) Iterator(java.util.Iterator) ASTIterator(org.hibernate.hql.internal.ast.util.ASTIterator) List(java.util.List) ArrayList(java.util.ArrayList)

Example 73 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class SimpleCaseNode method getDataType.

public Type getDataType() {
    final AST expression = getFirstChild();
    // option is used to hold each WHEN/ELSE in turn
    AST option = expression.getNextSibling();
    while (option != null) {
        final AST result;
        if (option.getType() == HqlSqlTokenTypes.WHEN) {
            result = option.getFirstChild().getNextSibling();
        } else if (option.getType() == HqlSqlTokenTypes.ELSE) {
            result = option.getFirstChild();
        } else {
            throw new QueryException("Unexpected node type :" + ASTUtil.getTokenTypeName(HqlSqlTokenTypes.class, option.getType()) + "; expecting WHEN or ELSE");
        }
        if (SqlNode.class.isInstance(result)) {
            final Type nodeDataType = ((SqlNode) result).getDataType();
            if (nodeDataType != null) {
                return nodeDataType;
            }
        }
        option = option.getNextSibling();
    }
    return null;
}
Also used : AST(antlr.collections.AST) QueryException(org.hibernate.QueryException) Type(org.hibernate.type.Type)

Example 74 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class FromParser method token.

public void token(String token, QueryTranslatorImpl q) throws QueryException {
    // start by looking for HQL keywords...
    String lcToken = token.toLowerCase(Locale.ROOT);
    if (lcToken.equals(",")) {
        if (!(expectingJoin | expectingAs)) {
            throw new QueryException("unexpected token: ,");
        }
        expectingJoin = false;
        expectingAs = false;
    } else if (lcToken.equals("join")) {
        if (!afterJoinType) {
            if (!(expectingJoin | expectingAs)) {
                throw new QueryException("unexpected token: join");
            }
            // inner joins can be abbreviated to 'join'
            joinType = JoinType.INNER_JOIN;
            expectingJoin = false;
            expectingAs = false;
        } else {
            afterJoinType = false;
        }
    } else if (lcToken.equals("fetch")) {
        if (q.isShallowQuery()) {
            throw new QueryException(QueryTranslator.ERROR_CANNOT_FETCH_WITH_ITERATE);
        }
        if (joinType == JoinType.NONE) {
            throw new QueryException("unexpected token: fetch");
        }
        if (joinType == JoinType.FULL_JOIN || joinType == JoinType.RIGHT_OUTER_JOIN) {
            throw new QueryException("fetch may only be used with inner join or left outer join");
        }
        afterFetch = true;
    } else if (lcToken.equals("outer")) {
        // 'outer' is optional and is ignored
        if (!afterJoinType || (joinType != JoinType.LEFT_OUTER_JOIN && joinType != JoinType.RIGHT_OUTER_JOIN)) {
            throw new QueryException("unexpected token: outer");
        }
    } else if (JOIN_TYPES.containsKey(lcToken)) {
        if (!(expectingJoin | expectingAs)) {
            throw new QueryException("unexpected token: " + token);
        }
        joinType = JOIN_TYPES.get(lcToken);
        afterJoinType = true;
        expectingJoin = false;
        expectingAs = false;
    } else if (lcToken.equals("class")) {
        if (!afterIn) {
            throw new QueryException("unexpected token: class");
        }
        if (joinType != JoinType.NONE) {
            throw new QueryException("outer or full join must be followed by path expression");
        }
        afterClass = true;
    } else if (lcToken.equals("in")) {
        if (alias == null) {
            memberDeclarations = true;
            afterMemberDeclarations = false;
        } else if (!expectingIn) {
            throw new QueryException("unexpected token: in");
        } else {
            afterIn = true;
            expectingIn = false;
        }
    } else if (lcToken.equals("as")) {
        if (!expectingAs) {
            throw new QueryException("unexpected token: as");
        }
        afterAs = true;
        expectingAs = false;
    } else if ("(".equals(token)) {
        if (!memberDeclarations) {
            throw new QueryException("unexpected token: (");
        }
        //TODO alias should be null here
        expectingPathExpression = true;
    } else if (")".equals(token)) {
        //			memberDeclarations = false;
        //			expectingPathExpression = false;
        afterMemberDeclarations = true;
    } else {
        if (afterJoinType) {
            throw new QueryException("join expected: " + token);
        }
        if (expectingJoin) {
            throw new QueryException("unexpected token: " + token);
        }
        if (expectingIn) {
            throw new QueryException("in expected: " + token);
        }
        if (afterAs || expectingAs) {
            if (entityName != null) {
                q.setAliasName(token, entityName);
            } else if (collectionName != null) {
                q.setAliasName(token, collectionName);
            } else {
                throw new QueryException("unexpected: as " + token);
            }
            afterAs = false;
            expectingJoin = true;
            expectingAs = false;
            entityName = null;
            collectionName = null;
            memberDeclarations = false;
            expectingPathExpression = false;
            afterMemberDeclarations = false;
        } else if (afterIn) {
            if (alias == null) {
                throw new QueryException("alias not specified for: " + token);
            }
            if (joinType != JoinType.NONE) {
                throw new QueryException("outer or full join must be followed by path expression");
            }
            if (afterClass) {
                // treat it as a classname
                Queryable p = q.getEntityPersisterUsingImports(token);
                if (p == null) {
                    throw new QueryException("persister not found: " + token);
                }
                q.addFromClass(alias, p);
            } else {
                // treat it as a path expression
                peParser.setJoinType(JoinType.INNER_JOIN);
                peParser.setUseThetaStyleJoin(true);
                ParserHelper.parse(peParser, q.unalias(token), ParserHelper.PATH_SEPARATORS, q);
                if (!peParser.isCollectionValued()) {
                    throw new QueryException("path expression did not resolve to collection: " + token);
                }
                String nm = peParser.addFromCollection(q);
                q.setAliasName(alias, nm);
            }
            alias = null;
            afterIn = false;
            afterClass = false;
            expectingJoin = true;
        } else if (memberDeclarations && expectingPathExpression) {
            expectingAs = true;
            peParser.setJoinType(JoinType.INNER_JOIN);
            peParser.setUseThetaStyleJoin(false);
            ParserHelper.parse(peParser, q.unalias(token), ParserHelper.PATH_SEPARATORS, q);
            if (!peParser.isCollectionValued()) {
                throw new QueryException("path expression did not resolve to collection: " + token);
            }
            collectionName = peParser.addFromCollection(q);
            expectingPathExpression = false;
            memberDeclarations = false;
        } else {
            // handle a path expression or class name that
            // appears at the start, in the "new" HQL
            // style or an alias that appears at the start
            // in the "old" HQL style
            Queryable p = q.getEntityPersisterUsingImports(token);
            if (p != null) {
                // starts with the name of a mapped class (new style)
                if (joinType != JoinType.NONE) {
                    throw new QueryException("outer or full join must be followed by path expression");
                }
                entityName = q.createNameFor(p.getEntityName());
                q.addFromClass(entityName, p);
                expectingAs = true;
            } else if (token.indexOf('.') < 0) {
                // starts with an alias (old style)
                // semi-bad thing about this: can't re-alias another alias.....
                alias = token;
                expectingIn = true;
            } else {
                //allow ODMG OQL style: from Person p, p.cars c
                if (joinType != JoinType.NONE) {
                    peParser.setJoinType(joinType);
                } else {
                    peParser.setJoinType(JoinType.INNER_JOIN);
                }
                peParser.setUseThetaStyleJoin(q.isSubquery());
                ParserHelper.parse(peParser, q.unalias(token), ParserHelper.PATH_SEPARATORS, q);
                entityName = peParser.addFromAssociation(q);
                joinType = JoinType.NONE;
                peParser.setJoinType(JoinType.INNER_JOIN);
                if (afterFetch) {
                    peParser.fetch(q, entityName);
                    afterFetch = false;
                }
                expectingAs = true;
            }
        }
    }
}
Also used : QueryException(org.hibernate.QueryException) Queryable(org.hibernate.persister.entity.Queryable)

Example 75 with QueryException

use of org.hibernate.QueryException in project hibernate-orm by hibernate.

the class LiteralProcessor method setConstantValue.

private void setConstantValue(DotNode node, String text, Object value) {
    if (LOG.isDebugEnabled()) {
        LOG.debugf("setConstantValue() %s -> %s %s", text, value, value.getClass().getName());
    }
    // Chop off the rest of the tree.
    node.setFirstChild(null);
    if (value instanceof String) {
        node.setType(SqlTokenTypes.QUOTED_STRING);
    } else if (value instanceof Character) {
        node.setType(SqlTokenTypes.QUOTED_STRING);
    } else if (value instanceof Byte) {
        node.setType(SqlTokenTypes.NUM_INT);
    } else if (value instanceof Short) {
        node.setType(SqlTokenTypes.NUM_INT);
    } else if (value instanceof Integer) {
        node.setType(SqlTokenTypes.NUM_INT);
    } else if (value instanceof Long) {
        node.setType(SqlTokenTypes.NUM_LONG);
    } else if (value instanceof Double) {
        node.setType(SqlTokenTypes.NUM_DOUBLE);
    } else if (value instanceof Float) {
        node.setType(SqlTokenTypes.NUM_FLOAT);
    } else {
        node.setType(SqlTokenTypes.CONSTANT);
    }
    Type type;
    try {
        type = walker.getSessionFactoryHelper().getFactory().getTypeResolver().heuristicType(value.getClass().getName());
    } catch (MappingException me) {
        throw new QueryException(me);
    }
    if (type == null) {
        throw new QueryException(QueryTranslator.ERROR_CANNOT_DETERMINE_TYPE + node.getText());
    }
    try {
        LiteralType literalType = (LiteralType) type;
        Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect();
        //noinspection unchecked
        node.setText(literalType.objectToSQLString(value, dialect));
    } catch (Exception e) {
        throw new QueryException(QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + node.getText(), e);
    }
    node.setDataType(type);
    node.setResolvedConstant(text);
}
Also used : LiteralType(org.hibernate.type.LiteralType) SemanticException(antlr.SemanticException) InvalidPathException(org.hibernate.hql.internal.ast.InvalidPathException) MappingException(org.hibernate.MappingException) HibernateException(org.hibernate.HibernateException) QueryException(org.hibernate.QueryException) MappingException(org.hibernate.MappingException) BigInteger(java.math.BigInteger) LiteralType(org.hibernate.type.LiteralType) Type(org.hibernate.type.Type) QueryException(org.hibernate.QueryException) Dialect(org.hibernate.dialect.Dialect)

Aggregations

QueryException (org.hibernate.QueryException)77 Type (org.hibernate.type.Type)20 Test (org.junit.Test)19 Session (org.hibernate.Session)18 Transaction (org.hibernate.Transaction)12 JoinType (org.hibernate.sql.JoinType)12 Queryable (org.hibernate.persister.entity.Queryable)10 CollectionType (org.hibernate.type.CollectionType)10 MappingException (org.hibernate.MappingException)9 QueryableCollection (org.hibernate.persister.collection.QueryableCollection)9 AssociationType (org.hibernate.type.AssociationType)8 HashMap (java.util.HashMap)6 HibernateException (org.hibernate.HibernateException)6 JoinSequence (org.hibernate.engine.internal.JoinSequence)6 EntityType (org.hibernate.type.EntityType)6 AST (antlr.collections.AST)5 Map (java.util.Map)5 SemanticException (antlr.SemanticException)4 ArrayList (java.util.ArrayList)4 FromElement (org.hibernate.hql.internal.ast.tree.FromElement)4