Search in sources :

Example 1 with JdbcParameter

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

the class SQLPlanner method buildInsertStatement.

private ExecutionPlan buildInsertStatement(String defaultTableSpace, Insert s, boolean returnValues) throws StatementExecutionException {
    String tableSpace = s.getTable().getSchemaName();
    String tableName = s.getTable().getName();
    if (tableSpace == null) {
        tableSpace = defaultTableSpace;
    }
    TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(tableSpace);
    if (tableSpaceManager == null) {
        throw new StatementExecutionException("no such tablespace " + tableSpace + " here at " + manager.getNodeId());
    }
    AbstractTableManager tableManager = tableSpaceManager.getTableManager(tableName);
    if (tableManager == null) {
        throw new StatementExecutionException("no such table " + tableName + " in tablespace " + tableSpace);
    }
    Table table = tableManager.getTable();
    ItemsList itemlist = s.getItemsList();
    if (itemlist instanceof ExpressionList) {
        int index = 0;
        List<Expression> keyValueExpression = new ArrayList<>();
        List<String> keyExpressionToColumn = new ArrayList<>();
        List<CompiledSQLExpression> valuesExpressions = new ArrayList<>();
        List<net.sf.jsqlparser.schema.Column> valuesColumns = new ArrayList<>();
        ExpressionList list = (ExpressionList) itemlist;
        if (s.getColumns() != null) {
            for (net.sf.jsqlparser.schema.Column c : s.getColumns()) {
                Column column = table.getColumn(c.getColumnName());
                if (column == null) {
                    throw new StatementExecutionException("no such column " + c.getColumnName() + " in table " + tableName + " in tablespace " + tableSpace);
                }
                Expression expression;
                try {
                    expression = list.getExpressions().get(index++);
                } catch (IndexOutOfBoundsException badQuery) {
                    throw new StatementExecutionException("bad number of VALUES in INSERT clause");
                }
                if (table.isPrimaryKeyColumn(column.name)) {
                    keyExpressionToColumn.add(column.name);
                    keyValueExpression.add(expression);
                }
                valuesColumns.add(c);
                valuesExpressions.add(SQLExpressionCompiler.compileExpression(null, expression));
            }
        } else {
            for (Column column : table.columns) {
                Expression expression = list.getExpressions().get(index++);
                if (table.isPrimaryKeyColumn(column.name)) {
                    keyExpressionToColumn.add(column.name);
                    keyValueExpression.add(expression);
                }
                valuesColumns.add(new net.sf.jsqlparser.schema.Column(column.name));
                valuesExpressions.add(SQLExpressionCompiler.compileExpression(null, expression));
            }
        }
        RecordFunction keyfunction;
        if (keyValueExpression.isEmpty() && table.auto_increment) {
            keyfunction = new AutoIncrementPrimaryKeyRecordFunction();
        } else {
            if (keyValueExpression.size() != table.primaryKey.length) {
                throw new StatementExecutionException("you must set a value for the primary key (expressions=" + keyValueExpression.size() + ")");
            }
            keyfunction = new SQLRecordKeyFunction(table, keyExpressionToColumn, keyValueExpression);
        }
        RecordFunction valuesfunction = new SQLRecordFunction(table, valuesColumns, valuesExpressions);
        try {
            return ExecutionPlan.simple(new InsertStatement(tableSpace, tableName, keyfunction, valuesfunction).setReturnValues(returnValues));
        } catch (IllegalArgumentException err) {
            throw new StatementExecutionException(err);
        }
    } else if (itemlist instanceof MultiExpressionList) {
        if (returnValues) {
            throw new StatementExecutionException("cannot 'return values' on multi-values insert");
        }
        MultiExpressionList multilist = (MultiExpressionList) itemlist;
        List<InsertStatement> inserts = new ArrayList<>();
        for (ExpressionList list : multilist.getExprList()) {
            List<Expression> keyValueExpression = new ArrayList<>();
            List<String> keyExpressionToColumn = new ArrayList<>();
            List<CompiledSQLExpression> valuesExpressions = new ArrayList<>();
            List<net.sf.jsqlparser.schema.Column> valuesColumns = new ArrayList<>();
            int index = 0;
            if (s.getColumns() != null) {
                for (net.sf.jsqlparser.schema.Column c : s.getColumns()) {
                    Column column = table.getColumn(c.getColumnName());
                    if (column == null) {
                        throw new StatementExecutionException("no such column " + c.getColumnName() + " in table " + tableName + " in tablespace " + tableSpace);
                    }
                    Expression expression;
                    try {
                        expression = list.getExpressions().get(index++);
                    } catch (IndexOutOfBoundsException badQuery) {
                        throw new StatementExecutionException("bad number of VALUES in INSERT clause");
                    }
                    if (table.isPrimaryKeyColumn(column.name)) {
                        keyExpressionToColumn.add(column.name);
                        keyValueExpression.add(expression);
                    }
                    valuesColumns.add(c);
                    valuesExpressions.add(SQLExpressionCompiler.compileExpression(null, expression));
                }
            } else {
                for (Column column : table.columns) {
                    Expression expression = list.getExpressions().get(index++);
                    if (table.isPrimaryKeyColumn(column.name)) {
                        keyExpressionToColumn.add(column.name);
                        keyValueExpression.add(expression);
                    }
                    valuesColumns.add(new net.sf.jsqlparser.schema.Column(column.name));
                    valuesExpressions.add(SQLExpressionCompiler.compileExpression(null, expression));
                }
            }
            RecordFunction keyfunction;
            if (keyValueExpression.isEmpty() && table.auto_increment) {
                keyfunction = new AutoIncrementPrimaryKeyRecordFunction();
            } else {
                if (keyValueExpression.size() != table.primaryKey.length) {
                    throw new StatementExecutionException("you must set a value for the primary key (expressions=" + keyValueExpression.size() + ")");
                }
                keyfunction = new SQLRecordKeyFunction(table, keyExpressionToColumn, keyValueExpression);
            }
            RecordFunction valuesfunction = new SQLRecordFunction(table, valuesColumns, valuesExpressions);
            InsertStatement insert = new InsertStatement(tableSpace, tableName, keyfunction, valuesfunction);
            inserts.add(insert);
        }
        try {
            return ExecutionPlan.multiInsert(inserts);
        } catch (IllegalArgumentException err) {
            throw new StatementExecutionException(err);
        }
    } else {
        List<Expression> keyValueExpression = new ArrayList<>();
        List<String> keyExpressionToColumn = new ArrayList<>();
        List<CompiledSQLExpression> valuesExpressions = new ArrayList<>();
        List<net.sf.jsqlparser.schema.Column> valuesColumns = new ArrayList<>();
        Select select = s.getSelect();
        ExecutionPlan datasource = buildSelectStatement(defaultTableSpace, select, true, -1);
        if (s.getColumns() == null) {
            throw new StatementExecutionException("for INSERT ... SELECT you have to declare the columns to be filled in (use INSERT INTO TABLE(c,c,c,) SELECT .....)");
        }
        IntHolder holder = new IntHolder(1);
        for (net.sf.jsqlparser.schema.Column c : s.getColumns()) {
            Column column = table.getColumn(c.getColumnName());
            if (column == null) {
                throw new StatementExecutionException("no such column " + c.getColumnName() + " in table " + tableName + " in tablespace " + tableSpace);
            }
            JdbcParameter readFromResultSetAsJdbcParameter = new JdbcParameter();
            readFromResultSetAsJdbcParameter.setIndex(holder.value++);
            if (table.isPrimaryKeyColumn(column.name)) {
                keyExpressionToColumn.add(column.name);
                keyValueExpression.add(readFromResultSetAsJdbcParameter);
            }
            valuesColumns.add(c);
            valuesExpressions.add(SQLExpressionCompiler.compileExpression(null, readFromResultSetAsJdbcParameter));
        }
        RecordFunction keyfunction;
        if (keyValueExpression.isEmpty() && table.auto_increment) {
            keyfunction = new AutoIncrementPrimaryKeyRecordFunction();
        } else {
            if (keyValueExpression.size() != table.primaryKey.length) {
                throw new StatementExecutionException("you must set a value for the primary key (expressions=" + keyValueExpression.size() + ")");
            }
            keyfunction = new SQLRecordKeyFunction(table, keyExpressionToColumn, keyValueExpression);
        }
        RecordFunction valuesfunction = new SQLRecordFunction(table, valuesColumns, valuesExpressions);
        try {
            return ExecutionPlan.dataManipulationFromSelect(new InsertStatement(tableSpace, tableName, keyfunction, valuesfunction).setReturnValues(returnValues), datasource);
        } catch (IllegalArgumentException err) {
            throw new StatementExecutionException(err);
        }
    }
}
Also used : ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) StatementExecutionException(herddb.model.StatementExecutionException) InsertStatement(herddb.model.commands.InsertStatement) ExecutionPlan(herddb.model.ExecutionPlan) Column(herddb.model.Column) TableSpaceManager(herddb.core.TableSpaceManager) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) IntHolder(herddb.utils.IntHolder) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) ColumnsList(herddb.model.ColumnsList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) List(java.util.List) RecordFunction(herddb.model.RecordFunction) AutoIncrementPrimaryKeyRecordFunction(herddb.model.AutoIncrementPrimaryKeyRecordFunction) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) Table(herddb.model.Table) CreateTable(net.sf.jsqlparser.statement.create.table.CreateTable) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) AbstractTableManager(herddb.core.AbstractTableManager) Expression(net.sf.jsqlparser.expression.Expression) AlterExpression(net.sf.jsqlparser.statement.alter.AlterExpression) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) SignedExpression(net.sf.jsqlparser.expression.SignedExpression) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) Select(net.sf.jsqlparser.statement.select.Select) AutoIncrementPrimaryKeyRecordFunction(herddb.model.AutoIncrementPrimaryKeyRecordFunction)

