smollerGraph 0.20.2
A small graph database, from scratch
Loading...
Searching...
No Matches
graph.cc
Go to the documentation of this file.
2
3#include <sys/stat.h>
4
5#include <algorithm>
6#include <cerrno>
7#include <cstdio>
8#include <cstdlib>
9#include <cstring>
10#include <string>
11#include <vector>
12
13#include "absl/status/status.h"
14#include "absl/strings/str_cat.h"
15
16namespace smollergraph {
17namespace {
18
19// Copies `text` into a field of a record, padded with zeros, and cut short if
20// it's too long, so the field always ends in a zero.
21template <size_t N>
22void CopyField(char (&field)[N], std::string_view text) {
23 std::memset(field, 0, N);
24 std::memcpy(field, text.data(), std::min(text.size(), N - 1));
25}
26
27// Puts a value in a property's record, with its type, so it can be read back.
28void Encode(const Value& value, PropertyRecord& record) {
29 if (const int64_t* number = std::get_if<int64_t>(&value)) {
30 record.type = ValueType::kInteger;
31 std::memset(record.value, 0, sizeof(record.value));
32 std::memcpy(record.value, number, sizeof(*number));
33 } else {
34 record.type = ValueType::kString;
35 CopyField(record.value, std::get<std::string>(value));
36 }
37}
38
39} // namespace
40
42 if (record.type == ValueType::kInteger) {
43 int64_t number = 0;
44 std::memcpy(&number, record.value, sizeof(number));
45 return number;
46 }
47 return std::string(record.value);
48}
49
51 absl::Status status = nodes_.OpenTemporary();
52 if (status.ok()) status = relationships_.OpenTemporary();
53 if (status.ok()) status = properties_.OpenTemporary();
54 if (status.ok()) status = names_.OpenTemporary();
55 if (status.ok()) status = labels_.OpenTemporary();
56 if (status.ok()) status = types_.OpenTemporary();
57 if (status.ok()) status = embeddings_.OpenTemporary();
58 if (!status.ok()) {
59 std::fprintf(stderr, "smollergraph: no temporary files: %s\n",
60 status.ToString().c_str());
61 std::abort();
62 }
63}
64
65absl::Status Graph::Open(const std::string& path) {
66 // A folder that's there already, from an earlier run, is fine.
67 if (mkdir(path.c_str(), 0755) != 0 && errno != EEXIST) {
68 return absl::ErrnoToStatus(errno, absl::StrCat("can't make ", path));
69 }
70 // Each file opens if the one before it did, and the first error is the one
71 // we return.
72 absl::Status status = nodes_.Open(path + "/nodes");
73 if (status.ok()) status = relationships_.Open(path + "/relationships");
74 if (status.ok()) status = properties_.Open(path + "/properties");
75 if (status.ok()) status = names_.Open(path + "/names");
76 if (status.ok()) status = labels_.Open(path + "/labels");
77 if (status.ok()) status = types_.Open(path + "/types");
78 if (status.ok()) status = embeddings_.Open(path + "/embeddings");
79 return status;
80}
81
82NodeId Graph::AddNode(std::string_view name) {
83 if (std::optional<NodeId> found = Find(name)) return *found;
84 NodeRecord record;
85 CopyField(record.name, name);
86 record.label = kNoToken;
90 NodeId id = nodes_.Append(record);
91 names_.Insert(name, id);
92 return id;
93}
94
95RelationshipId Graph::AddRelationship(NodeId from, std::string_view type,
96 NodeId to) {
97 RelationshipId id = relationships_.count();
98 RelationshipRecord record;
99 record.type = types_.Add(type);
100 record.from = from;
101 record.to = to;
103 // The new relationship goes at the front of two chains, the out chain of
104 // the node it starts at, and the in chain of the node it ends at.
105 NodeRecord start = nodes_.Read(from);
106 record.next_out = start.first_out;
107 start.first_out = id;
108 nodes_.Write(from, start);
109 // The end is read after the start is written, as they're one node when a
110 // relationship goes from a node to itself.
111 NodeRecord end = nodes_.Read(to);
112 record.next_in = end.first_in;
113 end.first_in = id;
114 nodes_.Write(to, end);
115 relationships_.Append(record);
116 return id;
117}
118
119void Graph::SetLabel(NodeId node, std::string_view label) {
120 NodeRecord record = nodes_.Read(node);
121 record.label = labels_.Add(label);
122 nodes_.Write(node, record);
123}
124
125void Graph::SetProperty(NodeId node, std::string_view key, const Value& value) {
126 NodeRecord record = nodes_.Read(node);
127 Set(record.first_property, key, value);
128 nodes_.Write(node, record);
129}
130
132 std::string_view key, const Value& value) {
133 RelationshipRecord record = relationships_.Read(relationship);
134 Set(record.first_property, key, value);
135 relationships_.Write(relationship, record);
136}
137
138void Graph::Set(PropertyId& first, std::string_view key, const Value& value) {
139 PropertyId id = first;
140 while (id != kNoProperty) {
141 PropertyRecord property = properties_.Read(id);
142 if (key == property.key) {
143 Encode(value, property);
144 properties_.Write(id, property);
145 return;
146 }
147 id = property.next;
148 }
149 // Like a relationship, a new property goes at the front of the chain.
150 PropertyRecord property;
151 CopyField(property.key, key);
152 Encode(value, property);
153 property.next = first;
154 first = properties_.Append(property);
155}
156
157void Graph::SetEmbedding(NodeId node, const Embedding& embedding) {
158 if (node < embeddings_.count()) {
159 embeddings_.Write(node, embedding);
160 } else {
161 embeddings_.Append(embedding);
162 }
163}
164
165std::vector<Embedding> Graph::Embeddings() const {
166 std::vector<Embedding> embeddings;
167 if (embeddings_.count() != nodes_.count()) return embeddings;
168 embeddings.reserve(embeddings_.count());
169 for (NodeId node = 0; node < embeddings_.count(); ++node) {
170 embeddings.push_back(embeddings_.Read(node));
171 }
172 return embeddings;
173}
174
175std::optional<Value> Graph::FindProperty(NodeId node,
176 std::string_view key) const {
177 NodeRecord record = nodes_.Read(node);
178 if (key == "name") return std::string(record.name);
179 return Lookup(record.first_property, key);
180}
181
183 RelationshipId relationship, std::string_view key) const {
184 return Lookup(relationships_.Read(relationship).first_property, key);
185}
186
187std::optional<Value> Graph::Lookup(PropertyId first,
188 std::string_view key) const {
189 PropertyId id = first;
190 while (id != kNoProperty) {
191 PropertyRecord property = properties_.Read(id);
192 if (key == property.key) return ValueOf(property);
193 id = property.next;
194 }
195 return std::nullopt;
196}
197
198std::vector<Property> Graph::Properties(NodeId node) const {
199 return Chain(nodes_.Read(node).first_property);
200}
201
202std::vector<Property> Graph::RelationshipProperties(
203 RelationshipId relationship) const {
204 return Chain(relationships_.Read(relationship).first_property);
205}
206
207std::vector<Property> Graph::Chain(PropertyId first) const {
208 std::vector<Property> found;
209 PropertyId id = first;
210 while (id != kNoProperty) {
211 PropertyRecord property = properties_.Read(id);
212 found.push_back({property.key, ValueOf(property)});
213 id = property.next;
214 }
215 // Newest first in the chain, and oldest first for callers.
216 std::reverse(found.begin(), found.end());
217 return found;
218}
219
220std::optional<NodeId> Graph::Find(std::string_view name) const {
221 return names_.Find(name);
222}
223
224std::vector<Hop> Graph::Hops(NodeId node, const std::vector<std::string>& types,
225 Direction direction) const {
226 std::vector<Hop> hops;
227 // A type without a token is on no relationship, so it's left out, and when
228 // none of them has one, there are no hops.
229 std::vector<TokenId> tokens;
230 for (const std::string& type : types) {
231 if (std::optional<TokenId> token = types_.Find(type)) {
232 tokens.push_back(*token);
233 }
234 }
235 if (tokens.empty()) return hops;
236 NodeRecord record = nodes_.Read(node);
237 if (direction != Direction::kIn) {
238 Follow(record.first_out, true, tokens, hops);
239 }
240 if (direction != Direction::kOut) {
241 Follow(record.first_in, false, tokens, hops);
242 }
243 return hops;
244}
245
246void Graph::Follow(RelationshipId first, bool out,
247 const std::vector<TokenId>& types,
248 std::vector<Hop>& hops) const {
249 std::vector<Hop> chain;
250 RelationshipId id = first;
251 while (id != kNoRelationship) {
252 RelationshipRecord record = relationships_.Read(id);
253 if (std::find(types.begin(), types.end(), record.type) != types.end()) {
254 chain.push_back({id, out ? record.to : record.from});
255 }
256 id = out ? record.next_out : record.next_in;
257 }
258 // The chain is newest first, and callers get them in the order they came.
259 hops.insert(hops.end(), chain.rbegin(), chain.rend());
260}
261
262std::vector<NodeId> Graph::Neighbours(NodeId node, std::string_view type,
263 Direction direction) const {
264 std::vector<NodeId> found;
265 for (Hop hop : Hops(node, {std::string(type)}, direction)) {
266 found.push_back(hop.node);
267 }
268 return found;
269}
270
271} // namespace smollergraph
NodeId AddNode(std::string_view name)
Returns the node with this name, adding it the first time.
Definition graph.cc:82
void SetRelationshipProperty(RelationshipId relationship, std::string_view key, const Value &value)
Definition graph.cc:131
PropertyRecord property(PropertyId id) const
Definition graph.h:201
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
void SetEmbedding(NodeId node, const Embedding &embedding)
Keeps a node's embedding, in place of the one it had.
Definition graph.cc:157
std::vector< Property > Properties(NodeId node) const
Returns the properties of a node or a relationship, in the order they were first set.
Definition graph.cc:198
std::optional< Value > FindRelationshipProperty(RelationshipId relationship, std::string_view key) const
Returns a relationship's property, if it has one, such as its weight.
Definition graph.cc:182
RelationshipRecord relationship(RelationshipId id) const
Definition graph.h:198
std::string type(RelationshipId relationship) const
Definition graph.h:194
NodeRecord node(NodeId id) const
Definition graph.h:197
RelationshipId AddRelationship(NodeId from, std::string_view type, NodeId to)
Definition graph.cc:95
std::vector< NodeId > Neighbours(NodeId node, std::string_view type, Direction direction=Direction::kOut) const
Returns the nodes the hops along relationships of type lead to.
Definition graph.cc:262
std::string name(NodeId node) const
Definition graph.h:190
absl::Status Open(const std::string &path)
Opens the graph in the folder at path, creating it when it isn't there.
Definition graph.cc:65
void SetLabel(NodeId node, std::string_view label)
Gives a node its label, such as Species, in place of the one it had.
Definition graph.cc:119
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
Graph()
A graph in temporary files, which are deleted with it.
Definition graph.cc:50
std::vector< Property > RelationshipProperties(RelationshipId relationship) const
Definition graph.cc:202
void SetProperty(NodeId node, std::string_view key, const Value &value)
Sets a property of a node or a relationship, replacing the value it had.
Definition graph.cc:125
std::vector< Embedding > Embeddings() const
Returns the embeddings of all the nodes, in the order of their ids, or none unless each node has one.
Definition graph.cc:165
absl::Status OpenTemporary()
Opens an index in a file with no name, which is deleted once it's closed.
Definition name_index.cc:21
absl::Status Open(const std::string &path)
Opens the index in the file at path, creating it when it isn't there.
Definition name_index.cc:12
void Insert(std::string_view name, uint32_t id)
Keeps id for name, which the index doesn't have yet.
Definition name_index.cc:40
std::optional< uint32_t > Find(std::string_view name) const
Returns the id kept for name, if there's one.
Definition name_index.cc:30
absl::Status Open(const std::string &path)
Opening another file writes back the changes to the one that was open.
Definition record_file.h:33
absl::Status OpenTemporary()
Definition record_file.h:41
void Write(uint32_t id, const Record &record)
Definition record_file.h:70
uint32_t Append(const Record &record)
Adds a record after the last one, and returns its id.
Definition record_file.h:76
uint32_t count() const
Definition record_file.h:52
Record Read(uint32_t id) const
Reads record id, which has to be below count().
Definition record_file.h:63
TokenId Add(std::string_view name)
Returns the token for name, adding it the first time.
absl::Status OpenTemporary()
std::optional< TokenId > Find(std::string_view name) const
Returns the token for name, if the store has one.
absl::Status Open(const std::string &path)
Opens the store in the file at path, creating it when it isn't there.
std::string_view label
Definition facts.cc:18
std::string_view text
Definition facts.cc:17
uint32_t RelationshipId
Definition graph.h:21
std::array< float, kEmbeddingSize > Embedding
A node's embedding: a vector of numbers that stands for where the node is in the graph,...
Definition graph.h:96
uint32_t NodeId
Definition graph.h:20
constexpr TokenId kNoToken
The token for no name, such as the label of a node that hasn't got one.
Definition token_store.h:23
Value ValueOf(const PropertyRecord &record)
Reads the value a property's record holds.
Definition graph.cc:41
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
constexpr RelationshipId kNoRelationship
The ids at the end of a chain, where there's no next relationship, or no next property.
Definition graph.h:26
Direction
A node and a property take 64 bytes, and a relationship 24, so a page holds 170 relationships,...
Definition graph.h:72
constexpr PropertyId kNoProperty
Definition graph.h:27
uint32_t PropertyId
Definition graph.h:22
Path path
Definition plan.cc:115
Direction direction
Definition query.cc:42
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 on disk: its name, its label's token, which says what kind of node it is, the first of the rel...
Definition graph.h:32
RelationshipId first_out
Definition graph.h:35
RelationshipId first_in
Definition graph.h:36
PropertyId first_property
Definition graph.h:37
A property on disk: its key, its value, and the next property of the node or relationship it belongs ...
Definition graph.h:57
A relationship on disk: its type's token, the nodes it joins, the next relationship that starts at fr...
Definition graph.h:43