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);
}
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);
}
}
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);
}
}
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);
}
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);
}
}
}
Aggregations