Example 2 with JdbcParameter

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

the class SQLPlanner method buildSelectStatement.

private ExecutionPlan buildSelectStatement(String defaultTableSpace, Select s, boolean scan, int maxRows) throws StatementExecutionException {
    PlainSelect selectBody = (PlainSelect) s.getSelectBody();
    net.sf.jsqlparser.schema.Table fromTable = (net.sf.jsqlparser.schema.Table) selectBody.getFromItem();
    TableRef mainTable = TableRef.buildFrom(fromTable, defaultTableSpace);
    String mainTableAlias = mainTable.tableAlias;
    String tableSpace = mainTable.tableSpace;
    TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(tableSpace);
    if (tableSpaceManager == null) {
        throw new TableSpaceDoesNotExistException("no such tablespace " + tableSpace + " here at " + manager.getNodeId());
    }
    AbstractTableManager tableManager = tableSpaceManager.getTableManager(mainTable.tableName);
    if (tableManager == null) {
        throw new TableDoesNotExistException("no such table " + mainTable.tableName + " in tablespace " + tableSpace);
    }
    // linked hash map retains the order of insertions
    LinkedHashMap<String, JoinSupport> joins = new LinkedHashMap<>();
    boolean joinPresent = false;
    joins.put(mainTable.tableAlias, new JoinSupport(mainTable, tableManager));
    if (selectBody.getJoins() != null) {
        for (Join join : selectBody.getJoins()) {
            joinPresent = true;
            if (join.isLeft() || join.isCross() || join.isRight() || join.isOuter() || join.isSimple()) {
                throw new StatementExecutionException("unsupported JOIN type: " + join);
            }
            net.sf.jsqlparser.schema.Table joinedTable = (net.sf.jsqlparser.schema.Table) join.getRightItem();
            TableRef joinedTableRef = TableRef.buildFrom(joinedTable, defaultTableSpace);
            if (!joinedTableRef.tableSpace.equalsIgnoreCase(mainTable.tableSpace)) {
                throw new TableDoesNotExistException("unsupported cross-tablespace JOIN " + "between" + mainTable.tableSpace + "." + mainTable.tableName + " and " + joinedTableRef.tableSpace + "." + joinedTableRef.tableName);
            }
            AbstractTableManager joinedTableManager = tableSpaceManager.getTableManager(joinedTableRef.tableName);
            if (joinedTableManager == null) {
                throw new TableDoesNotExistException("no such table " + joinedTableRef.tableName + " in tablespace " + tableSpace);
            }
            JoinSupport joinSupport = new JoinSupport(joinedTableRef, joinedTableManager);
            joins.put(joinedTableRef.tableAlias, joinSupport);
        }
    }
    Projection mainTableProjection;
    Table table = tableManager.getTable();
    boolean allColumns = false;
    boolean containsAggregateFunctions = false;
    for (SelectItem c : selectBody.getSelectItems()) {
        if (c instanceof AllColumns) {
            allColumns = true;
            break;
        } else if (c instanceof AllTableColumns) {
            AllTableColumns allTableColumns = (AllTableColumns) c;
            TableRef ref = TableRef.buildFrom(allTableColumns.getTable(), defaultTableSpace);
            if (!joinPresent && ref.tableAlias.equals(mainTable.tableAlias)) {
                // select a.*  FROM table a
                allColumns = true;
            } else {
                // select a.*, b.* FROM table a JOIN table b
                joins.get(ref.tableAlias).allColumns = true;
            }
        } else if (c instanceof SelectExpressionItem) {
            SelectExpressionItem se = (SelectExpressionItem) c;
            if (isAggregateFunction(se.getExpression())) {
                containsAggregateFunctions = true;
            }
            if (!joinPresent) {
                joins.get(mainTable.tableAlias).selectItems.add(c);
            } else {
                ColumnReferencesDiscovery discoverMainTableAlias = discoverMainTableAlias(se.getExpression());
                String mainTableAliasForItem = discoverMainTableAlias.getMainTableAlias();
                if (discoverMainTableAlias.isContainsMixedAliases()) {
                    throw new StatementExecutionException("unsupported single SELECT ITEM with mixed aliases: " + c);
                }
                if (mainTableAliasForItem == null) {
                    mainTableAliasForItem = mainTable.tableAlias;
                }
                joins.get(mainTableAliasForItem).selectItems.add(c);
            }
        } else {
            throw new StatementExecutionException("unsupported SELECT ITEM type: " + c);
        }
    }
    if (allColumns) {
        mainTableProjection = Projection.IDENTITY(table.columnNames, table.columns);
        for (Map.Entry<String, JoinSupport> join : joins.entrySet()) {
            JoinSupport support = join.getValue();
            support.projection = Projection.IDENTITY(support.table.columnNames, support.table.columns);
            support.allColumns = true;
        }
    } else {
        if (!joinPresent) {
            mainTableProjection = new SQLProjection(table, mainTableAlias, selectBody.getSelectItems());
        } else {
            for (JoinSupport support : joins.values()) {
                if (support.allColumns) {
                    support.projection = Projection.IDENTITY(support.table.columnNames, support.table.columns);
                } else {
                    support.projection = new SQLProjection(support.table, support.tableRef.tableAlias, support.selectItems);
                }
            }
            mainTableProjection = joins.get(mainTableAlias).projection;
        }
    }
    if (scan) {
        if (!joinPresent) {
            SQLRecordPredicate where = selectBody.getWhere() != null ? new SQLRecordPredicate(table, mainTableAlias, selectBody.getWhere()) : null;
            if (where != null) {
                discoverIndexOperations(selectBody.getWhere(), table, mainTableAlias, where, tableSpaceManager);
            }
            Aggregator aggregator = null;
            ScanLimitsImpl scanLimits = null;
            if (containsAggregateFunctions || (selectBody.getGroupByColumnReferences() != null && !selectBody.getGroupByColumnReferences().isEmpty())) {
                aggregator = new SQLAggregator(selectBody.getSelectItems(), selectBody.getGroupByColumnReferences(), manager.getRecordSetFactory());
            }
            TupleComparator comparatorOnScan = null;
            TupleComparator comparatorOnPlan = null;
            if (selectBody.getOrderByElements() != null && !selectBody.getOrderByElements().isEmpty()) {
                if (aggregator != null) {
                    comparatorOnPlan = SingleColumnSQLTupleComparator.make(mainTableAlias, selectBody.getOrderByElements(), null);
                } else {
                    comparatorOnScan = SingleColumnSQLTupleComparator.make(mainTableAlias, selectBody.getOrderByElements(), table.primaryKey);
                }
            }
            Limit limit = selectBody.getLimit();
            Top top = selectBody.getTop();
            if (limit != null && top != null) {
                throw new StatementExecutionException("LIMIT and TOP cannot be used on the same query");
            }
            if (limit != null) {
                if (limit.isLimitAll() || limit.isLimitNull() || limit.getOffset() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ")");
                }
                if (maxRows > 0 && limit.getRowCount() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ") and JDBC setMaxRows=" + maxRows);
                }
                int rowCount;
                int rowCountJdbcParameter = -1;
                if (limit.getRowCount() instanceof JdbcParameter) {
                    rowCount = -1;
                    rowCountJdbcParameter = ((JdbcParameter) limit.getRowCount()).getIndex() - 1;
                } else {
                    rowCount = ((Number) resolveValue(limit.getRowCount(), false)).intValue();
                }
                int offset = limit.getOffset() != null ? ((Number) resolveValue(limit.getOffset(), false)).intValue() : 0;
                scanLimits = new ScanLimitsImpl(rowCount, offset, rowCountJdbcParameter + 1);
            } else if (top != null) {
                if (top.isPercentage() || top.getExpression() == null) {
                    throw new StatementExecutionException("Invalid TOP clause (top=" + top + ")");
                }
                try {
                    int rowCount = Integer.parseInt(resolveValue(top.getExpression(), false) + "");
                    scanLimits = new ScanLimitsImpl(rowCount, 0);
                } catch (NumberFormatException error) {
                    throw new StatementExecutionException("Invalid TOP clause: " + error, error);
                }
            }
            if (maxRows > 0) {
                if (scanLimits == null) {
                    scanLimits = new ScanLimitsImpl(maxRows, 0);
                } else if (scanLimits.getMaxRows() <= 0 || scanLimits.getMaxRows() > maxRows) {
                    scanLimits = new ScanLimitsImpl(maxRows, scanLimits.getOffset());
                }
            }
            ScanLimitsImpl limitsOnScan = null;
            ScanLimitsImpl limitsOnPlan = null;
            if (aggregator != null) {
                limitsOnPlan = scanLimits;
            } else {
                limitsOnScan = scanLimits;
            }
            try {
                ScanStatement statement = new ScanStatement(tableSpace, mainTable.tableName, mainTableProjection, where, comparatorOnScan, limitsOnScan);
                return ExecutionPlan.make(statement, aggregator, limitsOnPlan, comparatorOnPlan);
            } catch (IllegalArgumentException err) {
                throw new StatementExecutionException(err);
            }
        } else {
            if (containsAggregateFunctions || (selectBody.getGroupByColumnReferences() != null && !selectBody.getGroupByColumnReferences().isEmpty())) {
                throw new StatementExecutionException("AGGREGATEs are not yet supported with JOIN");
            }
            Limit limit = selectBody.getLimit();
            Top top = selectBody.getTop();
            if (limit != null && top != null) {
                throw new StatementExecutionException("LIMIT and TOP cannot be used on the same query");
            }
            ScanLimitsImpl scanLimits = null;
            if (limit != null) {
                if (limit.isLimitAll() || limit.isLimitNull() || limit.getOffset() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ")");
                }
                if (maxRows > 0 && limit.getRowCount() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ") and JDBC setMaxRows=" + maxRows);
                }
                int rowCount;
                int rowCountJdbcParameter = -1;
                if (limit.getRowCount() instanceof JdbcParameter) {
                    rowCount = -1;
                    rowCountJdbcParameter = ((JdbcParameter) limit.getRowCount()).getIndex() - 1;
                } else {
                    rowCount = ((Number) resolveValue(limit.getRowCount(), false)).intValue();
                }
                int offset = limit.getOffset() != null ? ((Number) resolveValue(limit.getOffset(), false)).intValue() : 0;
                scanLimits = new ScanLimitsImpl(rowCount, offset, rowCountJdbcParameter + 1);
            } else if (top != null) {
                if (top.isPercentage() || top.getExpression() == null) {
                    throw new StatementExecutionException("Invalid TOP clause");
                }
                try {
                    int rowCount = Integer.parseInt(resolveValue(top.getExpression(), false) + "");
                    scanLimits = new ScanLimitsImpl(rowCount, 0);
                } catch (NumberFormatException error) {
                    throw new StatementExecutionException("Invalid TOP clause: " + error, error);
                }
            }
            if (maxRows > 0) {
                if (scanLimits == null) {
                    scanLimits = new ScanLimitsImpl(maxRows, 0);
                } else if (scanLimits.getMaxRows() <= 0 || scanLimits.getMaxRows() > maxRows) {
                    scanLimits = new ScanLimitsImpl(maxRows, scanLimits.getOffset());
                }
            }
            List<ColumnReferencesDiscovery> conditionsOnJoinedResult = new ArrayList<>();
            List<ScanStatement> scans = new ArrayList<>();
            for (Map.Entry<String, JoinSupport> join : joins.entrySet()) {
                String alias = join.getKey();
                JoinSupport joinSupport = join.getValue();
                Expression collectedConditionsForAlias = collectConditionsForAlias(alias, selectBody.getWhere(), conditionsOnJoinedResult, mainTableAlias);
                LOG.severe("Collected WHERE for alias " + alias + ": " + collectedConditionsForAlias);
                if (collectedConditionsForAlias == null) {
                    joinSupport.predicate = null;
                } else {
                    joinSupport.predicate = new SQLRecordPredicate(join.getValue().table, alias, collectedConditionsForAlias);
                }
            }
            for (Join join : selectBody.getJoins()) {
                if (join.getOnExpression() != null) {
                    ColumnReferencesDiscovery discoverMainTableAliasForJoinCondition = discoverMainTableAlias(join.getOnExpression());
                    conditionsOnJoinedResult.add(discoverMainTableAliasForJoinCondition);
                    LOG.severe("Collected ON-condition on final JOIN result: " + join.getOnExpression());
                }
            }
            for (ColumnReferencesDiscovery e : conditionsOnJoinedResult) {
                LOG.severe("Collected WHERE on final JOIN result: " + e.getExpression());
                for (Map.Entry<String, List<net.sf.jsqlparser.schema.Column>> entry : e.getColumnsByTable().entrySet()) {
                    String tableAlias = entry.getKey();
                    List<net.sf.jsqlparser.schema.Column> filteredColumnsOnJoin = entry.getValue();
                    LOG.severe("for  TABLE " + tableAlias + " we need to load " + filteredColumnsOnJoin);
                    JoinSupport support = joins.get(tableAlias);
                    if (support == null) {
                        throw new StatementExecutionException("invalid table alias " + tableAlias);
                    }
                    if (!support.allColumns) {
                        for (net.sf.jsqlparser.schema.Column c : filteredColumnsOnJoin) {
                            support.selectItems.add(new SelectExpressionItem(c));
                        }
                        support.projection = new SQLProjection(support.table, support.tableRef.tableAlias, support.selectItems);
                    }
                }
            }
            Map<String, Table> tables = new HashMap<>();
            for (Map.Entry<String, JoinSupport> join : joins.entrySet()) {
                JoinSupport joinSupport = join.getValue();
                tables.put(join.getKey(), joinSupport.table);
                ScanStatement statement = new ScanStatement(tableSpace, joinSupport.table.name, joinSupport.projection, joinSupport.predicate, null, null);
                scans.add(statement);
            }
            TuplePredicate joinFilter = null;
            if (!conditionsOnJoinedResult.isEmpty()) {
                joinFilter = new SQLRecordPredicate(null, null, composeAndExpression(conditionsOnJoinedResult));
            }
            Projection joinProjection = null;
            if (!allColumns) {
                joinProjection = new SQLProjection(tableSpace, tables, selectBody.getSelectItems());
            }
            TupleComparator comparatorOnPlan = null;
            if (selectBody.getOrderByElements() != null && !selectBody.getOrderByElements().isEmpty()) {
                comparatorOnPlan = SingleColumnSQLTupleComparator.make(mainTableAlias, selectBody.getOrderByElements(), null);
            }
            try {
                return ExecutionPlan.joinedScan(scans, joinFilter, joinProjection, scanLimits, comparatorOnPlan);
            } catch (IllegalArgumentException err) {
                throw new StatementExecutionException(err);
            }
        }
    } else {
        if (selectBody.getWhere() == null) {
            throw new StatementExecutionException("unsupported GET without WHERE");
        }
        if (joinPresent) {
            throw new StatementExecutionException("unsupported GET with JOIN");
        }
        // SELECT * FROM WHERE KEY=? AND ....
        SQLRecordKeyFunction keyFunction = findPrimaryKeyIndexSeek(selectBody.getWhere(), table, mainTableAlias);
        if (keyFunction == null || !keyFunction.isFullPrimaryKey()) {
            throw new StatementExecutionException("unsupported GET not on PK, bad where clause: " + selectBody.getWhere() + " (" + selectBody.getWhere().getClass() + ")");
        }
        Predicate where = buildSimplePredicate(selectBody.getWhere(), table, mainTableAlias);
        try {
            return ExecutionPlan.simple(new GetStatement(tableSpace, mainTable.tableName, keyFunction, where, false));
        } catch (IllegalArgumentException err) {
            throw new StatementExecutionException(err);
        }
    }
}
Also used : TuplePredicate(herddb.model.TuplePredicate) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Projection(herddb.model.Projection) StatementExecutionException(herddb.model.StatementExecutionException) LinkedHashMap(java.util.LinkedHashMap) TuplePredicate(herddb.model.TuplePredicate) Predicate(herddb.model.Predicate) TableSpaceManager(herddb.core.TableSpaceManager) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) ColumnsList(herddb.model.ColumnsList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) List(java.util.List) Top(net.sf.jsqlparser.statement.select.Top) AbstractTableManager(herddb.core.AbstractTableManager) GetStatement(herddb.model.commands.GetStatement) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) TableSpaceDoesNotExistException(herddb.model.TableSpaceDoesNotExistException) SelectExpressionItem(net.sf.jsqlparser.statement.select.SelectExpressionItem) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) TupleComparator(herddb.model.TupleComparator) AllColumns(net.sf.jsqlparser.statement.select.AllColumns) Column(herddb.model.Column) SelectItem(net.sf.jsqlparser.statement.select.SelectItem) ScanStatement(herddb.model.commands.ScanStatement) Table(herddb.model.Table) CreateTable(net.sf.jsqlparser.statement.create.table.CreateTable) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) Join(net.sf.jsqlparser.statement.select.Join) Aggregator(herddb.model.Aggregator) ScanLimitsImpl(herddb.model.ScanLimitsImpl) TableDoesNotExistException(herddb.model.TableDoesNotExistException) Expression(net.sf.jsqlparser.expression.Expression) AlterExpression(net.sf.jsqlparser.statement.alter.AlterExpression) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) SignedExpression(net.sf.jsqlparser.expression.SignedExpression) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) AllTableColumns(net.sf.jsqlparser.statement.select.AllTableColumns) Limit(net.sf.jsqlparser.statement.select.Limit)

