Search in sources :

Example 6 with ItemsList

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

the class ExpressionVisitorAdapterTest method testInExpression.

@Test
public void testInExpression() throws JSQLParserException {
    final List exprList = new ArrayList();
    Select select = (Select) CCJSqlParserUtil.parse("select * from foo where (a,b) in (select a,b from foo2)");
    PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
    Expression where = plainSelect.getWhere();
    where.accept(new ExpressionVisitorAdapter() {

        @Override
        public void visit(InExpression expr) {
            super.visit(expr);
            exprList.add(expr.getLeftExpression());
            exprList.add(expr.getLeftItemsList());
            exprList.add(expr.getRightItemsList());
        }
    });
    assertNull(exprList.get(0));
    assertTrue(exprList.get(1) instanceof ItemsList);
    assertTrue(exprList.get(2) instanceof ItemsList);
}
Also used : ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) ArrayList(java.util.ArrayList) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) Select(net.sf.jsqlparser.statement.select.Select) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) ArrayList(java.util.ArrayList) List(java.util.List) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) Test(org.junit.Test)

Example 7 with ItemsList

use of net.sf.jsqlparser.expression.operators.relational.ItemsList 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)

Example 8 with ItemsList

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

the class JSQLParserPlanner method planerInsertOrUpsert.

private ExecutionPlan planerInsertOrUpsert(String defaultTableSpace, net.sf.jsqlparser.schema.Table table, List<net.sf.jsqlparser.schema.Column> columns, ItemsList itemsList, boolean returnValues, boolean upsert) throws StatementExecutionException, StatementNotSupportedException {
    OpSchema inputSchema = getTableSchema(defaultTableSpace, table);
    TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(inputSchema.tableSpace);
    AbstractTableManager tableManager = tableSpaceManager.getTableManager(inputSchema.name);
    Table tableImpl = tableManager.getTable();
    List<CompiledSQLExpression> keyValueExpression = new ArrayList<>();
    List<String> keyExpressionToColumn = new ArrayList<>();
    List<CompiledSQLExpression> valuesExpressions = new ArrayList<>();
    List<String> valuesColumns = new ArrayList<>();
    boolean invalid = false;
    int index = 0;
    if (columns == null) {
        // INSERT INTO TABLE VALUES (xxxx) (no column list)
        columns = new ArrayList<>();
        for (Column c : tableImpl.getColumns()) {
            columns.add(new net.sf.jsqlparser.schema.Column(c.name));
        }
    }
    if (itemsList instanceof ExpressionList) {
        List<Expression> values = ((ExpressionList) itemsList).getExpressions();
        for (net.sf.jsqlparser.schema.Column column : columns) {
            CompiledSQLExpression exp = SQLParserExpressionCompiler.compileExpression(values.get(index), inputSchema);
            String columnName = fixMySqlBackTicks(column.getColumnName()).toLowerCase();
            if (exp instanceof ConstantExpression || exp instanceof JdbcParameterExpression || exp instanceof TypedJdbcParameterExpression || exp instanceof CompiledFunction) {
                boolean isAlwaysNull = (exp instanceof ConstantExpression) && ((ConstantExpression) exp).isNull();
                if (!isAlwaysNull) {
                    if (tableImpl.isPrimaryKeyColumn(columnName)) {
                        keyExpressionToColumn.add(columnName);
                        keyValueExpression.add(exp);
                    }
                    Column columnFromSchema = tableImpl.getColumn(columnName);
                    if (columnFromSchema == null) {
                        throw new StatementExecutionException("Column '" + columnName + "' not found in table " + tableImpl.name);
                    }
                    valuesColumns.add(columnFromSchema.name);
                    valuesExpressions.add(exp);
                }
                index++;
            } else {
                checkSupported(false, "Unsupported expression type " + exp.getClass().getName());
                break;
            }
        }
        // handle default values
        for (Column col : tableImpl.getColumns()) {
            if (!valuesColumns.contains(col.name)) {
                if (col.defaultValue != null) {
                    valuesColumns.add(col.name);
                    CompiledSQLExpression defaultValueExpression = makeDefaultValue(col);
                    valuesExpressions.add(defaultValueExpression);
                } else if (ColumnTypes.isNotNullDataType(col.type) && !tableImpl.auto_increment) {
                    throw new StatementExecutionException("Column '" + col.name + "' has no default value and does not allow NULLs");
                }
            }
        }
        DMLStatement statement;
        if (!invalid) {
            RecordFunction keyfunction;
            if (keyValueExpression.isEmpty() && tableImpl.auto_increment) {
                keyfunction = new AutoIncrementPrimaryKeyRecordFunction();
            } else {
                if (keyValueExpression.size() != tableImpl.primaryKey.length) {
                    throw new StatementExecutionException("you must set a value for the primary key (expressions=" + keyValueExpression.size() + ")");
                }
                keyfunction = new SQLRecordKeyFunction(keyExpressionToColumn, keyValueExpression, tableImpl);
            }
            RecordFunction valuesfunction = new SQLRecordFunction(valuesColumns, tableImpl, valuesExpressions);
            statement = new InsertStatement(inputSchema.tableSpace, inputSchema.name, keyfunction, valuesfunction, upsert).setReturnValues(returnValues);
        } else {
            throw new StatementNotSupportedException();
        }
        PlannerOp op = new SimpleInsertOp(statement.setReturnValues(returnValues));
        return optimizePlan(op);
    } else if (itemsList instanceof MultiExpressionList) {
        List<ExpressionList> records = ((MultiExpressionList) itemsList).getExprList();
        ValuesOp values = planValuesForInsertOp(columns, tableImpl, inputSchema, records);
        InsertOp op = new InsertOp(tableImpl.tablespace, tableImpl.name, values, returnValues, upsert);
        return optimizePlan(op);
    } else {
        checkSupported(false);
        return null;
    }
}
Also used : ConstantExpression(herddb.sql.expressions.ConstantExpression) ArrayList(java.util.ArrayList) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) StatementExecutionException(herddb.model.StatementExecutionException) InsertStatement(herddb.model.commands.InsertStatement) ValuesOp(herddb.model.planner.ValuesOp) SimpleInsertOp(herddb.model.planner.SimpleInsertOp) Column(herddb.model.Column) TableSpaceManager(herddb.core.TableSpaceManager) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) List(java.util.List) SetOperationList(net.sf.jsqlparser.statement.select.SetOperationList) RecordFunction(herddb.model.RecordFunction) AutoIncrementPrimaryKeyRecordFunction(herddb.model.AutoIncrementPrimaryKeyRecordFunction) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) CompiledFunction(herddb.sql.expressions.CompiledFunction) Table(herddb.model.Table) ShowCreateTableCalculator.calculateShowCreateTable(herddb.sql.functions.ShowCreateTableCalculator.calculateShowCreateTable) CreateTable(net.sf.jsqlparser.statement.create.table.CreateTable) PlannerOp(herddb.model.planner.PlannerOp) JdbcParameterExpression(herddb.sql.expressions.JdbcParameterExpression) TypedJdbcParameterExpression(herddb.sql.expressions.TypedJdbcParameterExpression) TypedJdbcParameterExpression(herddb.sql.expressions.TypedJdbcParameterExpression) AbstractTableManager(herddb.core.AbstractTableManager) AccessCurrentRowExpression(herddb.sql.expressions.AccessCurrentRowExpression) Expression(net.sf.jsqlparser.expression.Expression) CompiledMultiAndExpression(herddb.sql.expressions.CompiledMultiAndExpression) JdbcParameterExpression(herddb.sql.expressions.JdbcParameterExpression) AlterExpression(net.sf.jsqlparser.statement.alter.AlterExpression) TypedJdbcParameterExpression(herddb.sql.expressions.TypedJdbcParameterExpression) ConstantExpression(herddb.sql.expressions.ConstantExpression) SignedExpression(net.sf.jsqlparser.expression.SignedExpression) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) CompiledEqualsExpression(herddb.sql.expressions.CompiledEqualsExpression) DMLStatement(herddb.model.DMLStatement) OpSchema(herddb.sql.expressions.OpSchema) AutoIncrementPrimaryKeyRecordFunction(herddb.model.AutoIncrementPrimaryKeyRecordFunction) SimpleInsertOp(herddb.model.planner.SimpleInsertOp) InsertOp(herddb.model.planner.InsertOp)

