Search in sources :

Example 6 with Function

use of net.sf.jsqlparser.expression.Function in project herddb by diennea.

the class SQLParserExpressionCompiler method compileExpressionInternal.

private static CompiledSQLExpression compileExpressionInternal(Expression expression, OpSchema tableSchema) {
    if (expression == null) {
        return null;
    }
    if (expression instanceof JdbcParameter) {
        JdbcParameter p = (JdbcParameter) expression;
        return new JdbcParameterExpression(p.getIndex() - 1);
    } else if (expression instanceof StringValue || expression instanceof LongValue || expression instanceof NullValue || expression instanceof DoubleValue || expression instanceof TimestampValue) {
        return JSQLParserPlanner.resolveValueAsCompiledSQLExpression(expression, false);
    } else if (expression instanceof net.sf.jsqlparser.schema.Column) {
        // mapping a reference to a Column to the index in the schema of the table
        net.sf.jsqlparser.schema.Column col = (net.sf.jsqlparser.schema.Column) expression;
        String tableAlias = extractTableName(col);
        // no fix backtick, handle false/true literals, without backticks
        String columnName = col.getColumnName();
        if (isBooleanLiteral(col)) {
            return new ConstantExpression(Boolean.parseBoolean(columnName.toLowerCase()), ColumnTypes.NOTNULL_BOOLEAN);
        }
        IntHolder indexInSchema = new IntHolder(-1);
        ColumnRef found = findColumnInSchema(tableAlias, columnName, tableSchema, indexInSchema);
        if (indexInSchema.value == -1 || found == null) {
            String nameInError = tableAlias != null ? tableAlias + "." + columnName : columnName;
            throw new StatementExecutionException("Column " + nameInError + " not found in target table (schema " + tableSchema + ")");
        }
        return new AccessCurrentRowExpression(indexInSchema.value, found.type);
    } else if (expression instanceof BinaryExpression) {
        return compileBinaryExpression((BinaryExpression) expression, tableSchema);
    } else if (expression instanceof IsNullExpression) {
        IsNullExpression eq = (IsNullExpression) expression;
        CompiledSQLExpression left = compileExpression(eq.getLeftExpression(), tableSchema);
        return new CompiledIsNullExpression(eq.isNot(), left);
    } else if (expression instanceof NotExpression) {
        NotExpression eq = (NotExpression) expression;
        CompiledSQLExpression left = compileExpression(eq.getExpression(), tableSchema);
        return new CompiledNotExpression(left);
    } else if (expression instanceof Parenthesis) {
        Parenthesis eq = (Parenthesis) expression;
        return compileExpression(eq.getExpression(), tableSchema);
    } else if (expression instanceof SignedExpression) {
        SignedExpression eq = (SignedExpression) expression;
        return new CompiledSignedExpression(eq.getSign(), compileExpression(eq.getExpression(), tableSchema));
    } else if (expression instanceof InExpression) {
        InExpression eq = (InExpression) expression;
        checkSupported(eq.getOldOracleJoinSyntax() == EqualsTo.NO_ORACLE_JOIN);
        checkSupported(eq.getOraclePriorPosition() == EqualsTo.NO_ORACLE_PRIOR);
        checkSupported(eq.getLeftItemsList() == null);
        checkSupported(eq.getMultiExpressionList() == null);
        checkSupported(eq.getRightExpression() == null);
        CompiledSQLExpression left = compileExpression(eq.getLeftExpression(), tableSchema);
        ItemsList rightItemsList = eq.getRightItemsList();
        checkSupported(rightItemsList instanceof ExpressionList, "Sub Selects are not supported with jSQLParser");
        ExpressionList expressionList = (ExpressionList) rightItemsList;
        CompiledSQLExpression[] values = new CompiledSQLExpression[expressionList.getExpressions().size()];
        int i = 0;
        for (Expression exp : expressionList.getExpressions()) {
            values[i++] = compileExpression(exp, tableSchema);
        }
        return new CompiledInExpression(left, values);
    } else if (expression instanceof TimeKeyExpression) {
        TimeKeyExpression eq = (TimeKeyExpression) expression;
        if (eq.getStringValue().equalsIgnoreCase("CURRENT_TIMESTAMP")) {
            return new CompiledFunction(BuiltinFunctions.CURRENT_TIMESTAMP, Collections.emptyList());
        }
    // fallthru
    } else if (expression instanceof Function) {
        Function eq = (Function) expression;
        checkSupported(eq.getKeep() == null);
        checkSupported(eq.getMultipartName() != null && eq.getMultipartName().size() == 1);
        checkSupported(eq.getNamedParameters() == null);
        checkSupported(eq.getAttribute() == null);
        checkSupported(eq.getAttributeName() == null);
        List<CompiledSQLExpression> operands = new ArrayList<>();
        if (eq.getParameters() != null) {
            for (Expression e : eq.getParameters().getExpressions()) {
                operands.add(compileExpression(e, tableSchema));
            }
        }
        switch(eq.getName().toUpperCase()) {
            case BuiltinFunctions.NAME_LOWERCASE:
                return new CompiledFunction(BuiltinFunctions.LOWER, operands);
            case BuiltinFunctions.NAME_UPPER:
                return new CompiledFunction(BuiltinFunctions.UPPER, operands);
            case BuiltinFunctions.NAME_ABS:
                return new CompiledFunction(BuiltinFunctions.ABS, operands);
            case BuiltinFunctions.NAME_AVG:
                return new CompiledFunction(BuiltinFunctions.AVG, operands);
            case BuiltinFunctions.NAME_ROUND:
                return new CompiledFunction(BuiltinFunctions.ROUND, operands);
            case BuiltinFunctions.NAME_EXTRACT:
                return new CompiledFunction(BuiltinFunctions.EXTRACT, operands);
            case BuiltinFunctions.NAME_FLOOR:
                return new CompiledFunction(BuiltinFunctions.FLOOR, operands);
            case BuiltinFunctions.NAME_RAND:
                return new CompiledFunction(BuiltinFunctions.RAND, operands);
            default:
        }
    // fallthru
    } else if (expression instanceof CaseExpression) {
        CaseExpression eq = (CaseExpression) expression;
        checkSupported(eq.getSwitchExpression() == null);
        List<WhenClause> whenClauses = eq.getWhenClauses();
        List<Map.Entry<CompiledSQLExpression, CompiledSQLExpression>> cases = new ArrayList<>(whenClauses.size());
        for (WhenClause c : whenClauses) {
            cases.add(new AbstractMap.SimpleImmutableEntry<>(compileExpression(c.getWhenExpression(), tableSchema), compileExpression(c.getThenExpression(), tableSchema)));
        }
        CompiledSQLExpression elseExp = eq.getElseExpression() != null ? compileExpression(eq.getElseExpression(), tableSchema) : null;
        return new CompiledCaseExpression(cases, elseExp);
    } else if (expression instanceof Between) {
        Between b = (Between) expression;
        boolean not = b.isNot();
        CompiledSQLExpression baseValue = compileExpression(b.getLeftExpression(), tableSchema);
        CompiledSQLExpression start = compileExpression(b.getBetweenExpressionStart(), tableSchema);
        CompiledSQLExpression end = compileExpression(b.getBetweenExpressionEnd(), tableSchema);
        CompiledSQLExpression result = new CompiledAndExpression(new CompiledGreaterThanEqualsExpression(baseValue, start), new CompiledMinorThanEqualsExpression(baseValue, end));
        if (not) {
            return new CompiledNotExpression(result);
        } else {
            return result;
        }
    } else if (expression instanceof net.sf.jsqlparser.expression.CastExpression) {
        net.sf.jsqlparser.expression.CastExpression b = (net.sf.jsqlparser.expression.CastExpression) expression;
        CompiledSQLExpression left = compileExpression(b.getLeftExpression(), tableSchema);
        int type = JSQLParserPlanner.sqlDataTypeToColumnType(b.getType());
        return new CastExpression(left, type);
    }
    // }
    throw new StatementExecutionException("not implemented expression type " + expression.getClass() + ": " + expression);
}
Also used : ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) ArrayList(java.util.ArrayList) StatementExecutionException(herddb.model.StatementExecutionException) CaseExpression(net.sf.jsqlparser.expression.CaseExpression) WhenClause(net.sf.jsqlparser.expression.WhenClause) NullValue(net.sf.jsqlparser.expression.NullValue) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) IntHolder(herddb.utils.IntHolder) List(java.util.List) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) StringValue(net.sf.jsqlparser.expression.StringValue) Between(net.sf.jsqlparser.expression.operators.relational.Between) IsNullExpression(net.sf.jsqlparser.expression.operators.relational.IsNullExpression) TimeKeyExpression(net.sf.jsqlparser.expression.TimeKeyExpression) LongValue(net.sf.jsqlparser.expression.LongValue) Map(java.util.Map) AbstractMap(java.util.AbstractMap) NotExpression(net.sf.jsqlparser.expression.NotExpression) Function(net.sf.jsqlparser.expression.Function) Parenthesis(net.sf.jsqlparser.expression.Parenthesis) TimestampValue(net.sf.jsqlparser.expression.TimestampValue) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) DoubleValue(net.sf.jsqlparser.expression.DoubleValue) CaseExpression(net.sf.jsqlparser.expression.CaseExpression) NotExpression(net.sf.jsqlparser.expression.NotExpression) IsNullExpression(net.sf.jsqlparser.expression.operators.relational.IsNullExpression) Expression(net.sf.jsqlparser.expression.Expression) OrExpression(net.sf.jsqlparser.expression.operators.conditional.OrExpression) TimeKeyExpression(net.sf.jsqlparser.expression.TimeKeyExpression) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) LikeExpression(net.sf.jsqlparser.expression.operators.relational.LikeExpression) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) SignedExpression(net.sf.jsqlparser.expression.SignedExpression) SignedExpression(net.sf.jsqlparser.expression.SignedExpression)

