smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
plan.cc
Go to the documentation of this file.
1#include "smollergraph/plan.h"
2
3#include <algorithm>
4#include <compare>
5#include <cstddef>
6#include <cstdint>
7#include <optional>
8#include <set>
9#include <string>
10#include <string_view>
11#include <utility>
12#include <variant>
13#include <vector>
14
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"
19
20namespace smollergraph {
21namespace {
22
23// A slot's variable, or _ and its number for a node the pattern didn't name.
24std::string SlotName(const Plan& plan, int slot) {
25 const std::string& variable = plan.slots[slot];
26 return variable.empty() ? absl::StrCat("_", slot) : variable;
27}
28
29// A value as Cypher writes it: a string in quotes, and a number as it is.
30std::string Literal(const Value& value) {
31 if (const std::string* text = std::get_if<std::string>(&value)) {
32 return absl::StrCat("'", *text, "'");
33 }
34 return ValueText(value);
35}
36
37// The name a node of the pattern has, if it gives it one, which the index can
38// find.
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;
43 }
44 return std::nullopt;
45}
46
47// Adds the filters on a node of the pattern, once the step `found` has put it
48// in a slot: one for its label, one for each of its properties, and one for
49// each comparison in WHERE on its variable. They come as early as they can, so
50// the rows they drop are expanded no further. A seek has found the name
51// already, and a label scan the label.
52void AddFilters(const Query& query, const NodePattern& node, int slot,
53 Step::Kind found, Plan& plan) {
54 if (!node.label.empty() && found != Step::Kind::kNodeByLabelScan) {
55 plan.steps.push_back({Step::Kind::kHasLabel, slot, -1, node.label});
56 }
57 for (const Property& property : node.properties) {
58 if (found == Step::Kind::kNodeIndexSeek && property.key == "name") {
59 continue;
60 }
61 plan.steps.push_back(
62 {Step::Kind::kFilter, slot, -1, property.key, "=", property.value});
63 }
64 if (node.variable.empty()) return;
65 for (const Comparison& comparison : query.where) {
66 if (comparison.property.variable != node.variable) continue;
67 plan.steps.push_back({Step::Kind::kFilter, slot, -1,
68 comparison.property.key, comparison.op,
69 comparison.value});
70 }
71}
72
73// How costly a node of the pattern is to find, when the plan starts from it:
74// a name is found in the index, a label by a scan that keeps fewer rows, and
75// otherwise each node in the graph is a start.
76int CostToFind(const NodePattern& node) {
77 if (NameOf(node)) return 0;
78 if (!node.label.empty()) return 1;
79 return 2;
80}
81
82// Adds a step that finds a node of the pattern, in a slot of its own: a seek
83// in the index for a node with a name, a scan of a label for a node with a
84// label, and otherwise a scan of all the nodes. Then come the filters on it.
85// Returns its slot.
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)) {
90 plan.steps.push_back({Step::Kind::kNodeIndexSeek, -1, slot, *name});
91 } else if (!node.label.empty()) {
92 plan.steps.push_back({Step::Kind::kNodeByLabelScan, -1, slot, node.label});
93 } else {
94 plan.steps.push_back({Step::Kind::kAllNodesScan, -1, slot, ""});
95 }
96 AddFilters(query, node, slot, plan.steps.back().kind, plan);
97 return slot;
98}
99
100// The types a step follows, joined by bars as Cypher writes them, such as
101// MemberOf|AdminTo.
102std::string Types(const Step& step) { return absl::StrJoin(step.types, "|"); }
103
104// A relationship as Cypher writes it, with its arrow pointing the way it's
105// followed, or with no arrow when it's followed both ways.
106std::string Arrow(Direction direction, std::string_view type) {
107 return absl::StrCat(direction == Direction::kIn ? "<-[:" : "-[:", type,
108 direction == Direction::kOut ? "]->" : "]-");
109}
110
111// A row: a node in each of the plan's slots, and the path the plan found, for
112// a plan that finds one.
113struct Row {
114 std::vector<NodeId> nodes;
115 Path path;
116};
117
118// Adds the expands from the node in `slot` to the pattern's `node`, along
119// `relationship` in `direction`, then the filters on `node`, and returns the
120// slot it ends up in.
121int AddExpands(const Query& query, const RelationshipPattern& relationship,
122 Direction direction, const NodePattern& node, int slot,
123 Plan& plan) {
124 // Each hop is an expand into a slot of its own. The last hop's slot is the
125 // pattern's node, and the ones before it are nodes it doesn't name.
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;
130 plan.steps.push_back({.kind = Step::Kind::kExpand,
131 .from = slot,
132 .to = to,
133 .direction = direction,
134 .types = relationship.types});
135 slot = to;
136 }
137 AddFilters(query, node, slot, Step::Kind::kExpand, plan);
138 return slot;
139}
140
141// Whether a property compares with a value as `op` says. A missing property
142// is Cypher's null, which no comparison keeps. Values of different types are
143// never equal, and have no order.
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;
154 return order >= 0;
155}
156
157// Adds a column to the plan for each item the query returns, and returns the
158// plan, or an error for an item it can't return.
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) {
163 // A path has no properties, so it's returned whole, or as a function
164 // of it, and a shortest path counts hops, so it has no cost.
165 if (!item.key.empty()) {
166 return absl::InvalidArgumentError(
167 absl::StrCat("the path ", item.variable, " has no properties"));
168 }
169 if (item.function == "cost" && query.shortest) {
170 return absl::InvalidArgumentError(
171 "a shortest path has no cost, as it counts hops");
172 }
173 plan.returns.push_back({.heading = item.function.empty()
174 ? item.variable
175 : absl::StrCat(item.function, "(",
176 item.variable, ")"),
177 .key = {},
178 .function = item.function});
179 continue;
180 }
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));
185 }
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"));
190 }
191 plan.returns.push_back(
192 {.heading = absl::StrCat(item.variable, ".", item.key),
193 .slot = static_cast<int>(found - plan.slots.begin()),
194 .key = item.key,
195 .function = {}});
196 }
197 return plan;
198}
199
200} // namespace
201
202std::string ValueText(const Value& value) {
203 if (const int64_t* number = std::get_if<int64_t>(&value)) {
204 return absl::StrCat(*number);
205 }
206 return std::get<std::string>(value);
207}
208
209absl::StatusOr<Plan> PlanQuery(const Query& query) {
210 Plan plan;
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"));
217 }
218 }
219 }
220
221 for (const Comparison& comparison : query.where) {
222 const std::string& variable = comparison.property.variable;
223 if (std::none_of(query.nodes.begin(), query.nodes.end(),
224 [&](const NodePattern& node) {
225 return node.variable == variable;
226 })) {
227 return absl::InvalidArgumentError(
228 absl::StrCat("there's no variable called ", variable));
229 }
230 }
231
232 for (const RelationshipPattern& relationship : query.relationships) {
233 if (relationship.hops == kAnyHops && query.path.empty()) {
234 return absl::InvalidArgumentError(
235 "a relationship with any number of hops needs shortestPath");
236 }
237 }
238
239 if (!query.path.empty()) {
240 if (query.relationships.size() != 1 ||
241 query.relationships[0].hops != kAnyHops) {
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)");
245 }
246 const RelationshipPattern& relationship = query.relationships[0];
247 // A path is a shortest one, or with a weight, a cheapest one.
248 if (query.shortest == !relationship.weight.empty()) {
249 return absl::InvalidArgumentError(
250 "a path needs shortestPath, or WSHORTEST with a weight, not both");
251 }
252 // Both ends are found, each in the way that's cheapest for it, and then
253 // the path between them.
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,
258 .from = from,
259 .to = to,
260 .direction = relationship.direction,
261 .weight = relationship.weight,
262 .types = relationship.types});
263 return AddReturns(query, std::move(plan));
264 }
265
266 // The plan starts from the node of the pattern that's cheapest to find, the
267 // first of them when there's a tie.
268 size_t first = 0;
269 for (size_t i = 1; i < query.nodes.size(); ++i) {
270 if (CostToFind(query.nodes[i]) < CostToFind(query.nodes[first])) first = i;
271 }
272 AddFind(query, query.nodes[first], plan);
273 // From the start, it expands to the pattern's right end, then to its left
274 // end, following each relationship there from the node after it, so the
275 // other way.
276 int slot = 0;
277 for (size_t i = first; i < query.relationships.size(); ++i) {
278 slot = AddExpands(query, query.relationships[i],
279 query.relationships[i].direction, query.nodes[i + 1],
280 slot, plan);
281 }
282 slot = 0;
283 for (size_t i = first; i > 0; --i) {
284 const RelationshipPattern& relationship = query.relationships[i - 1];
285 slot = AddExpands(query, relationship, Reversed(relationship.direction),
286 query.nodes[i - 1], slot, plan);
287 }
288 return AddReturns(query, std::move(plan));
289}
290
291Result Run(const Plan& plan, const Graph& graph) {
292 // A single row to begin with, with its slots still to fill.
293 std::vector<Row> rows = {{std::vector<NodeId>(plan.slots.size()), {}}};
294 for (const Step& step : plan.steps) {
295 std::vector<Row> next;
296 for (const Row& row : rows) {
297 switch (step.kind) {
298 case Step::Kind::kNodeIndexSeek:
299 if (std::optional<NodeId> node = graph.Find(step.text)) {
300 next.push_back(row);
301 next.back().nodes[step.to] = *node;
302 }
303 break;
304 case Step::Kind::kAllNodesScan:
305 for (NodeId node = 0; node < graph.node_count(); ++node) {
306 next.push_back(row);
307 next.back().nodes[step.to] = node;
308 }
309 break;
310 case Step::Kind::kNodeByLabelScan:
311 for (NodeId node = 0; node < graph.node_count(); ++node) {
312 if (graph.label(node) != step.text) continue;
313 next.push_back(row);
314 next.back().nodes[step.to] = node;
315 }
316 break;
317 case Step::Kind::kExpand:
318 for (Hop hop :
319 graph.Hops(row.nodes[step.from], step.types, step.direction)) {
320 next.push_back(row);
321 next.back().nodes[step.to] = hop.node;
322 }
323 break;
324 case Step::Kind::kFilter:
325 if (Compare(graph.FindProperty(row.nodes[step.from], step.text),
326 step.op, step.value)) {
327 next.push_back(row);
328 }
329 break;
330 case Step::Kind::kHasLabel:
331 if (graph.label(row.nodes[step.from]) == step.text) {
332 next.push_back(row);
333 }
334 break;
335 case Step::Kind::kShortestPath:
336 case Step::Kind::kCheapestPath: {
337 NodeId from = row.nodes[step.from];
338 NodeId to = row.nodes[step.to];
339 PathSearch search =
340 step.kind == Step::Kind::kShortestPath
341 ? ShortestPath(graph, from, to, step.types, step.direction)
342 : CheapestPath(graph, from, to, step.types, step.direction,
343 step.weight);
344 if (search.path) {
345 next.push_back(row);
346 next.back().path = *std::move(search.path);
347 }
348 break;
349 }
350 }
351 }
352 rows = std::move(next);
353 }
354
355 Result result;
356 for (const Column& column : plan.returns) {
357 result.columns.push_back(column.heading);
358 }
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;
363 for (const Column& column : plan.returns) {
364 if (column.slot >= 0) {
365 NodeId node = row.nodes[column.slot];
366 cells.push_back({.node = node,
367 .value = graph.FindProperty(node, column.key),
368 .path = {}});
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});
374 } else {
375 cells.push_back(
376 {row.path.nodes[0], PathText(graph, row.path), row.path});
377 }
378 values.push_back(cells.back().value);
379 }
380 // DISTINCT keeps the first of rows that return the same values.
381 if (plan.distinct && !seen.insert(std::move(values)).second) continue;
382 result.rows.push_back(std::move(cells));
383 }
384 return result;
385}
386
387absl::StatusOr<Result> Execute(const Graph& graph, std::string_view text) {
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");
393 }
394 absl::StatusOr<Plan> plan = PlanQuery(*query);
395 if (!plan.ok()) return plan.status();
396 return Run(*plan, graph);
397}
398
399std::string Explain(const Plan& plan) {
400 std::string text;
401 for (const Step& step : plan.steps) {
402 switch (step.kind) {
403 case Step::Kind::kNodeIndexSeek:
404 absl::StrAppend(&text, "NodeIndexSeek (", SlotName(plan, step.to),
405 " {name: '", step.text, "'})\n");
406 break;
407 case Step::Kind::kAllNodesScan:
408 absl::StrAppend(&text, "AllNodesScan (", SlotName(plan, step.to),
409 ")\n");
410 break;
411 case Step::Kind::kNodeByLabelScan:
412 absl::StrAppend(&text, "NodeByLabelScan (", SlotName(plan, step.to),
413 ":", step.text, ")\n");
414 break;
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");
419 break;
420 case Step::Kind::kFilter:
421 absl::StrAppend(&text, "Filter ", SlotName(plan, step.from), ".",
422 step.text, " ", step.op, " ", Literal(step.value),
423 "\n");
424 break;
425 case Step::Kind::kHasLabel:
426 absl::StrAppend(&text, "Filter ", SlotName(plan, step.from), ":",
427 step.text, "\n");
428 break;
429 case Step::Kind::kShortestPath:
430 // A star after the types, as the path has any number of hops.
431 absl::StrAppend(&text, "ShortestPath (", SlotName(plan, step.from), ")",
432 Arrow(step.direction, Types(step) + "*"), "(",
433 SlotName(plan, step.to), ")\n");
434 break;
435 case Step::Kind::kCheapestPath:
436 absl::StrAppend(
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");
441 break;
442 }
443 }
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");
449 return text;
450}
451
452} // namespace smollergraph
A graph kept in three files of records, one for nodes, one for relationships and one for their proper...
Definition graph.h:113
size_t node_count() const
Definition graph.h:202
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.
Definition graph.cc:175
std::optional< NodeId > Find(std::string_view name) const
Returns the node with this name, if the graph has one.
Definition graph.cc:220
std::string label(NodeId node) const
Definition graph.h:191
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,...
Definition graph.cc:224
std::vector< Property > properties
Definition facts.cc:19
std::string_view text
Definition facts.cc:17
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 ...
Definition query.cc:239
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,...
Definition plan.cc:209
uint32_t NodeId
Definition graph.h:20
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.
Definition plan.cc:291
std::variant< int64_t, std::string > Value
A property's value, as the graph hands it out: a whole number or a string.
Definition graph.h:100
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 ...
Definition plan.cc:387
absl::StatusOr< Query > Parse(std::string_view text)
Reads a query.
Definition parser.cc:284
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...
Definition query.cc:196
std::string ValueText(const Value &value)
A value as sg query prints it: a number in digits, and a string as it is.
Definition plan.cc:202
Direction
A node and a property take 64 bytes, and a relationship 24, so a page holds 170 relationships,...
Definition graph.h:72
Direction Reversed(Direction direction)
The direction to follow a relationship in from its other end: out becomes in, in becomes out,...
Definition graph.h:76
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...
Definition query.cc:166
std::string Explain(const Plan &plan)
The plan's steps, a line each, in the order they run, as EXPLAIN shows them.
Definition plan.cc:399
constexpr int kAnyHops
The hops of a relationship written with a star and no number, such as -[:KNOWS*]-,...
Definition parser.h:24
std::vector< NodeId > nodes
Definition plan.cc:114
Path path
Definition plan.cc:115
Direction direction
Definition query.cc:42
A column of what a plan returns: its heading, such as b.name, p or length(p), and the property of the...
Definition plan.h:63
A comparison in WHERE, such as b.weight_g < 1000: a property, an operator, which is one of = <> < <= ...
Definition parser.h:50
A step from a node along one of its relationships: the relationship, and the node at its other end.
Definition graph.h:84
A node in a pattern, such as (a:Animal {name: 'Red fox'}).
Definition parser.h:16
What a search for a path found: the path, if there is one, and how many nodes the search reached,...
Definition query.h:36
std::optional< Path > path
Definition query.h:37
How to answer a query: where to start, and where to go from there.
Definition plan.h:71
std::vector< Step > steps
Definition plan.h:72
std::vector< Column > returns
What it returns, a column at a time, in order.
Definition plan.h:77
std::vector< std::string > slots
The pattern's variable for each slot, or nothing for a node it didn't give one.
Definition plan.h:75
A query in our subset of Cypher, such as MATCH (a {name: 'Red fox'})-[:EATS]->(b) WHERE b....
Definition parser.h:71
std::vector< RelationshipPattern > relationships
Definition parser.h:79
std::string path
The path's variable, for a pattern written as p = shortestPath(...), which asks for a shortest path b...
Definition parser.h:76
std::vector< Comparison > where
The comparisons in WHERE, joined by AND, so a row has to pass them all.
Definition parser.h:81
std::vector< NodePattern > nodes
Definition parser.h:78
A relationship from a node in a pattern to the next one, such as -[:EATS]->, or -[:EATS*2]->,...
Definition parser.h:30
std::vector< std::string > types
Its types: a relationship of any of them matches.
Definition parser.h:32
std::string weight
The property a cheapest path adds up, as in -[:KNOWS* WSHORTEST(weight)]-, which is how Kùzu writes i...
Definition parser.h:39
Direction direction
Which way to follow it from the node before it: out, in when it's written with its arrow on the left,...
Definition parser.h:36
What a query returns: a row for each match of its pattern, with a cell for each column.
Definition plan.h:101
std::vector< std::vector< Cell > > rows
Definition plan.h:103
std::vector< std::string > columns
Definition plan.h:102
One step of a plan.
Definition plan.h:19
@ 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.