Search in sources :

Example 16 with ExpressionList

use of net.sf.jsqlparser.expression.operators.relational.ExpressionList in project JSqlParser by JSQLParser.

the class UpsertDeParser method visit.

@Override
public void visit(MultiExpressionList multiExprList) {
    buffer.append(" VALUES ");
    for (Iterator<ExpressionList> it = multiExprList.getExprList().iterator(); it.hasNext(); ) {
        buffer.append("(");
        for (Iterator<Expression> iter = it.next().getExpressions().iterator(); iter.hasNext(); ) {
            Expression expression = iter.next();
            expression.accept(expressionVisitor);
            if (iter.hasNext()) {
                buffer.append(", ");
            }
        }
        buffer.append(")");
        if (it.hasNext()) {
            buffer.append(", ");
        }
    }
}
Also used : Expression(net.sf.jsqlparser.expression.Expression) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList)

Example 17 with ExpressionList

use of net.sf.jsqlparser.expression.operators.relational.ExpressionList in project herddb by diennea.

the class HerdDBCLI method rewriteQuery.

private static QueryWithParameters rewriteQuery(String query, TableSpaceMapper mapper, boolean frommysqldump) throws ScriptException {
    try {
        List<Object> parameters = new ArrayList<>();
        if (frommysqldump && query.startsWith("INSERT INTO")) {
            // this is faster than CCJSqlParserUtil and will allow the cache to work at "client-side" too
            QueryWithParameters rewriteSimpleInsertStatement = MySqlDumpInsertStatementRewriter.rewriteSimpleInsertStatement(query);
            if (rewriteSimpleInsertStatement != null) {
                query = rewriteSimpleInsertStatement.query;
                parameters.addAll(rewriteSimpleInsertStatement.jdbcParameters);
                String schema = mapper == null ? null : mapper.getTableSpace(rewriteSimpleInsertStatement.tableName);
                return new QueryWithParameters(query, rewriteSimpleInsertStatement.tableName, parameters, schema);
            }
        }
        String _query = query;
        net.sf.jsqlparser.statement.Statement stmt = PARSER_CACHE.get(_query, () -> {
            return CCJSqlParserUtil.parse(_query);
        });
        if (stmt instanceof Insert) {
            boolean somethingdone = false;
            Insert insert = (Insert) stmt;
            ItemsList itemlist = insert.getItemsList();
            if (itemlist instanceof ExpressionList) {
                ExpressionList list = (ExpressionList) itemlist;
                List<Expression> expressions = list.getExpressions();
                for (int i = 0; i < expressions.size(); i++) {
                    Expression e = expressions.get(i);
                    boolean done = false;
                    if (e instanceof StringValue) {
                        StringValue sv = (StringValue) e;
                        parameters.add(sv.getValue());
                        done = true;
                    } else if (e instanceof LongValue) {
                        LongValue sv = (LongValue) e;
                        parameters.add(sv.getValue());
                        done = true;
                    } else if (e instanceof NullValue) {
                        NullValue sv = (NullValue) e;
                        parameters.add(null);
                        done = true;
                    } else if (e instanceof TimestampValue) {
                        TimestampValue sv = (TimestampValue) e;
                        parameters.add(sv.getValue());
                        done = true;
                    } else if (e instanceof DoubleValue) {
                        DoubleValue sv = (DoubleValue) e;
                        parameters.add(sv.getValue());
                        done = true;
                    }
                    if (done) {
                        somethingdone = true;
                        expressions.set(i, new JdbcParameter());
                    }
                }
                if (somethingdone) {
                    StringBuilder queryResult = new StringBuilder();
                    InsertDeParser deparser = new InsertDeParser(new ExpressionDeParser(null, queryResult), null, queryResult);
                    deparser.deParse(insert);
                    query = queryResult.toString();
                }
            } else if (itemlist instanceof MultiExpressionList) {
                MultiExpressionList mlist = (MultiExpressionList) itemlist;
                List<ExpressionList> lists = mlist.getExprList();
                for (ExpressionList list : lists) {
                    List<Expression> expressions = list.getExpressions();
                    for (int i = 0; i < expressions.size(); i++) {
                        Expression e = expressions.get(i);
                        boolean done = false;
                        if (e instanceof StringValue) {
                            StringValue sv = (StringValue) e;
                            parameters.add(sv.getValue());
                            done = true;
                        } else if (e instanceof LongValue) {
                            LongValue sv = (LongValue) e;
                            parameters.add(sv.getValue());
                            done = true;
                        } else if (e instanceof NullValue) {
                            NullValue sv = (NullValue) e;
                            parameters.add(null);
                            done = true;
                        } else if (e instanceof TimestampValue) {
                            TimestampValue sv = (TimestampValue) e;
                            parameters.add(sv.getValue());
                            done = true;
                        } else if (e instanceof DoubleValue) {
                            DoubleValue sv = (DoubleValue) e;
                            parameters.add(sv.getValue());
                            done = true;
                        }
                        if (done) {
                            somethingdone = true;
                            expressions.set(i, new JdbcParameter());
                        }
                    }
                }
                if (somethingdone) {
                    StringBuilder queryResult = new StringBuilder();
                    InsertDeParser deparser = new InsertDeParser(new ExpressionDeParser(null, queryResult), null, queryResult);
                    deparser.deParse(insert);
                    query = queryResult.toString();
                }
            }
            String schema = mapper == null ? null : mapper.getTableSpace(stmt);
            return new QueryWithParameters(query, null, parameters, schema);
        } else {
            String schema = mapper == null ? null : mapper.getTableSpace(stmt);
            return new QueryWithParameters(query, null, Collections.emptyList(), schema);
        }
    } catch (ExecutionException err) {
        System.out.println("error for query: " + query + " -> " + err.getCause());
        return null;
    }
}
Also used : ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) InsertDeParser(net.sf.jsqlparser.util.deparser.InsertDeParser) ArrayList(java.util.ArrayList) Insert(net.sf.jsqlparser.statement.insert.Insert) NullValue(net.sf.jsqlparser.expression.NullValue) TimestampValue(net.sf.jsqlparser.expression.TimestampValue) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) 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) ExecutionException(java.util.concurrent.ExecutionException) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) Expression(net.sf.jsqlparser.expression.Expression) DoubleValue(net.sf.jsqlparser.expression.DoubleValue) LongValue(net.sf.jsqlparser.expression.LongValue) ExpressionDeParser(net.sf.jsqlparser.util.deparser.ExpressionDeParser)