Example 7 with Function

use of net.sf.jsqlparser.expression.Function in project dbeaver by dbeaver.

the class SQLQueryTransformerCount method tryInjectCount.

private SQLQuery tryInjectCount(SQLDataSource dataSource, SQLQuery query) throws DBException {
    try {
        Statement statement = CCJSqlParserUtil.parse(query.getText());
        if (statement instanceof Select && ((Select) statement).getSelectBody() instanceof PlainSelect) {
            PlainSelect select = (PlainSelect) ((Select) statement).getSelectBody();
            if (select.getHaving() != null) {
                throw new DBException("Can't inject COUNT into query with HAVING clause");
            }
            if (!CommonUtils.isEmpty(select.getGroupByColumnReferences())) {
                throw new DBException("Can't inject COUNT into query with GROUP BY clause");
            }
            Distinct selectDistinct = select.getDistinct();
            if (selectDistinct != null) {
                // Remove distinct
                select.setDistinct(null);
            }
            Function countFunc = new Function();
            countFunc.setName("count");
            if (selectDistinct != null) {
                countFunc.setDistinct(true);
                List<Expression> exprs = new ArrayList<>();
                for (SelectItem item : select.getSelectItems()) {
                    if (item instanceof SelectExpressionItem) {
                        exprs.add(((SelectExpressionItem) item).getExpression());
                    }
                }
                if (!exprs.isEmpty()) {
                    countFunc.setParameters(new ExpressionList(exprs));
                }
            }
            countFunc.setAllColumns(true);
            List<SelectItem> selectItems = new ArrayList<>();
            selectItems.add(new SelectExpressionItem(countFunc));
            select.setSelectItems(selectItems);
            select.setOrderByElements(null);
            return new SQLQuery(dataSource, select.toString(), query, false);
        } else {
            throw new DBException("Query [" + query.getText() + "] can't be modified");
        }
    } catch (JSQLParserException e) {
        throw new DBException("Can't transform query to SELECT count(*)", e);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) Statement(net.sf.jsqlparser.statement.Statement) JSQLParserException(net.sf.jsqlparser.JSQLParserException) ArrayList(java.util.ArrayList) Function(net.sf.jsqlparser.expression.Function) Expression(net.sf.jsqlparser.expression.Expression) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList)

