use of herddb.model.RecordFunction in project herddb by diennea.
the class TableManager method executeUpdate.
private StatementExecutionResult executeUpdate(UpdateStatement update, Transaction transaction, StatementEvaluationContext context) throws StatementExecutionException, DataStorageManagerException {
AtomicInteger updateCount = new AtomicInteger();
Holder<Bytes> lastKey = new Holder<>();
Holder<byte[]> lastValue = new Holder<>();
/*
an update can succeed only if the row is valid, the key is contains in the "keys" structure
the update will simply override the value of the row, assigning a null page to the row
the update can have a 'where' predicate which is to be evaluated against the decoded row, the update will be executed only if the predicate returns boolean 'true' value (CAS operation)
locks: the update uses a lock on the the key
*/
RecordFunction function = update.getFunction();
long transactionId = transaction != null ? transaction.transactionId : 0;
Predicate predicate = update.getPredicate();
ScanStatement scan = new ScanStatement(table.tablespace, table, predicate);
accessTableData(scan, context, new ScanResultOperation() {
@Override
public void accept(Record actual) throws StatementExecutionException, LogNotAvailableException, DataStorageManagerException {
byte[] newValue = function.computeNewValue(actual, context, tableContext);
final long size = DataPage.estimateEntrySize(actual.key, newValue);
if (size > maxLogicalPageSize) {
throw new RecordTooBigException("New version of record " + actual.key + " is to big to be update: new size " + size + ", actual size " + DataPage.estimateEntrySize(actual) + ", max size " + maxLogicalPageSize);
}
LogEntry entry = LogEntryFactory.update(table, actual.key.data, newValue, transaction);
CommitLogResult pos = log.log(entry, entry.transactionId <= 0);
apply(pos, entry, false);
lastKey.value = actual.key;
lastValue.value = newValue;
updateCount.incrementAndGet();
}
}, transaction, true, true);
return new DMLStatementExecutionResult(transactionId, updateCount.get(), lastKey.value, update.isReturnValues() ? (lastValue.value != null ? Bytes.from_array(lastValue.value) : null) : null);
}
use of herddb.model.RecordFunction in project herddb by diennea.
the class SQLPlanner method buildUpdateStatement.
private ExecutionPlan buildUpdateStatement(String defaultTableSpace, Update s, boolean returnValues) throws StatementExecutionException {
if (s.getTables().size() != 1) {
throw new StatementExecutionException("unsupported multi-table update " + s);
}
net.sf.jsqlparser.schema.Table fromTable = s.getTables().get(0);
String tableSpace = fromTable.getSchemaName();
String tableName = fromTable.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();
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);
}
if (table.isPrimaryKeyColumn(c.getColumnName())) {
throw new StatementExecutionException("updates of fields on the PK (" + Arrays.toString(table.primaryKey) + ") are not supported. Please perform a DELETE and than an INSERT");
}
}
List<CompiledSQLExpression> compiledSQLExpressions = new ArrayList<>();
for (Expression e : s.getExpressions()) {
compiledSQLExpressions.add(SQLExpressionCompiler.compileExpression(null, e));
}
RecordFunction function = new SQLRecordFunction(table, s.getColumns(), compiledSQLExpressions);
// Perform a scan and then update each row
SQLRecordPredicate where = s.getWhere() != null ? new SQLRecordPredicate(table, table.name, s.getWhere()) : null;
if (where != null) {
Expression expressionWhere = s.getWhere();
discoverIndexOperations(expressionWhere, table, table.name, where, tableSpaceManager);
}
DMLStatement st = new UpdateStatement(tableSpace, tableName, null, function, where).setReturnValues(returnValues);
return ExecutionPlan.simple(st);
}
use of herddb.model.RecordFunction in project herddb by diennea.
the class InsertOp method executeAsync.
@Override
public CompletableFuture<StatementExecutionResult> executeAsync(TableSpaceManager tableSpaceManager, TransactionContext transactionContext, StatementEvaluationContext context, boolean lockRequired, boolean forWrite) {
StatementExecutionResult input = this.input.execute(tableSpaceManager, transactionContext, context, true, true);
ScanResult downstreamScanResult = (ScanResult) input;
final Table table = tableSpaceManager.getTableManager(tableName).getTable();
long transactionId = transactionContext.transactionId;
List<DMLStatement> statements = new ArrayList<>();
try (DataScanner inputScanner = downstreamScanResult.dataScanner) {
while (inputScanner.hasNext()) {
DataAccessor row = inputScanner.next();
long transactionIdFromScanner = inputScanner.getTransactionId();
if (transactionIdFromScanner > 0 && transactionIdFromScanner != transactionId) {
transactionId = transactionIdFromScanner;
transactionContext = new TransactionContext(transactionId);
}
int index = 0;
List<CompiledSQLExpression> keyValueExpression = new ArrayList<>();
List<String> keyExpressionToColumn = new ArrayList<>();
List<CompiledSQLExpression> valuesExpressions = new ArrayList<>();
List<String> valuesColumns = new ArrayList<>();
for (Column column : table.getColumns()) {
Object value = row.get(index++);
if (value != null) {
ConstantExpression exp = new ConstantExpression(value, column.type);
if (table.isPrimaryKeyColumn(column.name)) {
keyExpressionToColumn.add(column.name);
keyValueExpression.add(exp);
}
valuesColumns.add(column.name);
valuesExpressions.add(exp);
}
}
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(keyExpressionToColumn, keyValueExpression, table);
}
RecordFunction valuesfunction = new SQLRecordFunction(valuesColumns, table, valuesExpressions);
DMLStatement insertStatement = new InsertStatement(tableSpace, tableName, keyfunction, valuesfunction, upsert).setReturnValues(returnValues);
statements.add(insertStatement);
}
if (statements.isEmpty()) {
return CompletableFuture.completedFuture(new DMLStatementExecutionResult(transactionId, 0, null, null));
}
if (statements.size() == 1) {
return tableSpaceManager.executeStatementAsync(statements.get(0), context, transactionContext);
}
if (returnValues) {
return Futures.exception(new StatementExecutionException("cannot 'return values' on multi-values insert"));
}
CompletableFuture<StatementExecutionResult> finalResult = new CompletableFuture<>();
AtomicInteger updateCounts = new AtomicInteger();
AtomicReference<Bytes> lastKey = new AtomicReference<>();
AtomicReference<Bytes> lastNewValue = new AtomicReference<>();
class ComputeNext implements BiConsumer<StatementExecutionResult, Throwable> {
int current;
public ComputeNext(int current) {
this.current = current;
}
@Override
public void accept(StatementExecutionResult res, Throwable error) {
if (error != null) {
finalResult.completeExceptionally(error);
return;
}
DMLStatementExecutionResult dml = (DMLStatementExecutionResult) res;
updateCounts.addAndGet(dml.getUpdateCount());
if (returnValues) {
lastKey.set(dml.getKey());
lastNewValue.set(dml.getNewvalue());
}
long newTransactionId = res.transactionId;
if (current == statements.size()) {
DMLStatementExecutionResult finalDMLResult = new DMLStatementExecutionResult(newTransactionId, updateCounts.get(), lastKey.get(), lastNewValue.get());
finalResult.complete(finalDMLResult);
return;
}
DMLStatement nextStatement = statements.get(current);
TransactionContext transactionContext = new TransactionContext(newTransactionId);
CompletableFuture<StatementExecutionResult> nextPromise = tableSpaceManager.executeStatementAsync(nextStatement, context, transactionContext);
nextPromise.whenComplete(new ComputeNext(current + 1));
}
}
DMLStatement firstStatement = statements.get(0);
tableSpaceManager.executeStatementAsync(firstStatement, context, transactionContext).whenComplete(new ComputeNext(1));
return finalResult;
} catch (DataScannerException err) {
throw new StatementExecutionException(err);
}
}
use of herddb.model.RecordFunction in project herddb by diennea.
the class CalcitePlanner method planInsert.
private PlannerOp planInsert(EnumerableTableModify dml, boolean returnValues, boolean upsert) {
final String tableSpace = dml.getTable().getQualifiedName().get(0);
final String tableName = dml.getTable().getQualifiedName().get(1);
DMLStatement statement = null;
if (dml.getInput() instanceof EnumerableProject) {
// fastest path for insert into TABLE(s,b,c) values(?,?,?)
EnumerableProject project = (EnumerableProject) dml.getInput();
if (project.getInput() instanceof EnumerableValues) {
EnumerableValues values = (EnumerableValues) project.getInput();
if (values.getTuples().size() == 1) {
final TableImpl tableImpl = (TableImpl) dml.getTable().unwrap(org.apache.calcite.schema.Table.class);
Table table = tableImpl.tableManager.getTable();
int index = 0;
List<RexNode> projects = project.getProjects();
List<CompiledSQLExpression> keyValueExpression = new ArrayList<>();
List<String> keyExpressionToColumn = new ArrayList<>();
List<CompiledSQLExpression> valuesExpressions = new ArrayList<>();
List<String> valuesColumns = new ArrayList<>();
boolean invalid = false;
for (Column column : table.getColumns()) {
CompiledSQLExpression exp = SQLExpressionCompiler.compileExpression(projects.get(index));
if (exp instanceof ConstantExpression || exp instanceof JdbcParameterExpression || exp instanceof TypedJdbcParameterExpression) {
boolean isAlwaysNull = (exp instanceof ConstantExpression) && ((ConstantExpression) exp).isNull();
if (!isAlwaysNull) {
if (table.isPrimaryKeyColumn(column.name)) {
keyExpressionToColumn.add(column.name);
keyValueExpression.add(exp);
}
valuesColumns.add(column.name);
valuesExpressions.add(exp);
}
index++;
} else {
invalid = true;
break;
}
}
if (!invalid) {
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(keyExpressionToColumn, keyValueExpression, table);
}
RecordFunction valuesfunction = new SQLRecordFunction(valuesColumns, table, valuesExpressions);
statement = new InsertStatement(tableSpace, tableName, keyfunction, valuesfunction, upsert).setReturnValues(returnValues);
}
}
}
}
if (statement != null) {
return new SimpleInsertOp(statement);
}
PlannerOp input = convertRelNode(dml.getInput(), null, false, false);
try {
return new InsertOp(tableSpace, tableName, input, returnValues, upsert);
} catch (IllegalArgumentException err) {
throw new StatementExecutionException(err);
}
}
use of herddb.model.RecordFunction 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;
}
}
Aggregations