15#include "absl/status/status.h"
16#include "absl/status/statusor.h"
17#include "absl/strings/str_cat.h"
18#include "absl/strings/str_join.h"
24std::string SlotName(
const Plan& plan,
int slot) {
25 const std::string& variable = plan.slots[slot];
26 return variable.empty() ? absl::StrCat(
"_", slot) : variable;
30std::string Literal(
const Value& value) {
31 if (
const std::string*
text = std::get_if<std::string>(&value)) {
32 return absl::StrCat(
"'", *
text,
"'");
39std::optional<std::string> NameOf(
const NodePattern& node) {
40 for (
const Property& property : node.
properties) {
41 const std::string* name = std::get_if<std::string>(&property.value);
42 if (property.key ==
"name" && name !=
nullptr)
return *name;
52void AddFilters(
const Query& query,
const NodePattern& node,
int slot,
57 for (
const Property& property : node.
properties) {
64 if (node.variable.empty())
return;
65 for (
const Comparison& comparison : query.where) {
66 if (comparison.property.variable != node.variable)
continue;
68 comparison.property.key, comparison.op,
76int CostToFind(
const NodePattern& node) {
77 if (NameOf(node))
return 0;
78 if (!node.label.empty())
return 1;
86int AddFind(
const Query& query,
const NodePattern& node, Plan& plan) {
87 plan.slots.push_back(node.variable);
88 int slot =
static_cast<int>(plan.slots.size()) - 1;
89 if (std::optional<std::string> name = NameOf(node)) {
91 }
else if (!node.label.empty()) {
96 AddFilters(query, node, slot, plan.steps.back().kind, plan);
102std::string Types(
const Step& step) {
return absl::StrJoin(step.types,
"|"); }
121int AddExpands(
const Query& query,
const RelationshipPattern& relationship,
126 for (
int hop = 0; hop < relationship.hops; ++hop) {
127 bool last = hop == relationship.hops - 1;
128 plan.slots.push_back(last ? node.variable :
"");
129 int to =
static_cast<int>(plan.slots.size()) - 1;
134 .types = relationship.types});
144bool Compare(
const std::optional<Value>& property,
const std::string& op,
145 const Value& value) {
146 if (!property)
return false;
147 if (property->index() != value.index())
return op ==
"<>";
148 std::strong_ordering order = *property <=> value;
149 if (op ==
"=")
return order == 0;
150 if (op ==
"<>")
return order != 0;
151 if (op ==
"<")
return order < 0;
152 if (op ==
"<=")
return order <= 0;
153 if (op ==
">")
return order > 0;
159absl::StatusOr<Plan> AddReturns(
const Query& query, Plan plan) {
160 plan.distinct = query.distinct;
161 for (
const ReturnItem& item : query.returns) {
162 if (!query.path.empty() && item.variable == query.path) {
165 if (!item.key.empty()) {
166 return absl::InvalidArgumentError(
167 absl::StrCat(
"the path ", item.variable,
" has no properties"));
169 if (item.function ==
"cost" && query.shortest) {
170 return absl::InvalidArgumentError(
171 "a shortest path has no cost, as it counts hops");
173 plan.returns.push_back({.heading = item.function.empty()
175 : absl::StrCat(item.function,
"(",
178 .function = item.function});
181 auto found = std::find(plan.slots.begin(), plan.slots.end(), item.variable);
182 if (found == plan.slots.end()) {
183 return absl::InvalidArgumentError(
184 absl::StrCat(
"there's no variable called ", item.variable));
186 if (item.key.empty() || !item.function.empty()) {
187 return absl::InvalidArgumentError(
188 absl::StrCat(
"a node is returned by its properties, such as ",
189 item.variable,
".name"));
191 plan.returns.push_back(
192 {.heading = absl::StrCat(item.variable,
".", item.key),
193 .slot =
static_cast<int>(found - plan.slots.begin()),
203 if (
const int64_t* number = std::get_if<int64_t>(&value)) {
204 return absl::StrCat(*number);
206 return std::get<std::string>(value);
211 for (
size_t i = 0; i < query.
nodes.size(); ++i) {
212 const std::string& variable = query.
nodes[i].variable;
213 for (
size_t j = 0; j < i; ++j) {
214 if (!variable.empty() && query.
nodes[j].variable == variable) {
215 return absl::InvalidArgumentError(
216 absl::StrCat(
"the variable ", variable,
" is on two nodes"));
222 const std::string& variable = comparison.property.variable;
223 if (std::none_of(query.
nodes.begin(), query.
nodes.end(),
225 return node.variable == variable;
227 return absl::InvalidArgumentError(
228 absl::StrCat(
"there's no variable called ", variable));
233 if (relationship.hops ==
kAnyHops && query.
path.empty()) {
234 return absl::InvalidArgumentError(
235 "a relationship with any number of hops needs shortestPath");
239 if (!query.
path.empty()) {
242 return absl::InvalidArgumentError(
243 "a path needs two nodes, with a relationship of any number of hops "
244 "between them, such as (a)-[:KNOWS*]-(b)");
249 return absl::InvalidArgumentError(
250 "a path needs shortestPath, or WSHORTEST with a weight, not both");
254 int from = AddFind(query, query.
nodes[0], plan);
255 int to = AddFind(query, query.
nodes[1], plan);
256 plan.
steps.push_back({.kind = query.
shortest ? Step::Kind::kShortestPath
257 : Step::Kind::kCheapestPath,
261 .weight = relationship.
weight,
262 .types = relationship.
types});
263 return AddReturns(query, std::move(plan));
269 for (
size_t i = 1; i < query.
nodes.size(); ++i) {
270 if (CostToFind(query.
nodes[i]) < CostToFind(query.
nodes[first])) first = i;
272 AddFind(query, query.
nodes[first], plan);
277 for (
size_t i = first; i < query.
relationships.size(); ++i) {
283 for (
size_t i = first; i > 0; --i) {
286 query.
nodes[i - 1], slot, plan);
288 return AddReturns(query, std::move(plan));
293 std::vector<Row> rows = {{std::vector<NodeId>(plan.
slots.size()), {}}};
295 std::vector<Row> next;
296 for (
const Row& row : rows) {
298 case Step::Kind::kNodeIndexSeek:
299 if (std::optional<NodeId> node = graph.
Find(step.text)) {
301 next.back().nodes[step.to] = *node;
304 case Step::Kind::kAllNodesScan:
307 next.back().nodes[step.to] = node;
310 case Step::Kind::kNodeByLabelScan:
312 if (graph.
label(node) != step.text)
continue;
314 next.back().nodes[step.to] = node;
317 case Step::Kind::kExpand:
319 graph.
Hops(row.nodes[step.from], step.types, step.direction)) {
321 next.back().nodes[step.to] = hop.node;
324 case Step::Kind::kFilter:
325 if (Compare(graph.
FindProperty(row.nodes[step.from], step.text),
326 step.op, step.value)) {
330 case Step::Kind::kHasLabel:
331 if (graph.
label(row.nodes[step.from]) == step.text) {
335 case Step::Kind::kShortestPath:
336 case Step::Kind::kCheapestPath: {
337 NodeId from = row.nodes[step.from];
338 NodeId to = row.nodes[step.to];
340 step.kind == Step::Kind::kShortestPath
341 ?
ShortestPath(graph, from, to, step.types, step.direction)
342 :
CheapestPath(graph, from, to, step.types, step.direction,
346 next.back().path = *std::move(search.
path);
352 rows = std::move(next);
357 result.
columns.push_back(column.heading);
359 std::set<std::vector<std::optional<Value>>> seen;
360 for (
const Row& row : rows) {
361 std::vector<Cell> cells;
362 std::vector<std::optional<Value>> values;
364 if (column.slot >= 0) {
365 NodeId node = row.nodes[column.slot];
366 cells.push_back({.node = node,
369 }
else if (column.function ==
"length") {
370 int64_t length = row.path.relationships.size();
371 cells.push_back({row.path.nodes[0], length, row.path});
372 }
else if (column.function ==
"cost") {
373 cells.push_back({row.path.nodes[0], row.path.cost, row.path});
376 {row.path.nodes[0],
PathText(graph, row.path), row.path});
378 values.push_back(cells.back().value);
381 if (plan.
distinct && !seen.insert(std::move(values)).second)
continue;
382 result.
rows.push_back(std::move(cells));
388 absl::StatusOr<Query> query =
Parse(
text);
389 if (!query.ok())
return query.status();
390 if (query->explain) {
391 return absl::InvalidArgumentError(
392 "EXPLAIN asks for the plan, which PlanQuery and Explain give");
394 absl::StatusOr<Plan> plan =
PlanQuery(*query);
395 if (!plan.ok())
return plan.status();
396 return Run(*plan, graph);
403 case Step::Kind::kNodeIndexSeek:
404 absl::StrAppend(&
text,
"NodeIndexSeek (", SlotName(plan, step.to),
405 " {name: '", step.text,
"'})\n");
407 case Step::Kind::kAllNodesScan:
408 absl::StrAppend(&
text,
"AllNodesScan (", SlotName(plan, step.to),
411 case Step::Kind::kNodeByLabelScan:
412 absl::StrAppend(&
text,
"NodeByLabelScan (", SlotName(plan, step.to),
413 ":", step.text,
")\n");
415 case Step::Kind::kExpand:
416 absl::StrAppend(&
text,
"Expand (", SlotName(plan, step.from),
")",
417 Arrow(step.direction, Types(step)),
"(",
418 SlotName(plan, step.to),
")\n");
420 case Step::Kind::kFilter:
421 absl::StrAppend(&
text,
"Filter ", SlotName(plan, step.from),
".",
422 step.text,
" ", step.op,
" ", Literal(step.value),
425 case Step::Kind::kHasLabel:
426 absl::StrAppend(&
text,
"Filter ", SlotName(plan, step.from),
":",
429 case Step::Kind::kShortestPath:
431 absl::StrAppend(&
text,
"ShortestPath (", SlotName(plan, step.from),
")",
432 Arrow(step.direction, Types(step) +
"*"),
"(",
433 SlotName(plan, step.to),
")\n");
435 case Step::Kind::kCheapestPath:
437 &
text,
"CheapestPath (", SlotName(plan, step.from),
")",
438 Arrow(step.direction,
439 absl::StrCat(Types(step),
"* WSHORTEST(", step.weight,
")")),
440 "(", SlotName(plan, step.to),
")\n");
444 std::vector<std::string> headings;
445 headings.reserve(plan.
returns.size());
446 for (
const Column& column : plan.
returns) headings.push_back(column.heading);
447 absl::StrAppend(&
text, plan.
distinct ?
"Return DISTINCT " :
"Return ",
448 absl::StrJoin(headings,
", "),
"\n");
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
size_t node_count() const
std::optional< Value > FindProperty(NodeId node, std::string_view key) const
Returns a node's property, if it has one. Its name is a property too.
std::optional< NodeId > Find(std::string_view name) const
Returns the node with this name, if the graph has one.
std::string label(NodeId node) const
std::vector< Hop > Hops(NodeId node, const std::vector< std::string > &types, Direction direction) const
Returns the hops from node along relationships of any of types: those that start at it,...
std::vector< Property > properties
std::string PathText(const Graph &graph, const Path &path)
A path as Cypher writes it, with the nodes' names, and each relationship's arrow pointing the way it ...
absl::StatusOr< Plan > PlanQuery(const Query &query)
Plans a query, starting from the node of its pattern that's cheapest to find, or for a shortest path,...
Result Run(const Plan &plan, const Graph &graph)
Runs a plan on a graph, a step at a time, each on all of the rows at once.
std::variant< int64_t, std::string > Value
A property's value, as the graph hands it out: a whole number or a string.
absl::StatusOr< Result > Execute(const Graph &graph, std::string_view text)
Parses, plans and runs a query in our subset of Cypher on a graph, in one call, as Kùzu's connection ...
absl::StatusOr< Query > Parse(std::string_view text)
Reads a query.
PathSearch CheapestPath(const Graph &graph, NodeId from, NodeId to, const std::vector< std::string > &types, Direction direction, std::string_view key)
Returns a cheapest path from from to to, along relationships of any of types followed in direction: o...
std::string ValueText(const Value &value)
A value as sg query prints it: a number in digits, and a string as it is.
Direction
A node and a property take 64 bytes, and a relationship 24, so a page holds 170 relationships,...
Direction Reversed(Direction direction)
The direction to follow a relationship in from its other end: out becomes in, in becomes out,...
PathSearch ShortestPath(const Graph &graph, NodeId from, NodeId to, const std::vector< std::string > &types, Direction direction)
Returns a shortest path from from to to, along relationships of any of types followed in direction: o...
std::string Explain(const Plan &plan)
The plan's steps, a line each, in the order they run, as EXPLAIN shows them.
constexpr int kAnyHops
The hops of a relationship written with a star and no number, such as -[:KNOWS*]-,...
std::vector< NodeId > nodes
A column of what a plan returns: its heading, such as b.name, p or length(p), and the property of the...
A comparison in WHERE, such as b.weight_g < 1000: a property, an operator, which is one of = <> < <= ...
A step from a node along one of its relationships: the relationship, and the node at its other end.
A node in a pattern, such as (a:Animal {name: 'Red fox'}).
What a search for a path found: the path, if there is one, and how many nodes the search reached,...
std::optional< Path > path
How to answer a query: where to start, and where to go from there.
std::vector< Step > steps
std::vector< Column > returns
What it returns, a column at a time, in order.
std::vector< std::string > slots
The pattern's variable for each slot, or nothing for a node it didn't give one.
A query in our subset of Cypher, such as MATCH (a {name: 'Red fox'})-[:EATS]->(b) WHERE b....
std::vector< RelationshipPattern > relationships
std::string path
The path's variable, for a pattern written as p = shortestPath(...), which asks for a shortest path b...
std::vector< Comparison > where
The comparisons in WHERE, joined by AND, so a row has to pass them all.
std::vector< NodePattern > nodes
A relationship from a node in a pattern to the next one, such as -[:EATS]->, or -[:EATS*2]->,...
std::vector< std::string > types
Its types: a relationship of any of them matches.
std::string weight
The property a cheapest path adds up, as in -[:KNOWS* WSHORTEST(weight)]-, which is how Kùzu writes i...
Direction direction
Which way to follow it from the node before it: out, in when it's written with its arrow on the left,...
What a query returns: a row for each match of its pattern, with a cell for each column.
std::vector< std::vector< Cell > > rows
std::vector< std::string > columns
@ kNodeIndexSeek
A row for the node named text, in slot to, found in the index.
@ kHasLabel
The rows whose node in slot from has the label text.
@ kFilter
The rows whose node in slot from has a property text that compares with value as op says.
@ kExpand
For each row, a row for each node that a relationship of any of the types goes to from the node in sl...
@ kNodeByLabelScan
A row for each node with the label text, in slot to.
@ kAllNodesScan
A row for each node in the graph, in slot to.