use of herddb.model.StatementExecutionException in project herddb by diennea.
the class TableManager method checkForeignKeyConstraintsAsChildTable.
private void checkForeignKeyConstraintsAsChildTable(ForeignKeyDef fk, DataAccessor values, StatementEvaluationContext context, Transaction transaction) throws StatementExecutionException {
// We are creating a SQL query and then using DBManager
// using an SQL query will let us leverage the SQL Planner
// and use the best index to perform the execution
// the SQL Planner will cache the plan, and the plan will also be
// invalidated consistently during DML operations.
String query = childForeignKeyQueries.computeIfAbsent(fk.name, (l -> {
Table parentTable = tableSpaceManager.getTableManagerByUUID(fk.parentTableId).getTable();
// with '*' we are not going to perform projections or copies
StringBuilder q = new StringBuilder("SELECT * FROM ");
q.append(delimit(parentTable.tablespace));
q.append(".");
q.append(delimit(parentTable.name));
q.append(" WHERE ");
for (int i = 0; i < fk.parentTableColumns.length; i++) {
if (i > 0) {
q.append(" AND ");
}
q.append(delimit(fk.parentTableColumns[i]));
q.append("=?");
}
return q.toString();
}));
final List<Object> valuesToMatch = new ArrayList<>(fk.columns.length);
boolean allNulls = true;
for (int i = 0; i < fk.columns.length; i++) {
Object value = values.get(fk.columns[i]);
allNulls = allNulls && value == null;
valuesToMatch.add(value);
}
if (allNulls) {
// all of the values are null, so no check on the parent table
return;
}
TransactionContext tx = transaction != null ? new TransactionContext(transaction.transactionId) : TransactionContext.NO_TRANSACTION;
boolean fkOk;
try (DataScanner scan = tableSpaceManager.getDbmanager().executeSimpleQuery(tableSpaceManager.getTableSpaceName(), query, valuesToMatch, // only one record
1, // keep read locks in TransactionContext
true, tx, null)) {
List<DataAccessor> resultSet = scan.consume();
fkOk = !resultSet.isEmpty();
} catch (DataScannerException err) {
throw new StatementExecutionException(err);
}
if (!fkOk) {
throw new ForeignKeyViolationException(fk.name, "foreignKey " + table.name + "." + fk.name + " violated");
}
}
use of herddb.model.StatementExecutionException in project herddb by diennea.
the class SysnodesTableManager method buildVirtualRecordList.
@Override
protected Iterable<Record> buildVirtualRecordList(Transaction transaction) throws StatementExecutionException {
try {
Collection<NodeMetadata> nodes = tableSpaceManager.getMetadataStorageManager().listNodes();
List<Record> result = new ArrayList<>();
for (NodeMetadata t : nodes) {
result.add(RecordSerializer.makeRecord(table, "nodeid", t.nodeId, "address", t.host + ":" + t.port, "ssl", t.ssl ? 1 : 0));
}
return result;
} catch (MetadataStorageManagerException error) {
throw new StatementExecutionException(error);
}
}
use of herddb.model.StatementExecutionException in project herddb by diennea.
the class SystablespacesTableManager method buildVirtualRecordList.
@Override
protected Iterable<Record> buildVirtualRecordList(Transaction transaction) throws StatementExecutionException {
try {
Collection<String> names = tableSpaceManager.getMetadataStorageManager().listTableSpaces();
List<Record> result = new ArrayList<>();
for (String name : names) {
TableSpace t = tableSpaceManager.getMetadataStorageManager().describeTableSpace(name);
if (t != null) {
result.add(RecordSerializer.makeRecord(table, "tablespace_name", t.name, "uuid", t.uuid, "leader", t.leaderId, "expectedreplicacount", t.expectedReplicaCount, "maxleaderinactivitytime", t.maxLeaderInactivityTime, "replica", t.replicas.stream().collect(Collectors.joining(","))));
}
}
return result;
} catch (MetadataStorageManagerException error) {
throw new StatementExecutionException(error);
}
}
use of herddb.model.StatementExecutionException in project herddb by diennea.
the class AbstractSystemTableManager method scan.
@Override
public DataScanner scan(ScanStatement statement, StatementEvaluationContext context, Transaction transaction, boolean lockRequired, boolean forWrite) throws StatementExecutionException {
Predicate predicate = statement.getPredicate();
MaterializedRecordSet recordSet = tableSpaceManager.getDbmanager().getRecordSetFactory().createRecordSet(table.columnNames, table.columns);
Iterable<Record> data = buildVirtualRecordList(transaction);
StreamSupport.stream(data.spliterator(), false).filter(record -> {
return (predicate == null || predicate.evaluate(record, context));
}).sorted(// enforce sort by PK
sortByPk).map(r -> r.getDataAccessor(table)).forEach(recordSet::add);
recordSet.writeFinished();
recordSet.sort(statement.getComparator());
recordSet.applyLimits(statement.getLimits(), context);
recordSet.applyProjection(statement.getProjection(), context);
return new SimpleDataScanner(transaction, recordSet);
}
use of herddb.model.StatementExecutionException in project herddb by diennea.
the class ConcurrentMapKeyToPageIndex method scanner.
@Override
public Stream<Map.Entry<Bytes, Long>> scanner(IndexOperation operation, StatementEvaluationContext context, TableContext tableContext, herddb.core.AbstractIndexManager index) throws DataStorageManagerException {
if (operation instanceof PrimaryIndexSeek) {
PrimaryIndexSeek seek = (PrimaryIndexSeek) operation;
byte[] seekValue;
try {
seekValue = seek.value.computeNewValue(null, context, tableContext);
} catch (InvalidNullValueForKeyException nullKey) {
seekValue = null;
}
if (seekValue == null) {
return Stream.empty();
}
Bytes key = Bytes.from_array(seekValue);
Long pageId = map.get(key);
if (pageId == null) {
return Stream.empty();
}
return Stream.of(new AbstractMap.SimpleImmutableEntry<>(key, pageId));
}
// every predicate (WHEREs...) will always be evaluated anyway on every record, in order to guarantee correctness
if (index != null) {
return index.recordSetScanner(operation, context, tableContext, this);
}
if (operation == null) {
Stream<Map.Entry<Bytes, Long>> baseStream = map.entrySet().stream();
return baseStream;
} else if (operation instanceof PrimaryIndexPrefixScan) {
PrimaryIndexPrefixScan scan = (PrimaryIndexPrefixScan) operation;
byte[] prefix;
try {
prefix = scan.value.computeNewValue(null, context, tableContext);
} catch (InvalidNullValueForKeyException err) {
return Stream.empty();
} catch (StatementExecutionException err) {
throw new RuntimeException(err);
}
Predicate<Map.Entry<Bytes, Long>> predicate = (Map.Entry<Bytes, Long> t) -> {
Bytes fullrecordKey = t.getKey();
return fullrecordKey.startsWith(prefix.length, prefix);
};
Stream<Map.Entry<Bytes, Long>> baseStream = map.entrySet().stream();
return baseStream.filter(predicate);
} else if (operation instanceof PrimaryIndexRangeScan) {
Bytes refminvalue;
PrimaryIndexRangeScan sis = (PrimaryIndexRangeScan) operation;
SQLRecordKeyFunction minKey = sis.minValue;
if (minKey != null) {
refminvalue = Bytes.from_nullable_array(minKey.computeNewValue(null, context, tableContext));
} else {
refminvalue = null;
}
Bytes refmaxvalue;
SQLRecordKeyFunction maxKey = sis.maxValue;
if (maxKey != null) {
refmaxvalue = Bytes.from_nullable_array(maxKey.computeNewValue(null, context, tableContext));
} else {
refmaxvalue = null;
}
Predicate<Map.Entry<Bytes, Long>> predicate;
if (refminvalue != null && refmaxvalue == null) {
predicate = (Map.Entry<Bytes, Long> entry) -> {
Bytes datum = entry.getKey();
return datum.compareTo(refminvalue) >= 0;
};
} else if (refminvalue == null && refmaxvalue != null) {
predicate = (Map.Entry<Bytes, Long> entry) -> {
Bytes datum = entry.getKey();
return datum.compareTo(refmaxvalue) <= 0;
};
} else if (refminvalue != null && refmaxvalue != null) {
predicate = (Map.Entry<Bytes, Long> entry) -> {
Bytes datum = entry.getKey();
return datum.compareTo(refmaxvalue) <= 0 && datum.compareTo(refminvalue) >= 0;
};
} else {
predicate = (Map.Entry<Bytes, Long> entry) -> {
return true;
};
}
Stream<Map.Entry<Bytes, Long>> baseStream = map.entrySet().stream();
return baseStream.filter(predicate);
} else {
throw new DataStorageManagerException("operation " + operation + " not implemented on " + this.getClass());
}
}
Aggregations