Example 3 with JdbcParameter

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

the class JdbcQueryRewriter method visit.

@Override
public void visit(ExpressionList expressionList) {
    List<Expression> expressions = expressionList.getExpressions();
    int size = expressions.size();
    for (int i = 0; i < size; i++) {
        Expression e = expressions.get(i);
        if (e instanceof JdbcParameter) {
            e = ImmutableExpressionsCache.internOrFixJdbcParameterExpression((JdbcParameter) e);
        }
        expressions.set(i, e);
        e.accept(this);
    }
}
Also used : KeepExpression(net.sf.jsqlparser.expression.KeepExpression) CaseExpression(net.sf.jsqlparser.expression.CaseExpression) NotExpression(net.sf.jsqlparser.expression.NotExpression) CastExpression(net.sf.jsqlparser.expression.CastExpression) IsNullExpression(net.sf.jsqlparser.expression.operators.relational.IsNullExpression) Expression(net.sf.jsqlparser.expression.Expression) IntervalExpression(net.sf.jsqlparser.expression.IntervalExpression) OrExpression(net.sf.jsqlparser.expression.operators.conditional.OrExpression) TimeKeyExpression(net.sf.jsqlparser.expression.TimeKeyExpression) JsonExpression(net.sf.jsqlparser.expression.JsonExpression) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) AnalyticExpression(net.sf.jsqlparser.expression.AnalyticExpression) AnyComparisonExpression(net.sf.jsqlparser.expression.AnyComparisonExpression) DateTimeLiteralExpression(net.sf.jsqlparser.expression.DateTimeLiteralExpression) AlterExpression(net.sf.jsqlparser.statement.alter.AlterExpression) WithinGroupExpression(net.sf.jsqlparser.expression.WithinGroupExpression) OracleHierarchicalExpression(net.sf.jsqlparser.expression.OracleHierarchicalExpression) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) LikeExpression(net.sf.jsqlparser.expression.operators.relational.LikeExpression) ExistsExpression(net.sf.jsqlparser.expression.operators.relational.ExistsExpression) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) AllComparisonExpression(net.sf.jsqlparser.expression.AllComparisonExpression) ExtractExpression(net.sf.jsqlparser.expression.ExtractExpression) SignedExpression(net.sf.jsqlparser.expression.SignedExpression) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) OracleHint(net.sf.jsqlparser.expression.OracleHint)

