Search in sources :

Example 71 with StatementExecutionException

use of herddb.model.StatementExecutionException 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 72 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class SQLRecordFunction method computeNewValue.

@Override
public byte[] computeNewValue(Record previous, StatementEvaluationContext context, TableContext tableContext) throws StatementExecutionException {
    try {
        if (previous != null) {
            Map<String, Object> asMap = previous.toBean(table);
            DataAccessor bean = previous.getDataAccessor(table);
            Function<String, Object> fieldValueComputer = (columnName) -> {
                CompiledSQLExpression e = expressionsByColumnName.get(columnName);
                if (e == null) {
                    return asMap.get(columnName);
                } else {
                    herddb.model.Column column = table.getColumn(columnName);
                    if (column == null) {
                        throw new StatementExecutionException("unknown column " + columnName + " in table " + table.name);
                    }
                    try {
                        return RecordSerializer.convert(column.type, e.evaluate(bean, context));
                    } catch (StatementExecutionException err) {
                        throw new StatementExecutionException("error on column " + column.name + " (" + ColumnTypes.typeToString(column.type) + "):" + err.getMessage(), err);
                    }
                }
            };
            return RecordSerializer.buildRecord(previous.value != null ? previous.value.getLength() : 0, table, fieldValueComputer);
        } else {
            Function<String, Object> fieldValueComputer = (columnName) -> {
                CompiledSQLExpression e = expressionsByColumnName.get(columnName);
                if (e == null) {
                    return null;
                } else {
                    herddb.model.Column column = table.getColumn(columnName);
                    if (column == null) {
                        throw new StatementExecutionException("unknown column " + columnName + " in table " + table.name);
                    }
                    try {
                        return RecordSerializer.convert(column.type, e.evaluate(DataAccessor.NULL, context));
                    } catch (StatementExecutionException err) {
                        throw new StatementExecutionException("error on column " + column.name + " (" + ColumnTypes.typeToString(column.type) + "):" + err.getMessage(), err);
                    }
                }
            };
            return RecordSerializer.buildRecord(0, table, fieldValueComputer);
        }
    } catch (IllegalArgumentException err) {
        throw new StatementExecutionException(err);
    }
}
Also used : DataAccessor(herddb.utils.DataAccessor) Record(herddb.model.Record) RecordFunction(herddb.model.RecordFunction) StatementExecutionException(herddb.model.StatementExecutionException) TableContext(herddb.model.TableContext) Table(herddb.model.Table) HashMap(java.util.HashMap) Function(java.util.function.Function) RecordSerializer(herddb.codec.RecordSerializer) ColumnTypes(herddb.model.ColumnTypes) List(java.util.List) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) Map(java.util.Map) StatementEvaluationContext(herddb.model.StatementEvaluationContext) DataAccessor(herddb.utils.DataAccessor) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) StatementExecutionException(herddb.model.StatementExecutionException)

Example 73 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class LimitOp method execute.

@Override
public StatementExecutionResult execute(TableSpaceManager tableSpaceManager, TransactionContext transactionContext, StatementEvaluationContext context, boolean lockRequired, boolean forWrite) throws StatementExecutionException {
    try {
        // TODO merge projection + scan + sort + limit
        StatementExecutionResult input = this.input.execute(tableSpaceManager, transactionContext, context, lockRequired, forWrite);
        ScanResult downstreamScanResult = (ScanResult) input;
        final DataScanner inputScanner = downstreamScanResult.dataScanner;
        int offset = computeOffset(context);
        int maxrows = computeMaxRows(context);
        if (maxrows <= 0 && offset == 0) {
            return downstreamScanResult;
        } else {
            LimitedDataScanner limited = new LimitedDataScanner(inputScanner, maxrows, offset, context);
            return new ScanResult(downstreamScanResult.transactionId, limited);
        }
    } catch (DataScannerException ex) {
        throw new StatementExecutionException(ex);
    }
}
Also used : ScanResult(herddb.model.ScanResult) DataScanner(herddb.model.DataScanner) LimitedDataScanner(herddb.model.LimitedDataScanner) StatementExecutionResult(herddb.model.StatementExecutionResult) LimitedDataScanner(herddb.model.LimitedDataScanner) StatementExecutionException(herddb.model.StatementExecutionException) DataScannerException(herddb.model.DataScannerException)