Example 9 with ItemsList

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

the class JSQLParserPlanner method buildInsertStatement.

private ExecutionPlan buildInsertStatement(String defaultTableSpace, Insert insert, boolean returnValues) throws StatementExecutionException {
    net.sf.jsqlparser.schema.Table table = insert.getTable();
    // no alias for INSERT!
    checkSupported(table.getAlias() == null);
    checkSupported(insert.getSelect() == null);
    ItemsList itemsList = insert.getItemsList();
    List<net.sf.jsqlparser.schema.Column> columns = insert.getColumns();
    return planerInsertOrUpsert(defaultTableSpace, table, columns, itemsList, returnValues, false);
}
Also used : ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) Column(herddb.model.Column)

Example 10 with ItemsList

use of net.sf.jsqlparser.expression.operators.relational.ItemsList 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) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) List(java.util.List) StringValue(net.sf.jsqlparser.expression.StringValue) ExecutionException(java.util.concurrent.ExecutionException) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) 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)

Aggregations

ItemsList (net.sf.jsqlparser.expression.operators.relational.ItemsList)10 ArrayList (java.util.ArrayList)6 List (java.util.List)6 Expression (net.sf.jsqlparser.expression.Expression)5 ExpressionList (net.sf.jsqlparser.expression.operators.relational.ExpressionList)5 Column (herddb.model.Column)4 StatementExecutionException (herddb.model.StatementExecutionException)3 JdbcParameter (net.sf.jsqlparser.expression.JdbcParameter)3 SignedExpression (net.sf.jsqlparser.expression.SignedExpression)3 InExpression (net.sf.jsqlparser.expression.operators.relational.InExpression)3 AbstractTableManager (herddb.core.AbstractTableManager)2 TableSpaceManager (herddb.core.TableSpaceManager)2 AutoIncrementPrimaryKeyRecordFunction (herddb.model.AutoIncrementPrimaryKeyRecordFunction)2 RecordFunction (herddb.model.RecordFunction)2 Table (herddb.model.Table)2 InsertStatement (herddb.model.commands.InsertStatement)2 CompiledSQLExpression (herddb.sql.expressions.CompiledSQLExpression)2 IntHolder (herddb.utils.IntHolder)2 BinaryExpression (net.sf.jsqlparser.expression.BinaryExpression)2 DoubleValue (net.sf.jsqlparser.expression.DoubleValue)2