Example 18 with ExpressionList

use of net.sf.jsqlparser.expression.operators.relational.ExpressionList in project herddb by diennea.

the class CompiledInExpression method create.

public static CompiledInExpression create(InExpression in, String validatedTableAlias) {
    if (in.getLeftItemsList() != null) {
        throw new StatementExecutionException("Unsupported operand " + in.getClass() + " with a non-expression left argument (" + in + ")");
    }
    CompiledSQLExpression left = compileExpression(validatedTableAlias, in.getLeftExpression());
    if (left == null) {
        return null;
    }
    if (in.getRightItemsList() instanceof ExpressionList) {
        List<CompiledSQLExpression> expList = new ArrayList<>();
        ExpressionList exps = (ExpressionList) in.getRightItemsList();
        for (Expression exp : exps.getExpressions()) {
            CompiledSQLExpression newExp = compileExpression(validatedTableAlias, exp);
            if (newExp == null) {
                return null;
            }
            expList.add(newExp);
        }
        return new CompiledInExpression(in.isNot(), left, expList, null);
    }
    if (in.getRightItemsList() instanceof SubSelect) {
        SubSelect ss = (SubSelect) in.getRightItemsList();
        if (!(ss.getSelectBody() instanceof PlainSelect)) {
            throw new StatementExecutionException("unsupported operand " + in.getClass() + " with subquery of type " + ss.getClass() + "(" + ss + ")");
        }
        return new CompiledInExpression(in.isNot(), left, null, ss);
    }
    throw new StatementExecutionException("unsupported operand " + in.getClass() + " with argument of type " + in.getRightItemsList().getClass() + "(" + in + ")");
}
Also used : Expression(net.sf.jsqlparser.expression.Expression) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) SQLExpressionCompiler.compileExpression(herddb.sql.expressions.SQLExpressionCompiler.compileExpression) ArrayList(java.util.ArrayList) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) SubSelect(net.sf.jsqlparser.statement.select.SubSelect) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) StatementExecutionException(herddb.model.StatementExecutionException)

