1use super::json::Json;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Position {
16 Index,
17 Type,
18 Other,
19}
20
21#[derive(Debug, Clone, PartialEq)]
23pub enum Plan {
24 All,
25 Empty,
26 Match(String),
28 Ids(Vec<i64>),
30 Union(Vec<Plan>),
31 Intersect(Vec<Plan>),
32 Minus(Box<Plan>),
34}
35
36#[derive(Debug, Clone, PartialEq)]
38pub struct Compiled {
39 pub plan: Plan,
40 pub exact: bool,
41}
42
43type Mapping<'a> = &'a dyn Fn(Position, i64) -> Option<u32>;
44
45#[derive(Default)]
47struct Node {
48 index: String,
49 parts: [Option<String>; 3],
50 impossible: bool,
51}
52
53impl Node {
54 fn render(&self) -> String {
55 let part = |slot: usize| self.parts[slot].as_deref().unwrap_or("*");
56 format!("({}: {} {} {})", self.index, part(0), part(1), part(2))
57 }
58
59 fn set(&mut self, slot: usize, value: String) {
60 match &self.parts[slot] {
61 Some(found) if *found != value => self.impossible = true,
62 _ => self.parts[slot] = Some(value),
63 }
64 }
65
66 fn constraints(&self) -> usize {
67 self.parts
68 .iter()
69 .flatten()
70 .filter(|part| !part.starts_with('$'))
71 .count()
72 }
73}
74
75fn slot_of(column: &str) -> Option<usize> {
76 match column {
77 "type_id" => Some(0),
78 "from_id" => Some(1),
79 "to_id" => Some(2),
80 _ => None,
81 }
82}
83
84fn forward_slot(relation: &str) -> Option<usize> {
86 match relation {
87 "type" => Some(0),
88 "from" => Some(1),
89 "to" => Some(2),
90 _ => None,
91 }
92}
93
94fn backward_slot(relation: &str) -> Option<usize> {
96 match relation {
97 "typed" => Some(0),
98 "out" => Some(1),
99 "in" => Some(2),
100 _ => None,
101 }
102}
103
104fn single_eq(condition: &Json) -> Option<i64> {
105 match condition {
106 Json::Object(pairs) if pairs.len() == 1 && pairs[0].0 == "_eq" => pairs[0].1.as_i64(),
107 _ => None,
108 }
109}
110
111struct Builder<'a> {
112 mapping: Mapping<'a>,
113 nodes: Vec<Node>,
114 next_variable: usize,
115}
116
117impl Builder<'_> {
118 fn variable(&mut self) -> String {
119 self.next_variable += 1;
120 format!("$v{}", self.next_variable)
121 }
122
123 fn address(&self, position: Position, id: i64) -> Option<String> {
124 if id == 0 && position == Position::Other {
125 return Some("0".to_string());
126 }
127 (self.mapping)(position, id).map(|address| address.to_string())
128 }
129
130 fn pure(&mut self, node: usize, condition: &Json) -> bool {
133 let mark = self.nodes.len();
134 let saved = self.nodes[node].parts.clone();
135 let Json::Object(pairs) = condition else {
136 return false;
137 };
138 let pure =
139 !pairs.is_empty() && pairs.iter().all(|(key, value)| self.term(node, key, value));
140 if !pure {
141 self.nodes.truncate(mark);
142 self.nodes[node].parts = saved;
143 }
144 pure
145 }
146
147 fn term(&mut self, node: usize, key: &str, value: &Json) -> bool {
149 if let Some(slot) = slot_of(key) {
150 let Some(id) = single_eq(value) else {
151 return false;
152 };
153 let position = if slot == 0 {
154 Position::Type
155 } else {
156 Position::Other
157 };
158 match self.address(position, id) {
159 Some(address) => self.nodes[node].set(slot, address),
160 None => self.nodes[node].impossible = true,
161 }
162 return true;
163 }
164 if let Some(slot) = forward_slot(key) {
165 let variable = self.variable();
166 let child = self.nodes.len();
167 self.nodes.push(Node {
168 index: variable.clone(),
169 ..Node::default()
170 });
171 if self.pure(child, value) {
172 self.nodes[node].set(slot, variable);
173 return true;
174 }
175 self.nodes.truncate(child);
176 return false;
177 }
178 if let Some(slot) = backward_slot(key) {
179 let variable = self.variable();
180 let child = self.nodes.len();
181 let parent = self.nodes[node].index.clone();
182 let mut pattern = Node {
183 index: variable,
184 ..Node::default()
185 };
186 pattern.parts[slot] = Some(parent);
187 self.nodes.push(pattern);
188 if self.pure(child, value) {
189 return true;
190 }
191 self.nodes.truncate(child);
192 return false;
193 }
194 if key == "_and" {
195 return value.as_list().iter().all(|item| match item {
196 Json::Object(pairs) => pairs.iter().all(|(key, value)| self.term(node, key, value)),
197 _ => false,
198 });
199 }
200 false
201 }
202}
203
204pub fn compile(condition: &Json, mapping: Mapping) -> Compiled {
206 let Json::Object(pairs) = condition else {
207 return Compiled {
208 plan: Plan::All,
209 exact: true,
210 };
211 };
212 let mut builder = Builder {
213 mapping,
214 nodes: vec![Node {
215 index: "$i".to_string(),
216 ..Node::default()
217 }],
218 next_variable: 0,
219 };
220 let mut plans = Vec::new();
221 let mut exact = true;
222 for (key, value) in pairs {
223 if key == "id" {
224 if let Some(ids) = id_list(value) {
225 plans.push(Plan::Ids(ids));
226 continue;
227 }
228 }
229 let mark = builder.nodes.len();
230 let saved = builder.nodes[0].parts.clone();
231 if builder.term(0, key, value) {
232 continue;
233 }
234 builder.nodes.truncate(mark);
235 builder.nodes[0].parts = saved;
236 let (plan, whole) = other(key, value, mapping);
237 if let Some(plan) = plan {
238 plans.push(plan);
239 }
240 exact &= whole;
241 }
242 let constrained = builder.nodes.len() > 1 || builder.nodes[0].parts.iter().any(Option::is_some);
243 if builder.nodes.iter().any(|node| node.impossible) {
244 return Compiled {
245 plan: Plan::Empty,
246 exact: true,
247 };
248 }
249 if constrained {
250 let root = builder.nodes.remove(0);
251 let mut children = std::mem::take(&mut builder.nodes);
252 children.sort_by_key(|node| std::cmp::Reverse(node.constraints()));
254 let ordered: Vec<Node> = if root.constraints() > 0 {
255 std::iter::once(root).chain(children).collect()
256 } else {
257 children.into_iter().chain(std::iter::once(root)).collect()
258 };
259 let text = ordered
260 .iter()
261 .map(Node::render)
262 .collect::<Vec<_>>()
263 .join(" ");
264 plans.insert(0, Plan::Match(format!("({text})")));
265 }
266 let plan = match plans.len() {
267 0 => Plan::All,
268 1 => plans.remove(0),
269 _ => Plan::Intersect(plans),
270 };
271 Compiled { plan, exact }
272}
273
274fn id_list(condition: &Json) -> Option<Vec<i64>> {
275 let Json::Object(pairs) = condition else {
276 return None;
277 };
278 if pairs.len() != 1 {
279 return None;
280 }
281 match pairs[0].0.as_str() {
282 "_eq" => pairs[0].1.as_i64().map(|id| vec![id]),
283 "_in" => match &pairs[0].1 {
284 Json::Array(items) => items.iter().map(Json::as_i64).collect(),
285 _ => None,
286 },
287 _ => None,
288 }
289}
290
291fn other(key: &str, value: &Json, mapping: Mapping) -> (Option<Plan>, bool) {
294 match key {
295 "_or" => {
296 let items: Vec<Compiled> = value
297 .as_list()
298 .iter()
299 .map(|item| compile(item, mapping))
300 .collect();
301 if items.is_empty() {
302 return (None, false);
303 }
304 let exact = items.iter().all(|item| item.exact);
305 (
306 Some(Plan::Union(
307 items.into_iter().map(|item| item.plan).collect(),
308 )),
309 exact,
310 )
311 }
312 "_and" => {
313 let items: Vec<Compiled> = value
314 .as_list()
315 .iter()
316 .map(|item| compile(item, mapping))
317 .collect();
318 let exact = items.iter().all(|item| item.exact);
319 (
320 Some(Plan::Intersect(
321 items.into_iter().map(|item| item.plan).collect(),
322 )),
323 exact,
324 )
325 }
326 "_not" => {
327 let inner = compile(value, mapping);
328 if inner.exact {
329 (Some(Plan::Minus(Box::new(inner.plan))), true)
330 } else {
331 (None, false)
332 }
333 }
334 column => {
335 if slot_of(column).is_none() {
336 return (None, false);
337 }
338 let ids = match id_list(value) {
339 Some(ids) => ids,
340 None => return (None, false),
341 };
342 let branches = ids
343 .into_iter()
344 .map(|id| {
345 let mut single = vec![(
346 column.to_string(),
347 Json::object(vec![("_eq", Json::Int(id))]),
348 )];
349 compile(&Json::Object(std::mem::take(&mut single)), mapping).plan
350 })
351 .collect();
352 (Some(Plan::Union(branches)), true)
353 }
354 }
355}
356
357pub fn render(plan: &Plan) -> String {
359 let list = |items: &[Plan]| items.iter().map(render).collect::<Vec<_>>().join(" ");
360 match plan {
361 Plan::All => "all".to_string(),
362 Plan::Empty => "empty".to_string(),
363 Plan::Match(text) => text.clone(),
364 Plan::Ids(ids) => format!(
365 "(ids {})",
366 ids.iter().map(i64::to_string).collect::<Vec<_>>().join(" ")
367 ),
368 Plan::Union(items) => format!("(union {})", list(items)),
369 Plan::Intersect(items) => format!("(intersect {})", list(items)),
370 Plan::Minus(item) => format!("(minus {})", render(item)),
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use super::*;
377
378 fn map(position: Position, id: i64) -> Option<u32> {
380 let _ = position;
381 (id != 404)
382 .then_some((id + 100) as u32)
383 .map(|a| if id == 0 { 99 } else { a })
384 }
385
386 fn plan(text: &str) -> Compiled {
387 compile(&Json::parse(text).unwrap(), &map)
388 }
389
390 fn matched(text: &str) -> Plan {
391 Plan::Match(text.to_string())
392 }
393
394 #[test]
396 fn shared_vectors() {
397 let vectors = Json::parse(include_str!(
398 "../../../docs/protocol/graphql/where-vectors.json"
399 ))
400 .unwrap();
401 let Json::Array(vectors) = vectors else {
402 panic!()
403 };
404 for vector in vectors {
405 let found = compile(vector.get("where").unwrap(), &map);
406 assert_eq!(
407 render(&found.plan),
408 vector.get("plan").unwrap().as_str().unwrap(),
409 "{}",
410 vector.get("where").unwrap().write()
411 );
412 assert_eq!(
413 Some(found.exact),
414 match vector.get("exact") {
415 Some(Json::Bool(exact)) => Some(*exact),
416 _ => None,
417 }
418 );
419 }
420 }
421
422 #[test]
423 fn equality_and_relations_join_variables() {
424 assert_eq!(
425 plan(r#"{"type_id":{"_eq":5}}"#).plan,
426 matched("(($i: 105 * *))")
427 );
428 let joined = plan(r#"{"from":{"type_id":{"_eq":5}}}"#);
429 assert!(joined.exact);
430 assert_eq!(joined.plan, matched("(($v1: 105 * *) ($i: * $v1 *))"));
431 }
432}