Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions database/src/main/java/io/hstore/db/Reader.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import io.hstore.db.property.PropertyBag;
import io.hstore.db.property.PropertyIndex;
import io.hstore.db.property.PropertySlots;
import io.hstore.db.retrieve.Signature;
import io.hstore.db.retrieve.Signatures;
import io.hstore.db.schema.Schema;
import io.hstore.db.schema.TypeDef;
import io.hstore.db.security.Access;
Expand Down Expand Up @@ -40,6 +42,8 @@
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
import java.util.stream.LongStream;
Expand All @@ -52,8 +56,10 @@ public sealed class Reader permits Writer {
private final Principal principal;

private Boolean onlyDefaultTenant;
private final Map<Integer, Optional<Access.Privilege>> grantedTypes = new HashMap<>();
private long grantsGeneration = -1;
private record Grants(long generation, Map<Integer, Optional<Access.Privilege>> types) {
}

private final AtomicReference<Grants> grants = new AtomicReference<>(new Grants(-1, new ConcurrentHashMap<>()));

Reader(HypergraphDatabase database, View view, Principal principal) {
this.database = database;
Expand Down Expand Up @@ -99,11 +105,12 @@ public boolean writable(int type) {

private Optional<Access.Privilege> privilege(int type) {
long current = database.engine().transactions().current().id();
if (current != grantsGeneration) {
grantedTypes.clear();
grantsGeneration = current;
Grants known = grants.get();
if (known.generation() != current) {
Grants fresh = new Grants(current, new ConcurrentHashMap<>());
known = grants.compareAndSet(known, fresh) ? fresh : grants.get();
}
return grantedTypes.computeIfAbsent(type, found -> {
return known.types().computeIfAbsent(type, found -> {
try (Snapshot latest = database.engine().snapshot()) {
return Access.onType(latest, principal.user(), found);
}
Expand Down Expand Up @@ -173,6 +180,26 @@ public boolean edgeAtom(long atom) {
return view.atom(atom).filter(this::admits).map(record -> record instanceof AtomRecord.EdgeRecord).orElse(false);
}

public long[] signatureEdges(Signature signature) {
return Signatures.edges(view, tenant(), signature).toArray();
}

public long signatureCount(Signature signature) {
return Signatures.count(view, tenant(), signature);
}

public boolean signatureCollides(Signature signature) {
return Signatures.collides(view, tenant(), signature);
}

public Optional<Signature> signatureOf(long edge) {
return visible(edge) ? Signatures.of(view, edge) : Optional.empty();
}

public boolean concurrentReads() {
return view instanceof Snapshot;
}

public LongStream validityEndpoints(int edgeType, int side, long lowExclusive, long highInclusive) {
return ValidityIndex.edges(view, tenant(), edgeType, side, lowExclusive, highInclusive);
}
Expand Down
16 changes: 16 additions & 0 deletions database/src/main/java/io/hstore/db/query/Ast.java
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,15 @@ public record Match(boolean edges, String variable, Optional<String> type, Optio
List<Projection> projections, Optional<Expr> orderBy, boolean descending, OptionalLong limit) {
}

public record StructuralVertex(String name, Optional<String> type) {
}

public record StructuralEdge(String name, String type, List<StructuralVertex> vertices) {
}

public record StructuralAnchor(String vertex, Ref atom) {
}

public sealed interface Instant {
record Generation(long id) implements Instant {
}
Expand Down Expand Up @@ -293,6 +302,13 @@ record ResolveSignals(List<Ref> edges, long from, long to) implements Statement
record Query(Match match) implements Statement {
}

record StructuralMatch(List<StructuralEdge> edges, List<StructuralAnchor> anchors, Optional<String> mode, boolean count,
boolean bindings, OptionalLong limit) implements Statement {
}

record ExplainStructural(StructuralMatch match) implements Statement {
}

record Explain(Match match) implements Statement {
}

Expand Down
82 changes: 82 additions & 0 deletions database/src/main/java/io/hstore/db/query/Executor.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import io.hstore.db.query.Ast.MemberClause;
import io.hstore.db.query.Ast.Statement;
import io.hstore.db.query.QueryResult.Cell;
import io.hstore.db.retrieve.HyperMatch;
import io.hstore.db.retrieve.HyperQuery;
import io.hstore.db.retrieve.RankQuery;
import io.hstore.db.retrieve.Ranking;
import io.hstore.db.retrieve.RoleTimeScorer;
Expand Down Expand Up @@ -60,8 +62,10 @@

import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -317,6 +321,9 @@ QueryResult run(Statement statement) {
case Statement.SetAlgebra algebra -> algebra.into().isPresent() ? write(writer -> setAlgebra(writer, algebra)) : read(reader -> setAlgebra(reader, algebra));
case Statement.Rank rank -> read(reader -> rank(reader, rank));
case Statement.Transitions transitions -> read(reader -> transitions(reader, transitions));
case Statement.StructuralMatch match -> read(reader -> structural(reader, match));
case Statement.ExplainStructural(Statement.StructuralMatch match) -> read(reader ->
QueryResult.message(hyperMatch(reader, match).explain(hyperQuery(reader, match))));
case Statement.Expand(Ast.Ref atom, int depth, OptionalLong limit) -> read(reader -> table(List.of("path", "atom", "status"),
Hora.on(reader).expand(session.resolve(reader, atom), depth(depth), budget(limit).withDepth(depth(depth)))
.map(expansion -> List.<Cell>of(new Cell.Items(expansion.path().stream().map(id -> (Cell) new Cell.AtomCell(id, "")).toList()),
Expand Down Expand Up @@ -607,6 +614,81 @@ private QueryResult query(Reader reader, Ast.Match match) {
rows.size(), trace.pagesRead(), trace.cacheHits(), System.nanoTime() - started));
}

private HyperMatch hyperMatch(Reader reader, Statement.StructuralMatch statement) {
return HyperMatch.on(reader).withThreads(Math.max(1, Runtime.getRuntime().availableProcessors()))
.withMode(statement.mode().map(HyperMatch.Mode::valueOf).orElse(HyperMatch.Mode.AUTO));
}

private HyperQuery hyperQuery(Reader reader, Statement.StructuralMatch statement) {
Map<String, String> types = new LinkedHashMap<>();
for (Ast.StructuralEdge edge : statement.edges()) {
for (Ast.StructuralVertex vertex : edge.vertices()) {
types.putIfAbsent(vertex.name(), null);
vertex.type().ifPresent(type -> {
String known = types.get(vertex.name());
if (known != null && !known.equals(type)) {
throw HStoreException.invalid("vertex " + vertex.name() + " is declared as " + known + " and " + type);
}
types.put(vertex.name(), type);
});
}
}
HyperQuery.Builder builder = HyperQuery.builder();
types.forEach((name, type) -> {
if (type == null) {
throw HStoreException.invalid("vertex " + name + " needs a type the first time it is named, as " + name + ":Type");
}
builder.vertex(name, reader.requireReadableType(type).id());
});
for (Ast.StructuralEdge edge : statement.edges()) {
TypeDef type = reader.requireReadableType(edge.type());
if (!type.kind().isEdge()) {
throw HStoreException.invalid(edge.type() + " is not a hyperedge type");
}
builder.edge(edge.name(), type.id(), edge.vertices().stream().map(Ast.StructuralVertex::name).toArray(String[]::new));
}
for (Ast.StructuralAnchor anchor : statement.anchors()) {
builder.anchor(anchor.vertex(), reader.require(session.resolve(reader, anchor.atom())).id());
}
return builder.build();
}

private QueryResult structural(Reader reader, Statement.StructuralMatch statement) {
long started = System.nanoTime();
HyperQuery query = hyperQuery(reader, statement);
HyperMatch match = hyperMatch(reader, statement);
Budget.Meter meter = Budget.DEFAULT.start();
HyperMatch.Plan plan = match.prepare(query, meter);
if (statement.count()) {
return QueryResult.table(List.of("count"), List.of(List.of(QueryResult.number(match.count(plan, meter)))));
}
long limit = statement.limit().orElse(Long.MAX_VALUE);
List<long[]> tuples = match.tuples(plan, meter, limit);
List<String> columns = new ArrayList<>(query.edges().stream().map(HyperQuery.Edge::name).toList());
if (statement.bindings()) {
columns.addAll(query.vertices().stream().map(HyperQuery.Vertex::name).toList());
}
List<List<Cell>> rows = new ArrayList<>();
for (int t = 0; t < tuples.size() && rows.size() < limit; t++) {
long[] tuple = tuples.get(t);
List<Cell> edges = Arrays.stream(tuple).mapToObj(edge -> atomCell(reader, edge)).toList();
if (!statement.bindings()) {
rows.add(edges);
continue;
}
Iterator<long[]> bindings = match.bindings(query, tuple);
while (bindings.hasNext() && rows.size() < limit) {
meter.consume(1);
List<Cell> row = new ArrayList<>(edges);
Arrays.stream(bindings.next()).forEach(vertex -> row.add(atomCell(reader, vertex)));
rows.add(row);
}
}
Optional<IoTrace> trace = IoTrace.current();
return QueryResult.table(columns, rows).withTrace(new QueryResult.Trace(0, reader.generation(), match.describe(plan), Double.NaN, rows.size(),
trace.map(IoTrace::pagesRead).orElse(0L), trace.map(IoTrace::cacheHits).orElse(0L), System.nanoTime() - started));
}

private QueryResult transitions(Reader reader, Statement.Transitions statement) {
OptionalInt type = statement.type().map(name -> {
TypeDef found = reader.requireReadableType(name);
Expand Down
47 changes: 47 additions & 0 deletions database/src/main/java/io/hstore/db/query/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,15 @@ private Statement statement() {
return new Statement.Query(match());
}
if (accept("EXPLAIN")) {
if (accept("HYPERMATCH")) {
return new Statement.ExplainStructural(structuralMatch());
}
expect("MATCH");
return new Statement.Explain(match());
}
if (accept("HYPERMATCH")) {
return structuralMatch();
}
if (accept("MEMBERS")) {
expect("OF");
Ref edge = ref();
Expand Down Expand Up @@ -1248,6 +1254,47 @@ private String variable() {
return token.text();
}

private Statement.StructuralMatch structuralMatch() {
List<Ast.StructuralEdge> edges = new ArrayList<>();
do {
String name = identifier();
expectSymbol(":");
String type = identifier();
expectSymbol("(");
List<Ast.StructuralVertex> vertices = new ArrayList<>();
do {
String vertex = identifier();
vertices.add(new Ast.StructuralVertex(vertex, acceptSymbol(":") ? Optional.of(identifier()) : Optional.empty()));
} while (acceptSymbol(","));
expectSymbol(")");
edges.add(new Ast.StructuralEdge(name, type, List.copyOf(vertices)));
if (edges.size() > 64) {
throw HStoreException.invalid("a structural match has at most 64 hyperedges");
}
} while (acceptSymbol(","));
List<Ast.StructuralAnchor> anchors = new ArrayList<>();
if (accept("WHERE")) {
do {
String vertex = identifier();
expectSymbol("=");
anchors.add(new Ast.StructuralAnchor(vertex, ref()));
} while (accept("AND"));
}
Optional<String> mode = Optional.empty();
if (accept("MODE")) {
String found = identifier().toUpperCase(java.util.Locale.ROOT);
if (!List.of("AUTO", "HGMATCH", "MACH").contains(found)) {
throw HStoreException.invalid("MODE must be AUTO, HGMATCH or MACH");
}
mode = Optional.of(found);
}
if (accept("COUNT")) {
return new Statement.StructuralMatch(List.copyOf(edges), List.copyOf(anchors), mode, true, false, OptionalLong.empty());
}
boolean bindings = accept("BINDINGS");
return new Statement.StructuralMatch(List.copyOf(edges), List.copyOf(anchors), mode, false, bindings, limit());
}

private Ast.Instant transitionInstant() {
return accept("GENERATION") ? new Ast.Instant.Generation(longValue()) : new Ast.Instant.Time(parseInstant(string()));
}
Expand Down
Loading
Loading