Example 19 with ExpressionList

use of net.sf.jsqlparser.expression.operators.relational.ExpressionList in project dbeaver by serge-rider.

the class SQLQueryTransformerCount method tryInjectCount.

private SQLQuery tryInjectCount(DBPDataSource 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 (select.getGroupBy() != null && !CommonUtils.isEmpty(select.getGroupBy().getGroupByExpressions())) {
                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 20 with ExpressionList

use of net.sf.jsqlparser.expression.operators.relational.ExpressionList in project spanner-jdbc by olavloite.

the class CloudSpannerPreparedStatement method createInsertMutation.

private Mutation createInsertMutation(Insert insert, boolean generateParameterMetaData) throws SQLException {
    ItemsList items = insert.getItemsList();
    if (generateParameterMetaData && items == null && insert.getSelect() != null) {
        // Just initialize the parameter meta data of the select statement
        createSelectBuilder(insert.getSelect(), insert.getSelect().toString());
        return null;
    }
    if (!(items instanceof ExpressionList)) {
        throw new CloudSpannerSQLException("Insert statement must specify a list of values", Code.INVALID_ARGUMENT);
    }
    if (insert.getColumns() == null || insert.getColumns().isEmpty()) {
        throw new CloudSpannerSQLException("Insert statement must specify a list of column names", Code.INVALID_ARGUMENT);
    }
    List<Expression> expressions = ((ExpressionList) items).getExpressions();
    String table = unquoteIdentifier(insert.getTable().getFullyQualifiedName());
    getParameterStore().setTable(table);
    WriteBuilder builder;
    if (insert.isUseDuplicate()) {
        /**
         * Do an insert-or-update. BUT: Cloud Spanner does not support supplying different values for
         * the insert and update statements, meaning that only the values specified in the INSERT part
         * of the statement will be considered. Anything specified in the 'ON DUPLICATE KEY UPDATE
         * ...' statement will be ignored.
         */
        if (this.forceUpdate)
            builder = Mutation.newUpdateBuilder(table);
        else
            builder = Mutation.newInsertOrUpdateBuilder(table);
    } else {
        /**
         * Just do an insert and throw an error if a row with the specified key alread exists.
         */
        builder = Mutation.newInsertBuilder(table);
    }
    int index = 0;
    for (Column col : insert.getColumns()) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        expressions.get(index).accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(), builder.set(columnName), columnName));
        index++;
    }
    return builder.build();
}
Also used : ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) Expression(net.sf.jsqlparser.expression.Expression) Column(net.sf.jsqlparser.schema.Column) WriteBuilder(com.google.cloud.spanner.Mutation.WriteBuilder) CloudSpannerSQLException(nl.topicus.jdbc.exception.CloudSpannerSQLException) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList)

Aggregations

ExpressionList (net.sf.jsqlparser.expression.operators.relational.ExpressionList)21 Expression (net.sf.jsqlparser.expression.Expression)16 ArrayList (java.util.ArrayList)11 Test (org.junit.Test)9 MultiExpressionList (net.sf.jsqlparser.expression.operators.relational.MultiExpressionList)6 StringReader (java.io.StringReader)5 JSQLParserException (net.sf.jsqlparser.JSQLParserException)4 Function (net.sf.jsqlparser.expression.Function)4 Statement (net.sf.jsqlparser.statement.Statement)4 DBException (org.jkiss.dbeaver.DBException)4 JdbcParameter (net.sf.jsqlparser.expression.JdbcParameter)3 ItemsList (net.sf.jsqlparser.expression.operators.relational.ItemsList)3 Insert (net.sf.jsqlparser.statement.insert.Insert)3 StatementExecutionException (herddb.model.StatementExecutionException)2 List (java.util.List)2 AnalyticExpression (net.sf.jsqlparser.expression.AnalyticExpression)2 BinaryExpression (net.sf.jsqlparser.expression.BinaryExpression)2 KeepExpression (net.sf.jsqlparser.expression.KeepExpression)2 SignedExpression (net.sf.jsqlparser.expression.SignedExpression)2 InExpression (net.sf.jsqlparser.expression.operators.relational.InExpression)2