Example 74 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class SemiJoinOp method execute.

@Override
public StatementExecutionResult execute(TableSpaceManager tableSpaceManager, TransactionContext transactionContext, StatementEvaluationContext context, boolean lockRequired, boolean forWrite) throws StatementExecutionException {
    ScanResult resLeft = (ScanResult) left.execute(tableSpaceManager, transactionContext, context, lockRequired, forWrite);
    transactionContext = new TransactionContext(resLeft.transactionId);
    ScanResult resRight = (ScanResult) right.execute(tableSpaceManager, transactionContext, context, lockRequired, forWrite);
    DataScanner leftScanner = resLeft.dataScanner;
    DataScanner rightScanner = resRight.dataScanner;
    if (!leftScanner.isRewindSupported()) {
        try {
            MaterializedRecordSet recordSet = tableSpaceManager.getDbmanager().getRecordSetFactory().createRecordSet(leftScanner.getFieldNames(), leftScanner.getSchema());
            leftScanner.forEach(d -> {
                recordSet.add(d);
            });
            recordSet.writeFinished();
            SimpleDataScanner materialized = new SimpleDataScanner(leftScanner.getTransaction(), recordSet);
            leftScanner.close();
            leftScanner = materialized;
        } catch (DataScannerException err) {
            throw new StatementExecutionException(err);
        }
    }
    if (!rightScanner.isRewindSupported()) {
        try {
            MaterializedRecordSet recordSet = tableSpaceManager.getDbmanager().getRecordSetFactory().createRecordSet(rightScanner.getFieldNames(), rightScanner.getSchema());
            rightScanner.forEach(d -> {
                recordSet.add(d);
            });
            recordSet.writeFinished();
            SimpleDataScanner materialized = new SimpleDataScanner(rightScanner.getTransaction(), recordSet);
            rightScanner.close();
            rightScanner = materialized;
        } catch (DataScannerException err) {
            throw new StatementExecutionException(err);
        }
    }
    final long resTransactionId = resRight.transactionId;
    Enumerable<DataAccessor> result = EnumerableDefaults.semiJoin(leftScanner.createRewindOnCloseEnumerable(), rightScanner.createRewindOnCloseEnumerable(), JoinKey.keyExtractor(leftKeys), JoinKey.keyExtractor(rightKeys));
    EnumerableDataScanner joinedScanner = new EnumerableDataScanner(rightScanner.getTransaction(), fieldNames, columns, result, leftScanner, rightScanner);
    return new ScanResult(resTransactionId, joinedScanner);
}
Also used : ScanResult(herddb.model.ScanResult) SimpleDataScanner(herddb.core.SimpleDataScanner) DataScanner(herddb.model.DataScanner) MaterializedRecordSet(herddb.core.MaterializedRecordSet) TransactionContext(herddb.model.TransactionContext) DataAccessor(herddb.utils.DataAccessor) SimpleDataScanner(herddb.core.SimpleDataScanner) StatementExecutionException(herddb.model.StatementExecutionException) DataScannerException(herddb.model.DataScannerException)

Example 75 with StatementExecutionException

use of herddb.model.StatementExecutionException in project herddb by diennea.

the class DropTableSQLTest method dropTableWithTransaction.