Example 8 with Function

use of net.sf.jsqlparser.expression.Function in project sandbox by irof.

the class ParsingTest method postgres_sequence.

@Test
void postgres_sequence() throws Exception {
    try (InputStream inputStream = this.getClass().getResourceAsStream("/select-postgres-sequence.sql")) {
        Statement statement = CCJSqlParserUtil.parse(inputStream);
        Select select = Select.class.cast(statement);
        class SequenceFinder extends SelectVisitorAdapter {

            String sequenceExpression;

            @Override
            public void visit(PlainSelect plainSelect) {
                List<SelectItem> selectItems = plainSelect.getSelectItems();
                SelectItem selectItem = selectItems.get(0);
                SelectItemVisitor expressionVisitor = new ExpressionVisitorAdapter() {

                    @Override
                    public void visit(Function function) {
                        sequenceExpression = function.toString();
                        super.visit(function);
                    }
                };
                selectItem.accept(expressionVisitor);
            }
        }
        SequenceFinder sequenceFinder = new SequenceFinder();
        select.getSelectBody().accept(sequenceFinder);
        assertThat(sequenceFinder.sequenceExpression).isEqualTo("nextval('hoge_seq')");
    }
}
Also used : Function(net.sf.jsqlparser.expression.Function) InputStream(java.io.InputStream) Statement(net.sf.jsqlparser.statement.Statement) ExpressionVisitorAdapter(net.sf.jsqlparser.expression.ExpressionVisitorAdapter) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 9 with Function

