1use anyhow::Result;
7use std::collections::HashMap;
8
9use crate::changes_simplifier::simplify_generic_changes;
10use crate::error::LinkError;
11use crate::link::GenericLink as Link;
12use crate::link_reference_validator::GenericLinkReferenceValidator;
13use crate::lino_link::LinoLink;
14use crate::named_type_links::NamedTypeLinks;
15use crate::query_address::QueryAddress;
16use crate::query_types::{GenericResolvedLink as ResolvedLink, Pattern};
17
18mod matching;
20mod mutations;
22mod resolution;
24
25pub type Changes<T = u32> = Vec<(Option<Link<T>>, Option<Link<T>>)>;
28
29type ResolvedChange<T> = (Option<ResolvedLink<T>>, Option<ResolvedLink<T>>);
30
31pub type QueryProcessor = GenericQueryProcessor<u32>;
33
34pub struct GenericQueryProcessor<T: QueryAddress> {
37 address: std::marker::PhantomData<T>,
38 trace: bool,
39 auto_create_missing_references: bool,
40 validate_references: bool,
41}
42
43impl<T: QueryAddress> GenericQueryProcessor<T> {
44 pub fn new(trace: bool) -> Self {
46 Self {
47 address: std::marker::PhantomData,
48 trace,
49 auto_create_missing_references: false,
50 validate_references: true,
51 }
52 }
53
54 pub fn with_auto_create_missing_references(
55 mut self,
56 auto_create_missing_references: bool,
57 ) -> Self {
58 self.auto_create_missing_references = auto_create_missing_references;
59 self
60 }
61
62 pub fn process_query(
69 &self,
70 storage: &mut impl NamedTypeLinks<T>,
71 query: &str,
72 ) -> Result<Changes<T>> {
73 let changes = self.process_query_raw(storage, query)?;
74 Ok(self.simplify_changes_list(&changes))
75 }
76
77 fn process_query_raw(
80 &self,
81 storage: &mut impl NamedTypeLinks<T>,
82 query: &str,
83 ) -> Result<Changes<T>> {
84 if storage
85 .query_limits()
86 .is_some_and(|limits| query.len() > limits.max_bytes)
87 {
88 return Err(LinkError::QueryError("query byte limit exceeded".into()).into());
89 }
90 self.trace_msg(&format!("[ProcessQuery] Query: \"{}\"", query));
91
92 let query = query.trim();
93 if query.is_empty() {
94 self.trace_msg("[ProcessQuery] Query is empty, returning.");
95 return Ok(vec![]);
96 }
97
98 let parsed_links = crate::query_parser::parse_for::<T>(query, storage.query_limits())?;
99
100 self.trace_msg(&format!(
101 "[ProcessQuery] Parser returned {} top-level link(s).",
102 parsed_links.len()
103 ));
104
105 if parsed_links.is_empty() {
106 self.trace_msg("[ProcessQuery] No top-level parsed links found, returning.");
107 return Ok(vec![]);
108 }
109
110 let (restriction_link, substitution_link) = match &parsed_links[0].values {
113 Some(values) if values.len() >= 2 => (&values[0], &values[1]),
114 _ if parsed_links.len() >= 2 => (&parsed_links[0], &parsed_links[1]),
115 _ => {
116 self.trace_msg("[ProcessQuery] Query has fewer than 2 links, returning.");
117 return Ok(vec![]);
118 }
119 };
120
121 self.process_lino_raw(storage, restriction_link, substitution_link)
122 }
123
124 pub(crate) fn preview(
128 &self,
129 storage: &mut impl NamedTypeLinks<T>,
130 restriction_link: &LinoLink,
131 substitution_link: &LinoLink,
132 ) -> Result<()> {
133 let preview = Self {
134 address: std::marker::PhantomData,
135 trace: self.trace,
136 auto_create_missing_references: self.auto_create_missing_references,
137 validate_references: false,
138 };
139 let changes = preview.process_lino_raw(storage, restriction_link, substitution_link)?;
140 if storage.query_limits().is_some() {
141 let mut budget =
144 crate::query_reply_budget::QueryReplyBudget::new(storage.query_limits());
145 for (before, after) in preview.simplify_changes_list(&changes) {
146 for link in [before, after].into_iter().flatten() {
147 for id in [link.index, link.source, link.target] {
148 budget.reference(storage, id)?;
149 }
150 }
151 }
152 }
153 Ok(())
154 }
155
156 fn process_lino_raw(
157 &self,
158 storage: &mut impl NamedTypeLinks<T>,
159 restriction_link: &LinoLink,
160 substitution_link: &LinoLink,
161 ) -> Result<Changes<T>> {
162 self.trace_msg(&format!(
163 "[ProcessQuery] Restriction link => Id={:?} Values.Count={}",
164 restriction_link.id,
165 restriction_link.values_count()
166 ));
167 self.trace_msg(&format!(
168 "[ProcessQuery] Substitution link => Id={:?} Values.Count={}",
169 substitution_link.id,
170 substitution_link.values_count()
171 ));
172
173 let mut changes_list = Vec::new();
174
175 if restriction_link.is_empty() && substitution_link.is_empty() {
177 self.trace_msg(
178 "[ProcessQuery] Restriction & substitution both empty => no operation, returning.",
179 );
180 return Ok(vec![]);
181 }
182
183 if restriction_link.is_empty() && !substitution_link.is_empty() {
185 self.trace_msg(
186 "[ProcessQuery] No restriction, but substitution is non-empty => creation scenario.",
187 );
188 if let Some(values) = &substitution_link.values {
189 changes_list.extend(self.validate_links_exist_or_will_be_created(
190 storage,
191 restriction_link,
192 substitution_link,
193 )?);
194
195 for link_to_create in values {
196 let created_id =
197 self.ensure_link_created(storage, link_to_create, &mut changes_list)?;
198 self.trace_msg(&format!(
199 "[ProcessQuery] Created link ID #{} from substitution pattern.",
200 created_id
201 ));
202 }
203 }
204 storage.save()?;
205 return Ok(changes_list);
206 }
207
208 if !restriction_link.is_empty() && substitution_link.is_empty() {
210 self.trace_msg(
211 "[ProcessQuery] Restriction non-empty, substitution empty => deletion scenario.",
212 );
213 changes_list.extend(self.validate_links_exist_or_will_be_created(
214 storage,
215 restriction_link,
216 substitution_link,
217 )?);
218
219 let restriction_patterns = self.patterns_from_lino(restriction_link);
220 let mut links_to_delete = Vec::new();
221 for pattern in &restriction_patterns {
222 links_to_delete.extend(self.matched_links(storage, pattern, &HashMap::new())?);
223 }
224 links_to_delete.sort_by_key(|link| link.index);
225 links_to_delete.dedup_by_key(|link| link.index);
226
227 for link in links_to_delete {
228 if storage.exists(link.index) {
229 self.delete_observed(storage, link.index, &mut changes_list)?;
230 self.trace_msg(&format!("[ProcessQuery] Deleted link ID #{}.", link.index));
231 }
232 }
233 storage.save()?;
234 return Ok(changes_list);
235 }
236
237 self.trace_msg(
239 "[ProcessQuery] Both restriction and substitution non-empty => update/mixed scenario.",
240 );
241
242 let restriction_patterns = self.patterns_from_lino(restriction_link);
243 let substitution_patterns = self.patterns_from_lino(substitution_link);
244 changes_list.extend(self.validate_links_exist_or_will_be_created(
245 storage,
246 restriction_link,
247 substitution_link,
248 )?);
249 let solutions = self.find_all_solutions(storage, &restriction_patterns)?;
250
251 if solutions.is_empty() {
252 self.trace_msg("[ProcessQuery] No solutions found => returning.");
253 if !changes_list.is_empty() {
254 storage.save()?;
255 }
256 return Ok(changes_list);
257 }
258
259 let mut all_solutions_no_operation = true;
260 for solution in &solutions {
261 if !self.solution_is_no_operation(
262 storage,
263 solution,
264 &restriction_patterns,
265 &substitution_patterns,
266 )? {
267 all_solutions_no_operation = false;
268 break;
269 }
270 }
271
272 if all_solutions_no_operation {
273 for solution in &solutions {
274 for pattern in &restriction_patterns {
275 for link in self.matched_links(storage, pattern, solution)? {
276 if !changes_list.contains(&(Some(link), Some(link))) {
277 changes_list.push((Some(link), Some(link)));
278 }
279 }
280 }
281 }
282 return Ok(changes_list);
283 }
284
285 let mut all_planned_operations = Vec::new();
286 for solution in &solutions {
287 let restriction_links = self.resolve_patterns(
288 storage,
289 &restriction_patterns,
290 solution,
291 false,
292 &mut changes_list,
293 )?;
294 let substitution_links = self.resolve_patterns(
295 storage,
296 &substitution_patterns,
297 solution,
298 true,
299 &mut changes_list,
300 )?;
301 let operations = self.determine_operations(&restriction_links, &substitution_links);
302 Self::check_result_count(
303 storage,
304 all_planned_operations
305 .len()
306 .saturating_add(operations.len()),
307 )?;
308 all_planned_operations.extend(operations);
309 }
310
311 let intended_final_states = Self::intended_final_states(&all_planned_operations);
312
313 for (before, after) in all_planned_operations {
314 self.apply_operation(storage, before, after, &mut changes_list)?;
315 }
316
317 self.restore_unexpected_deletions(storage, &intended_final_states, &mut changes_list)?;
318
319 storage.save()?;
320
321 Ok(changes_list)
322 }
323
324 fn validate_links_exist_or_will_be_created(
325 &self,
326 storage: &mut impl NamedTypeLinks<T>,
327 restriction: &LinoLink,
328 substitution: &LinoLink,
329 ) -> Result<Changes<T>> {
330 if !self.validate_references {
331 return Ok(Vec::new());
332 }
333 GenericLinkReferenceValidator::<T>::for_query(
334 self.trace,
335 self.auto_create_missing_references,
336 )
337 .validate_with_plan(
338 storage,
339 restriction.values.as_deref().unwrap_or(&[]),
340 substitution.values.as_deref().unwrap_or(&[]),
341 |storage| storage.reserve_query_allocations(self, restriction, substitution),
342 )
343 }
344
345 fn patterns_from_lino(&self, lino_link: &LinoLink) -> Vec<Pattern> {
346 let mut patterns = lino_link
347 .values
348 .as_ref()
349 .map(|values| {
350 values
351 .iter()
352 .map(Self::create_pattern_from_lino)
353 .collect::<Vec<_>>()
354 })
355 .unwrap_or_default();
356
357 if lino_link.id.is_some() {
358 patterns.insert(0, Self::create_pattern_from_lino(lino_link));
359 }
360
361 patterns
362 }
363
364 fn create_pattern_from_lino(lino_link: &LinoLink) -> Pattern {
365 let index = lino_link.id.clone().unwrap_or_default();
366 match &lino_link.values {
367 Some(values) if values.len() == 2 => Pattern::new(
368 index,
369 Some(Self::create_pattern_from_lino(&values[0])),
370 Some(Self::create_pattern_from_lino(&values[1])),
371 ),
372 _ => Pattern::new(index, None, None),
373 }
374 }
375
376 fn find_all_solutions(
377 &self,
378 storage: &mut impl NamedTypeLinks<T>,
379 patterns: &[Pattern],
380 ) -> Result<Vec<HashMap<String, T>>> {
381 let mut partial_solutions = vec![HashMap::new()];
382
383 for pattern in patterns {
384 let mut new_solutions = Vec::new();
385 let mut bindings = 0usize;
386 let mut bytes = 0usize;
387 for solution in &partial_solutions {
388 for match_solution in self.match_pattern(storage, pattern, solution)? {
389 if Self::solutions_are_compatible(solution, &match_solution) {
390 let (mut count, mut size) = Self::solution_cost(solution);
392 for key in match_solution
393 .keys()
394 .filter(|key| !solution.contains_key(*key))
395 {
396 count = count.saturating_add(1);
397 size = size.saturating_add(Self::binding_cost(key));
398 }
399 Self::check_solution_capacity(
400 storage,
401 new_solutions.len() + 1,
402 bindings.saturating_add(count),
403 bytes.saturating_add(size),
404 )?;
405 let mut combined = solution.clone();
406 combined.extend(match_solution);
407 bindings = bindings.saturating_add(count);
408 bytes = bytes.saturating_add(size);
409 new_solutions.push(combined);
410 }
411 }
412 }
413 partial_solutions = new_solutions;
414 if partial_solutions.is_empty() {
415 break;
416 }
417 }
418
419 Ok(partial_solutions)
420 }
421
422 fn check_result_count(storage: &impl NamedTypeLinks<T>, count: usize) -> Result<()> {
423 if storage
424 .query_limits()
425 .is_some_and(|limits| count > limits.max_results)
426 {
427 return Err(LinkError::QueryError("query result limit exceeded".into()).into());
428 }
429 Ok(())
430 }
431
432 fn binding_cost(key: &str) -> usize {
433 key.len().saturating_add(64 + std::mem::size_of::<T>())
435 }
436
437 fn solution_cost(solution: &HashMap<String, T>) -> (usize, usize) {
438 (
439 solution.len(),
440 solution.keys().fold(0usize, |bytes, key| {
441 bytes.saturating_add(Self::binding_cost(key))
442 }),
443 )
444 }
445
446 fn check_solution_capacity(
447 storage: &impl NamedTypeLinks<T>,
448 results: usize,
449 bindings: usize,
450 bytes: usize,
451 ) -> Result<()> {
452 Self::check_result_count(storage, results)?;
453 if storage.query_limits().is_some_and(|limits| {
454 bindings > limits.max_bindings || bytes > limits.max_binding_bytes
455 }) {
456 return Err(LinkError::QueryError("query binding memory limit exceeded".into()).into());
457 }
458 Ok(())
459 }
460
461 fn solutions_are_compatible(
462 existing: &HashMap<String, T>,
463 new_assignments: &HashMap<String, T>,
464 ) -> bool {
465 new_assignments
466 .iter()
467 .all(|(key, value)| existing.get(key).is_none_or(|existing| existing == value))
468 }
469
470 fn determine_operations(
471 &self,
472 restrictions: &[ResolvedLink<T>],
473 substitutions: &[ResolvedLink<T>],
474 ) -> Vec<ResolvedChange<T>> {
475 let mut operations = Vec::new();
476 let mut restriction_by_index = HashMap::new();
477 let mut substitution_by_index = HashMap::new();
478 let mut wildcard_restrictions = Vec::new();
479 let mut wildcard_substitutions = Vec::new();
480
481 for restriction in restrictions {
482 if Self::is_normal_index(restriction.index) {
483 restriction_by_index.insert(restriction.index, restriction.clone());
484 } else {
485 wildcard_restrictions.push(restriction.clone());
486 }
487 }
488
489 for substitution in substitutions {
490 if Self::is_normal_index(substitution.index) {
491 substitution_by_index.insert(substitution.index, substitution.clone());
492 } else {
493 wildcard_substitutions.push(substitution.clone());
494 }
495 }
496
497 let mut all_indices = restriction_by_index
498 .keys()
499 .chain(substitution_by_index.keys())
500 .copied()
501 .collect::<Vec<_>>();
502 all_indices.sort_unstable();
503 all_indices.dedup();
504
505 for index in all_indices {
506 operations.push((
507 restriction_by_index.get(&index).cloned(),
508 substitution_by_index.get(&index).cloned(),
509 ));
510 }
511
512 operations.extend(
513 wildcard_restrictions
514 .into_iter()
515 .map(|restriction| (Some(restriction), None)),
516 );
517 operations.extend(
518 wildcard_substitutions
519 .into_iter()
520 .map(|substitution| (None, Some(substitution))),
521 );
522
523 operations
524 }
525
526 fn apply_operation(
527 &self,
528 storage: &mut impl NamedTypeLinks<T>,
529 before: Option<ResolvedLink<T>>,
530 after: Option<ResolvedLink<T>>,
531 changes: &mut Changes<T>,
532 ) -> Result<()> {
533 match (before, after) {
534 (Some(before), None) => {
535 let mut links = self.links_matching_definition(storage, &before)?;
536 links.sort_by_key(|link| link.index);
537 links.dedup_by_key(|link| link.index);
538 for link in links {
539 if storage.exists(link.index) {
540 self.delete_observed(storage, link.index, changes)?;
541 }
542 }
543 }
544 (None, Some(after)) => {
545 self.create_or_update_resolved_link(storage, &after, changes)?;
546 }
547 (Some(before), Some(after)) => {
548 if before.index == after.index && storage.exists(before.index) {
549 let stored = storage.get_link(before.index).unwrap();
550 let source = Self::resolve_unspecified(after.source, stored.source);
553 let target = Self::resolve_unspecified(after.target, stored.target);
554 if stored.source != source || stored.target != target {
555 self.update_observed(storage, before.index, source, target, changes)?;
559 } else {
560 changes.push((Some(stored), Some(stored)));
561 }
562 if let Some(name) = &after.name {
563 storage.set_name(before.index, crate::query_parser::name(name))?;
564 }
565 } else {
566 self.apply_operation(storage, Some(before), None, changes)?;
567 self.apply_operation(storage, None, Some(after), changes)?;
568 }
569 }
570 (None, None) => {}
571 }
572
573 Ok(())
574 }
575
576 fn links_matching_definition(
577 &self,
578 storage: &mut impl NamedTypeLinks<T>,
579 definition: &ResolvedLink<T>,
580 ) -> Result<Vec<Link<T>>> {
581 Ok(storage
582 .all_links()
583 .into_iter()
584 .filter(|link| {
585 (definition.index == T::from_byte(0)
586 || Self::is_any(definition.index)
587 || link.index == definition.index)
588 && (Self::is_any(definition.source) || link.source == definition.source)
589 && (Self::is_any(definition.target) || link.target == definition.target)
590 })
591 .collect())
592 }
593
594 fn assign_variable(id: &str, value: T, assignments: &mut HashMap<String, T>) {
595 if Self::is_variable(id) {
598 assignments.insert(id.to_string(), value);
599 }
600 }
601
602 fn is_variable(identifier: &str) -> bool {
603 !identifier.is_empty() && identifier.starts_with('$')
604 }
605
606 fn is_any(value: T) -> bool {
607 value == T::MAX
608 }
609
610 fn resolve_unspecified(value: T, existing: T) -> T {
624 if Self::is_any(value) {
625 existing
626 } else {
627 value
628 }
629 }
630
631 fn search_unspecified(storage: &mut impl NamedTypeLinks<T>, source: T, target: T) -> Option<T> {
640 if !Self::is_any(source) && !Self::is_any(target) {
641 return storage.search(source, target);
642 }
643 storage
644 .all_links()
645 .into_iter()
646 .filter(|link| {
647 (Self::is_any(source) || link.source == source)
648 && (Self::is_any(target) || link.target == target)
649 })
650 .map(|link| link.index)
651 .min()
652 }
653
654 fn is_normal_index(value: T) -> bool {
655 value != T::from_byte(0) && !Self::is_any(value)
656 }
657
658 fn is_numeric_or_wildcard(identifier: &str) -> bool {
659 identifier == "*" || identifier.parse::<T>().is_ok()
660 }
661
662 fn simplify_changes_list(&self, changes: &Changes<T>) -> Changes<T> {
672 let to_simplify: Vec<(Link<T>, Link<T>)> = changes
673 .iter()
674 .map(|(before, after)| {
675 (
676 before.unwrap_or_else(Link::null),
677 after.unwrap_or_else(Link::null),
678 )
679 })
680 .collect();
681
682 simplify_generic_changes(to_simplify)
683 .into_iter()
684 .map(|(before, after)| {
685 (
686 (!before.is_null()).then_some(before),
687 (!after.is_null()).then_some(after),
688 )
689 })
690 .collect()
691 }
692
693 fn trace_msg(&self, msg: &str) {
695 if self.trace {
696 crate::diagnostics::stderr!("{}", msg);
697 }
698 }
699}