Example 4 with JdbcParameter

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

the class SQLExpressionCompiler method compileSpecialBinaryExpression.

private static CompiledSQLExpression compileSpecialBinaryExpression(String validatedTableAlias, Expression exp) {
    BinaryExpression be = (BinaryExpression) exp;
    // MOST frequent expressions "TABLE.COLUMNNAME OPERATOR ?", we can hardcode the access to the column and to the JDBC parameter
    if (be.getLeftExpression() instanceof net.sf.jsqlparser.schema.Column) {
        net.sf.jsqlparser.schema.Column c = (net.sf.jsqlparser.schema.Column) be.getLeftExpression();
        if (validatedTableAlias != null) {
            if (c.getTable() != null && c.getTable().getName() != null && !c.getTable().getName().equals(validatedTableAlias)) {
                return null;
            }
        }
        String columnName = c.getColumnName();
        switch(columnName) {
            case BuiltinFunctions.BOOLEAN_TRUE:
                return null;
            case BuiltinFunctions.BOOLEAN_FALSE:
                return null;
            default:
                // OK !
                break;
        }
        if (be.getRightExpression() instanceof JdbcParameter) {
            JdbcParameter jdbcParam = (JdbcParameter) be.getRightExpression();
            int jdbcIndex = jdbcParam.getIndex() - 1;
            if (be instanceof EqualsTo) {
                return new ColumnEqualsJdbcParameter(be.isNot(), columnName, jdbcIndex);
            } else if (be instanceof NotEqualsTo) {
                return new ColumnNotEqualsJdbcParameter(be.isNot(), columnName, jdbcIndex);
            } else if (be instanceof GreaterThanEquals) {
                return new ColumnGreaterThanEqualsJdbcParameter(be.isNot(), columnName, jdbcIndex);
            } else if (be instanceof GreaterThan) {
                return new ColumnGreaterThanJdbcParameter(be.isNot(), columnName, jdbcIndex);
            } else if (be instanceof MinorThan) {
                return new ColumnMinorThanJdbcParameter(be.isNot(), columnName, jdbcIndex);
            } else if (be instanceof MinorThanEquals) {
                return new ColumnMinorThanEqualsJdbcParameter(be.isNot(), columnName, jdbcIndex);
            }
        }
    // TODO handle "TABLE.COLUMNNAME OPERATOR CONSTANT"
    }
    return null;
}
Also used : MinorThan(net.sf.jsqlparser.expression.operators.relational.MinorThan) MinorThanEquals(net.sf.jsqlparser.expression.operators.relational.MinorThanEquals) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) NotEqualsTo(net.sf.jsqlparser.expression.operators.relational.NotEqualsTo) RawString(herddb.utils.RawString) GreaterThanEquals(net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) GreaterThan(net.sf.jsqlparser.expression.operators.relational.GreaterThan) EqualsTo(net.sf.jsqlparser.expression.operators.relational.EqualsTo) NotEqualsTo(net.sf.jsqlparser.expression.operators.relational.NotEqualsTo)