use of net.sf.jsqlparser.expression.Function in project Mybatis-PageHelper by pagehelper.

the class FunctionCountTest method test2.

@Test
public void test2() {
    Select select = select("select distinct(name) from user where a > 100");
    List<SelectItem> selectItems = ((PlainSelect) select.getSelectBody()).getSelectItems();
    for (SelectItem item : selectItems) {
        if (item instanceof Function) {
            System.out.println("Function:" + item.toString());
        } else {
            System.out.println("Not a function:" + item.toString());
        }
    }
}
Also used : Function(net.sf.jsqlparser.expression.Function) SelectItem(net.sf.jsqlparser.statement.select.SelectItem) Select(net.sf.jsqlparser.statement.select.Select) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) Test(org.junit.Test)

Example 10 with Function

use of net.sf.jsqlparser.expression.Function in project Mybatis-PageHelper by pagehelper.

the class FunctionCountTest method test.

@Test
public void test() {
    Select select = select("select max(name),code,min(aa),nvl(ab,0),heh from user where a > 100");
    List<SelectItem> selectItems = ((PlainSelect) select.getSelectBody()).getSelectItems();
    for (SelectItem item : selectItems) {
        if (item instanceof SelectExpressionItem) {
            Expression exp = ((SelectExpressionItem) item).getExpression();
            if (exp instanceof Function) {
                System.out.println("Function:" + item.toString());
            } else {
                System.out.println("Not a function:" + exp.toString());
            }
        } else {
            System.out.println("Not a function:" + item.toString());
        }
    }
}
Also used : Function(net.sf.jsqlparser.expression.Function) Expression(net.sf.jsqlparser.expression.Expression) SelectItem(net.sf.jsqlparser.statement.select.SelectItem) SelectExpressionItem(net.sf.jsqlparser.statement.select.SelectExpressionItem) Select(net.sf.jsqlparser.statement.select.Select) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) Test(org.junit.Test)

Aggregations

Function (net.sf.jsqlparser.expression.Function)13 Expression (net.sf.jsqlparser.expression.Expression)10 ArrayList (java.util.ArrayList)7 ExpressionList (net.sf.jsqlparser.expression.operators.relational.ExpressionList)6 StatementExecutionException (herddb.model.StatementExecutionException)5 SignedExpression (net.sf.jsqlparser.expression.SignedExpression)4 Statement (net.sf.jsqlparser.statement.Statement)4 SelectExpressionItem (net.sf.jsqlparser.statement.select.SelectExpressionItem)4 SelectItem (net.sf.jsqlparser.statement.select.SelectItem)4 IntHolder (herddb.utils.IntHolder)3 List (java.util.List)3 JSQLParserException (net.sf.jsqlparser.JSQLParserException)3 BinaryExpression (net.sf.jsqlparser.expression.BinaryExpression)3 CaseExpression (net.sf.jsqlparser.expression.CaseExpression)3 TimeKeyExpression (net.sf.jsqlparser.expression.TimeKeyExpression)3 AndExpression (net.sf.jsqlparser.expression.operators.conditional.AndExpression)3 OrExpression (net.sf.jsqlparser.expression.operators.conditional.OrExpression)3 InExpression (net.sf.jsqlparser.expression.operators.relational.InExpression)3 IsNullExpression (net.sf.jsqlparser.expression.operators.relational.IsNullExpression)3 LikeExpression (net.sf.jsqlparser.expression.operators.relational.LikeExpression)3