1use std::collections::{BTreeSet, HashSet};
5use std::rc::Rc;
6
7use super::document::{Field, Selection};
8use super::execute::{Exec, GqlError, GqlResult};
9use super::json::Json;
10use super::plan::{compile, Plan};
11use super::store::{LinkRow, ValueKind};
12use super::tables::{columns, compare, passes, relation, Relation, TABLES};
13use crate::triplets::{match_triplets_query, Triplet, TripletQuery};
14
15impl<'a> Exec<'a, '_> {
16 pub fn select_field(&mut self, field: &'a Field) -> GqlResult<Option<Json>> {
18 let name = field.name.as_str();
19 if let Some(table) = TABLES.iter().find(|table| **table == name) {
20 let rows = self.select(table, field)?;
21 return Ok(Some(self.project_all(table, &rows, &field.selections)?));
22 }
23 if let Some(table) = name
24 .strip_suffix("_by_pk")
25 .filter(|table| TABLES.contains(table))
26 {
27 let key = primary_key(table);
28 let id = field.argument(key, self.variables).unwrap_or(Json::Null);
29 let condition = Json::Object(vec![(key.to_string(), Json::object(vec![("_eq", id)]))]);
30 let rows = self.rows(table, &condition)?;
31 return Ok(Some(match rows.first() {
32 Some(row) => self.project(table, row, &field.selections)?,
33 None => Json::Null,
34 }));
35 }
36 if let Some(table) = name
37 .strip_suffix("_aggregate")
38 .filter(|table| TABLES.contains(table))
39 {
40 let rows = self.select(table, field)?;
41 return Ok(Some(self.aggregate(table, rows, field)?));
42 }
43 Ok(None)
44 }
45
46 fn select(&mut self, table: &str, field: &'a Field) -> GqlResult<Vec<Json>> {
48 let condition = field
49 .argument("where", self.variables)
50 .unwrap_or(Json::Null);
51 let rows = self.rows(table, &condition)?;
52 self.shape(table, rows, field)
53 }
54
55 fn shape(
57 &mut self,
58 table: &str,
59 mut rows: Vec<Json>,
60 field: &'a Field,
61 ) -> GqlResult<Vec<Json>> {
62 let distinct = field
63 .argument("distinct_on", self.variables)
64 .unwrap_or(Json::Null);
65 let distinct: Vec<String> = match &distinct {
66 Json::String(column) => vec![column.clone()],
67 other => other
68 .as_list()
69 .iter()
70 .filter_map(|c| c.as_str().map(str::to_string))
71 .collect(),
72 };
73 let order = field
74 .argument("order_by", self.variables)
75 .unwrap_or(Json::Null);
76 let mut specs = Vec::new();
77 for item in order_items(&order) {
78 flatten_order(&item, &mut Vec::new(), &mut specs);
79 }
80 if !specs.is_empty() {
81 let mut keyed = Vec::with_capacity(rows.len());
82 for row in rows {
83 let mut key = Vec::with_capacity(specs.len());
84 for (path, _) in &specs {
85 key.push(self.sort_value(table, &row, path)?);
86 }
87 keyed.push((key, row));
88 }
89 keyed.sort_by(|(left, _), (right, _)| {
90 for ((left, right), (_, direction)) in left.iter().zip(right).zip(&specs) {
91 let found = order_values(left, right, direction);
92 if found != std::cmp::Ordering::Equal {
93 return found;
94 }
95 }
96 std::cmp::Ordering::Equal
97 });
98 rows = keyed.into_iter().map(|(_, row)| row).collect();
99 }
100 if !distinct.is_empty() {
101 let mut seen = HashSet::new();
102 rows.retain(|row| {
103 let key: Vec<String> = distinct
104 .iter()
105 .map(|column| row.get(column).map_or_else(String::new, Json::write))
106 .collect();
107 seen.insert(key)
108 });
109 }
110 let offset = field
111 .argument("offset", self.variables)
112 .and_then(|o| o.as_i64())
113 .unwrap_or(0)
114 .max(0) as usize;
115 let rows = rows.into_iter().skip(offset);
116 Ok(
117 match field
118 .argument("limit", self.variables)
119 .and_then(|l| l.as_i64())
120 {
121 Some(limit) => rows.take(limit.max(0) as usize).collect(),
122 None => rows.collect(),
123 },
124 )
125 }
126
127 fn sort_value(&mut self, table: &str, row: &Json, path: &[String]) -> GqlResult<Json> {
128 let Some((first, rest)) = path.split_first() else {
129 return Ok(Json::Null);
130 };
131 if let Some(found) = relation(table, first) {
132 let local = row.get(found.local).cloned().unwrap_or(Json::Null);
133 let related = self.related(found, &local)?;
134 return match related.first() {
135 Some(next) => self.sort_value(found.target, next, rest),
136 None => Ok(Json::Null),
137 };
138 }
139 self.column_value(table, row, first)
140 }
141
142 pub fn rows(&mut self, table: &str, condition: &Json) -> GqlResult<Vec<Json>> {
144 if table != "links" {
145 let mut rows = self.table_rows(table)?;
146 let mut kept = Vec::new();
147 for row in rows.drain(..) {
148 if self.matches(table, &row, condition)? {
149 kept.push(row);
150 }
151 }
152 return Ok(kept);
153 }
154 let store = &*self.store;
155 let compiled = compile(condition, &|position, id| store.address(position, id));
156 let mut found = self.link_rows_of(&compiled.plan)?;
157 found.sort_by_key(|row| row.id);
158 let mut rows = Vec::with_capacity(found.len());
159 for row in found {
160 let row = row.to_json();
161 if compiled.exact || self.matches("links", &row, condition)? {
162 rows.push(row);
163 }
164 }
165 Ok(rows)
166 }
167
168 fn link_rows_of(&mut self, plan: &Plan) -> GqlResult<Vec<LinkRow>> {
169 let subject = self.subject;
170 let addresses = self.addresses(plan)?;
171 let triplets: Vec<Triplet> = self.store.view(subject, |view| {
172 addresses
173 .iter()
174 .filter_map(|address| view.get_triplet(*address))
175 .collect()
176 });
177 Ok(triplets
178 .iter()
179 .filter_map(|triplet| self.store.row_of(triplet))
180 .collect())
181 }
182
183 fn addresses(&mut self, plan: &Plan) -> GqlResult<BTreeSet<u32>> {
186 let subject = self.subject;
187 Ok(match plan {
188 Plan::Empty => BTreeSet::new(),
189 Plan::All => {
190 let all = self
191 .store
192 .view(subject, |view| view.each_triplet(TripletQuery::any()));
193 all.iter()
194 .map(|t| t.index)
195 .filter(|t| self.store.deep_of(*t).is_some())
196 .collect()
197 }
198 Plan::Ids(ids) => ids
199 .iter()
200 .filter_map(|id| self.store.triplet_of(*id))
201 .collect(),
202 Plan::Match(text) => {
203 let found = self
204 .store
205 .view(subject, |view| match_triplets_query(view, text, "$i"))
206 .map_err(GqlError::write)?;
207 found
208 .into_iter()
209 .filter(|t| self.store.deep_of(*t).is_some())
210 .collect()
211 }
212 Plan::Union(items) => {
213 let mut all = BTreeSet::new();
214 for item in items {
215 all.extend(self.addresses(item)?);
216 }
217 all
218 }
219 Plan::Intersect(items) => {
220 let mut all: Option<BTreeSet<u32>> = None;
221 for item in items {
222 let next = self.addresses(item)?;
223 all = Some(match all {
224 Some(all) => all.intersection(&next).copied().collect(),
225 None => next,
226 });
227 }
228 all.unwrap_or_default()
229 }
230 Plan::Minus(item) => {
231 let without = self.addresses(item)?;
232 let all = self.addresses(&Plan::All)?;
233 all.difference(&without).copied().collect()
234 }
235 })
236 }
237
238 fn column_value(&mut self, table: &str, row: &Json, column: &str) -> GqlResult<Json> {
240 if table == "links" && column == "value" {
241 let id = row.get("id").and_then(Json::as_i64).unwrap_or(0);
242 for kind in ValueKind::ALL {
243 if let Some((value_row, found)) = self.store.value_of_owner(kind, id) {
244 return Ok(Json::object(vec![
245 ("id", Json::Int(i64::from(value_row))),
246 ("value", found.value.clone()),
247 ]));
248 }
249 }
250 return Ok(Json::Null);
251 }
252 Ok(row.get(column).cloned().unwrap_or(Json::Null))
253 }
254
255 pub fn matches(&mut self, table: &str, row: &Json, condition: &Json) -> GqlResult<bool> {
257 let Json::Object(pairs) = condition else {
258 return Ok(true);
259 };
260 for (key, value) in pairs {
261 let passed = match key.as_str() {
262 "_and" => {
263 let mut all = true;
264 for item in value.as_list() {
265 all = all && self.matches(table, row, item)?;
266 }
267 all
268 }
269 "_or" => {
270 let mut any = false;
271 for item in value.as_list() {
272 any = any || self.matches(table, row, item)?;
273 }
274 any
275 }
276 "_not" => !self.matches(table, row, value)?,
277 _ => {
278 if let Some(found) = relation(table, key) {
279 let set = self.remote_set(found, value)?;
280 row.get(found.local)
281 .is_some_and(|local| set.contains(&local.write()))
282 } else if table == "links" && key == "value"
283 || columns(table).contains(&key.as_str())
284 {
285 let column = self.column_value(table, row, key)?;
286 let Json::Object(operators) = value else {
287 return Err(GqlError::validation(
288 "a comparison is an object",
289 format!("$.where.{key}"),
290 ));
291 };
292 let mut all = true;
293 for (operator, argument) in operators {
294 all = all
295 && passes(&column, operator, argument).map_err(|message| {
296 GqlError::validation(message, format!("$.where.{key}"))
297 })?;
298 }
299 all
300 } else {
301 return Err(GqlError::validation(
302 format!("field '{key}' not found in type: '{table}_bool_exp'"),
303 format!("$.where.{key}"),
304 ));
305 }
306 }
307 };
308 if !passed {
309 return Ok(false);
310 }
311 }
312 Ok(true)
313 }
314
315 fn remote_set(&mut self, found: Relation, condition: &Json) -> GqlResult<Rc<HashSet<String>>> {
316 let key = format!("{}|{}|{}", found.target, found.remote, condition.write());
317 if let Some(set) = self.memo.get(&key) {
318 return Ok(Rc::clone(set));
319 }
320 let rows = self.rows(found.target, condition)?;
321 let set: HashSet<String> = rows
322 .iter()
323 .filter_map(|row| row.get(found.remote))
324 .filter(|value| !value.is_null())
325 .map(Json::write)
326 .collect();
327 let set = Rc::new(set);
328 self.memo.insert(key, Rc::clone(&set));
329 Ok(set)
330 }
331
332 fn related(&mut self, found: Relation, local: &Json) -> GqlResult<Vec<Json>> {
334 if local.is_null() {
335 return Ok(Vec::new());
336 }
337 let id = local.as_i64().unwrap_or(0);
338 let subject = self.subject;
339 if found.target == "links" {
340 let Some(address) = self.store.triplet_of(id) else {
341 return Ok(Vec::new());
342 };
343 let query = match found.remote {
344 "id" => TripletQuery::by_index(address),
345 "type_id" => TripletQuery::by_type(address),
346 "from_id" => TripletQuery::by_from(address),
347 _ => TripletQuery::by_to(address),
348 };
349 let triplets = self.store.view(subject, |view| view.each_triplet(query));
350 let mut rows: Vec<LinkRow> = triplets
351 .iter()
352 .filter_map(|t| self.store.row_of(t))
353 .collect();
354 rows.sort_by_key(|row| row.id);
355 return Ok(rows.into_iter().map(LinkRow::to_json).collect());
356 }
357 if let (Some(kind), "link_id") = (ValueKind::of_table(found.target), found.remote) {
358 let Some((row, value)) = self.store.value_of_owner(kind, id) else {
359 return Ok(Vec::new());
360 };
361 return Ok(vec![Self::value_json(row, value)]);
362 }
363 let wanted = local.write();
364 let rows = self.table_rows(found.target)?;
365 Ok(rows
366 .into_iter()
367 .filter(|row| {
368 row.get(found.remote)
369 .is_some_and(|value| value.write() == wanted)
370 })
371 .collect())
372 }
373
374 pub fn project_all(
375 &mut self,
376 table: &str,
377 rows: &[Json],
378 selections: &'a [Selection],
379 ) -> GqlResult<Json> {
380 let mut out = Vec::with_capacity(rows.len());
381 for row in rows {
382 out.push(self.project(table, row, selections)?);
383 }
384 Ok(Json::Array(out))
385 }
386
387 pub fn project(
389 &mut self,
390 table: &str,
391 row: &Json,
392 selections: &'a [Selection],
393 ) -> GqlResult<Json> {
394 let mut out = Vec::new();
395 for field in self.flatten(selections, table)? {
396 let name = field.name.as_str();
397 let value = if name == "__typename" {
398 Json::str(table)
399 } else if let Some(found) = relation(table, name) {
400 let local = row.get(found.local).cloned().unwrap_or(Json::Null);
401 let rows = self.related(found, &local)?;
402 let condition = field.argument("where", self.variables);
403 let mut kept = Vec::with_capacity(rows.len());
404 for candidate in rows {
405 let passes = match &condition {
406 Some(condition) => self.matches(found.target, &candidate, condition)?,
407 None => true,
408 };
409 if passes {
410 kept.push(candidate);
411 }
412 }
413 if found.many {
414 let shaped = self.shape(found.target, kept, field)?;
415 self.project_all(found.target, &shaped, &field.selections)?
416 } else {
417 match kept.first() {
418 Some(first) => self.project(found.target, first, &field.selections)?,
419 None => Json::Null,
420 }
421 }
422 } else if let Some(found) = name
423 .strip_suffix("_aggregate")
424 .and_then(|base| relation(table, base))
425 {
426 let local = row.get(found.local).cloned().unwrap_or(Json::Null);
427 let rows = self.related(found, &local)?;
428 let condition = field.argument("where", self.variables);
429 let mut kept = Vec::new();
430 for candidate in rows {
431 if condition
432 .as_ref()
433 .map_or(Ok(true), |c| self.matches(found.target, &candidate, c))?
434 {
435 kept.push(candidate);
436 }
437 }
438 let shaped = self.shape(found.target, kept, field)?;
439 self.aggregate(found.target, shaped, field)?
440 } else if columns(table).contains(&name)
441 || (table == "links" && name == "value")
442 || row.get(name).is_some()
443 {
444 self.column_value(table, row, name)?
445 } else {
446 return Err(GqlError::validation(
447 format!("field '{name}' not found in type: '{table}'"),
448 format!("$.selectionSet.{table}.selectionSet.{name}"),
449 ));
450 };
451 out.push((field.response_key().to_string(), value));
452 }
453 Ok(Json::Object(out))
454 }
455
456 fn aggregate(&mut self, table: &str, rows: Vec<Json>, field: &'a Field) -> GqlResult<Json> {
458 let mut out = Vec::new();
459 let typename = format!("{table}_aggregate");
460 for item in self.flatten(&field.selections, &typename)? {
461 let value = match item.name.as_str() {
462 "__typename" => Json::String(typename.clone()),
463 "nodes" => self.project_all(table, &rows, &item.selections)?,
464 "aggregate" => self.aggregate_fields(table, &rows, item)?,
465 other => {
466 return Err(GqlError::validation(
467 format!("field '{other}' not found in type: '{typename}'"),
468 format!("$.selectionSet.{}.{other}", field.name),
469 ))
470 }
471 };
472 out.push((item.response_key().to_string(), value));
473 }
474 Ok(Json::Object(out))
475 }
476
477 fn aggregate_fields(
478 &mut self,
479 table: &str,
480 rows: &[Json],
481 field: &'a Field,
482 ) -> GqlResult<Json> {
483 let mut out = Vec::new();
484 let typename = format!("{table}_aggregate_fields");
485 for item in self.flatten(&field.selections, &typename)? {
486 let name = item.name.as_str();
487 let value = match name {
488 "__typename" => Json::String(typename.clone()),
489 "count" => {
490 let selected = item
491 .argument("columns", self.variables)
492 .unwrap_or(Json::Null);
493 let chosen: Vec<&Json> = match &selected {
494 Json::Null => Vec::new(),
495 Json::Array(items) => items.iter().collect(),
496 one => vec![one],
497 };
498 if chosen.is_empty() {
499 Json::Int(rows.len() as i64)
500 } else {
501 let key = |row: &Json| -> Option<String> {
502 let parts: Vec<String> = chosen
503 .iter()
504 .filter_map(|column| column.as_str())
505 .filter_map(|column| {
506 row.get(column).filter(|v| !v.is_null()).map(Json::write)
507 })
508 .collect();
509 (parts.len() == chosen.len()).then(|| parts.join("|"))
510 };
511 let present = rows.iter().filter_map(key);
512 if matches!(
513 item.argument("distinct", self.variables),
514 Some(Json::Bool(true))
515 ) {
516 Json::Int(present.collect::<HashSet<_>>().len() as i64)
517 } else {
518 Json::Int(present.count() as i64)
519 }
520 }
521 }
522 "max" | "min" | "sum" | "avg" => {
523 let inner = format!("{table}_{name}_fields");
524 let mut fields = Vec::new();
525 for column in self.flatten(&item.selections, &inner)? {
526 let value = if column.name == "__typename" {
527 Json::String(inner.clone())
528 } else {
529 summarise(name, rows, &column.name)
530 };
531 fields.push((column.response_key().to_string(), value));
532 }
533 Json::Object(fields)
534 }
535 other => {
536 return Err(GqlError::validation(
537 format!("field '{other}' not found in type: '{typename}'"),
538 format!("$.selectionSet.{}.{other}", field.name),
539 ))
540 }
541 };
542 out.push((item.response_key().to_string(), value));
543 }
544 Ok(Json::Object(out))
545 }
546}
547
548pub fn primary_key(table: &str) -> &'static str {
549 match table {
550 "selectors" => "item_id",
551 "handlers" => "handler_id",
552 "can" => "rule_id",
553 _ => "id",
554 }
555}
556
557fn summarise(operation: &str, rows: &[Json], column: &str) -> Json {
558 let values: Vec<&Json> = rows
559 .iter()
560 .filter_map(|row| row.get(column))
561 .filter(|v| !v.is_null())
562 .collect();
563 if values.is_empty() {
564 return Json::Null;
565 }
566 use std::cmp::Ordering::{Greater, Less};
567 match operation {
568 "max" => values
569 .iter()
570 .fold(values[0], |best, v| {
571 if compare(v, best) == Some(Greater) {
572 v
573 } else {
574 best
575 }
576 })
577 .clone(),
578 "min" => values
579 .iter()
580 .fold(values[0], |best, v| {
581 if compare(v, best) == Some(Less) {
582 v
583 } else {
584 best
585 }
586 })
587 .clone(),
588 _ => {
589 let sum: f64 = values.iter().filter_map(|v| v.as_f64()).sum();
590 let result = if operation == "avg" {
591 sum / values.len() as f64
592 } else {
593 sum
594 };
595 if result.fract() == 0.0 && operation == "sum" {
596 Json::Int(result as i64)
597 } else {
598 Json::Float(result)
599 }
600 }
601 }
602}
603
604fn order_items(order: &Json) -> Vec<Json> {
605 match order {
606 Json::Array(items) => items.clone(),
607 Json::Null => Vec::new(),
608 other => vec![other.clone()],
609 }
610}
611
612fn flatten_order(item: &Json, path: &mut Vec<String>, specs: &mut Vec<(Vec<String>, String)>) {
613 let Json::Object(pairs) = item else {
614 return;
615 };
616 for (key, value) in pairs {
617 path.push(key.clone());
618 match value.as_str() {
619 Some(direction) => specs.push((path.clone(), direction.to_string())),
620 None => flatten_order(value, path, specs),
621 }
622 path.pop();
623 }
624}
625
626fn order_values(left: &Json, right: &Json, direction: &str) -> std::cmp::Ordering {
628 use std::cmp::Ordering::{Equal, Greater, Less};
629 let descending = direction.starts_with("desc");
630 let nulls_first =
631 direction.ends_with("nulls_first") || (descending && !direction.ends_with("nulls_last"));
632 match (left.is_null(), right.is_null()) {
633 (true, true) => Equal,
634 (true, false) => {
635 if nulls_first {
636 Less
637 } else {
638 Greater
639 }
640 }
641 (false, true) => {
642 if nulls_first {
643 Greater
644 } else {
645 Less
646 }
647 }
648 _ => {
649 let found = compare(left, right).unwrap_or(Equal);
650 if descending {
651 found.reverse()
652 } else {
653 found
654 }
655 }
656 }
657}