Example 5 with JdbcParameter

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

the class SQLExpressionCompiler method compileExpression.

// this method never returns NULL
public static CompiledSQLExpression compileExpression(String validatedTableAlias, Expression exp) {
    if (exp instanceof BinaryExpression) {
        CompiledSQLExpression compiled = compileSpecialBinaryExpression(validatedTableAlias, exp);
        if (compiled != null) {
            return compiled;
        }
    }
    if (exp instanceof net.sf.jsqlparser.schema.Column) {
        return compileColumnExpression(validatedTableAlias, exp);
    } else if (exp instanceof StringValue) {
        return new ConstantExpression(RawString.of(((StringValue) exp).getValue()));
    } else if (exp instanceof LongValue) {
        try {
            return new ConstantExpression(((LongValue) exp).getValue());
        } catch (NumberFormatException largeNumber) {
            return new ConstantExpression(Double.valueOf(((LongValue) exp).getStringValue()));
        }
    } else if (exp instanceof DoubleValue) {
        return new ConstantExpression(((DoubleValue) exp).getValue());
    } else if (exp instanceof TimestampValue) {
        return new ConstantExpression(((TimestampValue) exp).getValue());
    } else if (exp instanceof NullValue) {
        return new ConstantExpression(null);
    } else if (exp instanceof TimeKeyExpression) {
        TimeKeyExpression ext = (TimeKeyExpression) exp;
        if (CURRENT_TIMESTAMP.equalsIgnoreCase(ext.getStringValue())) {
            return new ConstantExpression(new java.sql.Timestamp(System.currentTimeMillis()));
        } else {
            throw new StatementExecutionException("unhandled expression " + exp);
        }
    } else if (exp instanceof JdbcParameter) {
        int index = ((JdbcParameter) exp).getIndex() - 1;
        return new JdbcParameterExpression(index);
    } else if (exp instanceof AndExpression) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledAndExpression(a, b, c));
    } else if (exp instanceof OrExpression) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledOrExpression(a, b, c));
    } else if (exp instanceof Function) {
        return CompiledFunction.create((Function) exp, validatedTableAlias);
    } else if (exp instanceof Addition) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledAddExpression(a, b, c));
    } else if (exp instanceof Subtraction) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledSubtractExpression(a, b, c));
    } else if (exp instanceof Multiplication) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledMultiplyExpression(a, b, c));
    } else if (exp instanceof Division) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledDivideExpression(a, b, c));
    } else if (exp instanceof Parenthesis) {
        Parenthesis p = (Parenthesis) exp;
        CompiledSQLExpression inner = compileExpression(validatedTableAlias, p.getExpression());
        return new CompiledParenthesisExpression(p.isNot(), inner);
    } else if (exp instanceof EqualsTo) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledEqualsExpression(a, b, c));
    } else if (exp instanceof NotEqualsTo) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledNotEqualsExpression(a, b, c));
    } else if (exp instanceof MinorThan) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledMinorThenExpression(a, b, c));
    } else if (exp instanceof MinorThanEquals) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledMinorThenEqualsExpression(a, b, c));
    } else if (exp instanceof GreaterThan) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledGreaterThenExpression(a, b, c));
    } else if (exp instanceof GreaterThanEquals) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledGreaterThenEqualsExpression(a, b, c));
    } else if (exp instanceof LikeExpression) {
        return tryCompileBinaryExpression(validatedTableAlias, (BinaryExpression) exp, (a, b, c) -> new CompiledLikeExpression(a, b, c));
    } else if (exp instanceof Between) {
        return CompiledBetweenExpression.create(validatedTableAlias, (Between) exp);
    } else if (exp instanceof SignedExpression) {
        SignedExpression s = (SignedExpression) exp;
        CompiledSQLExpression inner = compileExpression(validatedTableAlias, s.getExpression());
        return new CompiledSignedExpression(s.getSign(), inner);
    } else if (exp instanceof InExpression) {
        InExpression in = (InExpression) exp;
        return CompiledInExpression.create(in, validatedTableAlias);
    } else if (exp instanceof IsNullExpression) {
        IsNullExpression i = (IsNullExpression) exp;
        CompiledSQLExpression left = compileExpression(validatedTableAlias, i.getLeftExpression());
        return new CompiledIsNullExpression(i.isNot(), left);
    } else if (exp instanceof CaseExpression) {
        return CompiledCaseExpression.create(validatedTableAlias, (CaseExpression) exp);
    }
    throw new StatementExecutionException("unsupported operand " + exp.getClass() + ", expression is " + exp);
}
Also used : Arrays(java.util.Arrays) Multiplication(net.sf.jsqlparser.expression.operators.arithmetic.Multiplication) BigDecimal(java.math.BigDecimal) Addition(net.sf.jsqlparser.expression.operators.arithmetic.Addition) CaseExpression(net.sf.jsqlparser.expression.CaseExpression) RexNode(org.apache.calcite.rex.RexNode) Map(java.util.Map) GreaterThanEquals(net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals) RawString(herddb.utils.RawString) StatementExecutionException(herddb.model.StatementExecutionException) IsNullExpression(net.sf.jsqlparser.expression.operators.relational.IsNullExpression) RexLiteral(org.apache.calcite.rex.RexLiteral) NullValue(net.sf.jsqlparser.expression.NullValue) GreaterThan(net.sf.jsqlparser.expression.operators.relational.GreaterThan) Expression(net.sf.jsqlparser.expression.Expression) MinorThanEquals(net.sf.jsqlparser.expression.operators.relational.MinorThanEquals) SqlCastFunction(org.apache.calcite.sql.fun.SqlCastFunction) RexInputRef(org.apache.calcite.rex.RexInputRef) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) Subtraction(net.sf.jsqlparser.expression.operators.arithmetic.Subtraction) OrExpression(net.sf.jsqlparser.expression.operators.conditional.OrExpression) List(java.util.List) TimeKeyExpression(net.sf.jsqlparser.expression.TimeKeyExpression) RexDynamicParam(org.apache.calcite.rex.RexDynamicParam) BinaryExpressionBuilder(herddb.sql.expressions.CompiledSQLExpression.BinaryExpressionBuilder) RexCorrelVariable(org.apache.calcite.rex.RexCorrelVariable) CalcitePlanner(herddb.sql.CalcitePlanner) RexCall(org.apache.calcite.rex.RexCall) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) RexFieldAccess(org.apache.calcite.rex.RexFieldAccess) BuiltinFunctions(herddb.sql.functions.BuiltinFunctions) LikeExpression(net.sf.jsqlparser.expression.operators.relational.LikeExpression) Division(net.sf.jsqlparser.expression.operators.arithmetic.Division) CURRENT_TIMESTAMP(herddb.sql.functions.BuiltinFunctions.CURRENT_TIMESTAMP) MinorThan(net.sf.jsqlparser.expression.operators.relational.MinorThan) ArrayList(java.util.ArrayList) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) Function(net.sf.jsqlparser.expression.Function) DoubleValue(net.sf.jsqlparser.expression.DoubleValue) SqlOperator(org.apache.calcite.sql.SqlOperator) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) EqualsTo(net.sf.jsqlparser.expression.operators.relational.EqualsTo) SignedExpression(net.sf.jsqlparser.expression.SignedExpression) LongValue(net.sf.jsqlparser.expression.LongValue) AbstractMap(java.util.AbstractMap) TimestampValue(net.sf.jsqlparser.expression.TimestampValue) NotEqualsTo(net.sf.jsqlparser.expression.operators.relational.NotEqualsTo) Between(net.sf.jsqlparser.expression.operators.relational.Between) Collections(java.util.Collections) StringValue(net.sf.jsqlparser.expression.StringValue) Parenthesis(net.sf.jsqlparser.expression.Parenthesis) Multiplication(net.sf.jsqlparser.expression.operators.arithmetic.Multiplication) InExpression(net.sf.jsqlparser.expression.operators.relational.InExpression) OrExpression(net.sf.jsqlparser.expression.operators.conditional.OrExpression) StatementExecutionException(herddb.model.StatementExecutionException) CaseExpression(net.sf.jsqlparser.expression.CaseExpression) NullValue(net.sf.jsqlparser.expression.NullValue) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) GreaterThan(net.sf.jsqlparser.expression.operators.relational.GreaterThan) StringValue(net.sf.jsqlparser.expression.StringValue) Addition(net.sf.jsqlparser.expression.operators.arithmetic.Addition) 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) EqualsTo(net.sf.jsqlparser.expression.operators.relational.EqualsTo) NotEqualsTo(net.sf.jsqlparser.expression.operators.relational.NotEqualsTo) MinorThanEquals(net.sf.jsqlparser.expression.operators.relational.MinorThanEquals) SqlCastFunction(org.apache.calcite.sql.fun.SqlCastFunction) Function(net.sf.jsqlparser.expression.Function) Parenthesis(net.sf.jsqlparser.expression.Parenthesis) TimestampValue(net.sf.jsqlparser.expression.TimestampValue) Division(net.sf.jsqlparser.expression.operators.arithmetic.Division) MinorThan(net.sf.jsqlparser.expression.operators.relational.MinorThan) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) NotEqualsTo(net.sf.jsqlparser.expression.operators.relational.NotEqualsTo) GreaterThanEquals(net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals) LikeExpression(net.sf.jsqlparser.expression.operators.relational.LikeExpression) Subtraction(net.sf.jsqlparser.expression.operators.arithmetic.Subtraction) DoubleValue(net.sf.jsqlparser.expression.DoubleValue) SignedExpression(net.sf.jsqlparser.expression.SignedExpression)

Aggregations

JdbcParameter (net.sf.jsqlparser.expression.JdbcParameter)11 BinaryExpression (net.sf.jsqlparser.expression.BinaryExpression)5 Expression (net.sf.jsqlparser.expression.Expression)5 StringReader (java.io.StringReader)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 SignedExpression (net.sf.jsqlparser.expression.SignedExpression)4 AndExpression (net.sf.jsqlparser.expression.operators.conditional.AndExpression)4 ExpressionList (net.sf.jsqlparser.expression.operators.relational.ExpressionList)4 Test (org.junit.Test)4 StatementExecutionException (herddb.model.StatementExecutionException)3 GreaterThanEquals (net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals)3 ItemsList (net.sf.jsqlparser.expression.operators.relational.ItemsList)3 MultiExpressionList (net.sf.jsqlparser.expression.operators.relational.MultiExpressionList)3 AlterExpression (net.sf.jsqlparser.statement.alter.AlterExpression)3 PlainSelect (net.sf.jsqlparser.statement.select.PlainSelect)3 AbstractTableManager (herddb.core.AbstractTableManager)2 TableSpaceManager (herddb.core.TableSpaceManager)2 Column (herddb.model.Column)2 ColumnsList (herddb.model.ColumnsList)2