@Test
public void dropTableWithTransaction() throws Exception {
    String nodeId = "localhost";
    try (DBManager manager = new DBManager("localhost", new MemoryMetadataStorageManager(), new MemoryDataStorageManager(), new MemoryCommitLogManager(), null, null)) {
        manager.start();
        CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId), nodeId, 1, 0, 0);
        manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        manager.waitForTablespace("tblspace1", 10000);
        long tx = ((TransactionResult) execute(manager, "EXECUTE begintransaction 'tblspace1'", Collections.emptyList())).getTransactionId();
        execute(manager, "CREATE TABLE tblspace1.tsql (k1 string primary key,n1 int,s1 string)", Collections.emptyList(), new TransactionContext(tx));
        execute(manager, "INSERT INTO tblspace1.tsql (k1) values('a')", Collections.emptyList(), new TransactionContext(tx));
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.tsql ", Collections.emptyList())) {
            fail();
        } catch (TableDoesNotExistException ok) {
        }
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.systables where table_name='tsql'", Collections.emptyList())) {
            List<DataAccessor> all = scan.consume();
            assertEquals(0, all.size());
        }
        execute(manager, "EXECUTE committransaction 'tblspace1'," + tx, Collections.emptyList());
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.tsql ", Collections.emptyList())) {
            List<DataAccessor> all = scan.consume();
            assertEquals(1, all.size());
        }
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.systables where table_name='tsql'", Collections.emptyList())) {
            List<DataAccessor> all = scan.consume();
            assertEquals(1, all.size());
        }
        long tx2 = ((TransactionResult) execute(manager, "EXECUTE begintransaction 'tblspace1'", Collections.emptyList())).getTransactionId();
        // name is not case sensitive
        execute(manager, "DROP TABLE tblspace1.tSQL", Collections.emptyList(), new TransactionContext(tx2));
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.tsql ", Collections.emptyList())) {
            List<DataAccessor> all = scan.consume();
            assertEquals(1, all.size());
        }
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.systables where table_name='tsql'", Collections.emptyList())) {
            List<DataAccessor> all = scan.consume();
            assertEquals(1, all.size());
        }
        execute(manager, "EXECUTE committransaction 'tblspace1'," + tx2, Collections.emptyList());
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.systables where table_name='tsql'", Collections.emptyList())) {
            List<DataAccessor> all = scan.consume();
            assertEquals(0, all.size());
        }
        try (DataScanner scan = scan(manager, "SELECT * FROM tblspace1.tsql ", Collections.emptyList())) {
            fail();
        } catch (TableDoesNotExistException ok) {
            assertTrue(manager.getPlanner() instanceof JSQLParserPlanner);
        } catch (StatementExecutionException ok) {
            assertEquals("From line 1, column 15 to line 1, column 28: Object 'TSQL' not found within 'tblspace1'", ok.getMessage());
            assertTrue(manager.getPlanner() instanceof CalcitePlanner);
        }
    }
}
Also used : JSQLParserPlanner(herddb.sql.JSQLParserPlanner) TransactionResult(herddb.model.TransactionResult) MemoryDataStorageManager(herddb.mem.MemoryDataStorageManager) DataAccessor(herddb.utils.DataAccessor) StatementExecutionException(herddb.model.StatementExecutionException) TableDoesNotExistException(herddb.model.TableDoesNotExistException) CreateTableSpaceStatement(herddb.model.commands.CreateTableSpaceStatement) DataScanner(herddb.model.DataScanner) TransactionContext(herddb.model.TransactionContext) MemoryCommitLogManager(herddb.mem.MemoryCommitLogManager) CalcitePlanner(herddb.sql.CalcitePlanner) MemoryMetadataStorageManager(herddb.mem.MemoryMetadataStorageManager) Test(org.junit.Test)

Aggregations

StatementExecutionException (herddb.model.StatementExecutionException)163 Table (herddb.model.Table)69 ArrayList (java.util.ArrayList)57 DataScanner (herddb.model.DataScanner)49 TransactionContext (herddb.model.TransactionContext)47 DataStorageManagerException (herddb.storage.DataStorageManagerException)40 List (java.util.List)40 DataScannerException (herddb.model.DataScannerException)39 StatementExecutionResult (herddb.model.StatementExecutionResult)39 Column (herddb.model.Column)37 DataAccessor (herddb.utils.DataAccessor)36 LogNotAvailableException (herddb.log.LogNotAvailableException)35 LogEntry (herddb.log.LogEntry)34 Test (org.junit.Test)34 InsertStatement (herddb.model.commands.InsertStatement)32 Bytes (herddb.utils.Bytes)32 CommitLogResult (herddb.log.CommitLogResult)31 Record (herddb.model.Record)31 DMLStatementExecutionResult (herddb.model.DMLStatementExecutionResult)30 Map (java.util.Map)30