1use anyhow::Result;
9use std::collections::HashSet;
10
11use crate::error::LinkError;
12use crate::link::GenericLink as Link;
13use crate::lino_link::LinoLink;
14use crate::named_type_links::NamedTypeLinks;
15use crate::query_address::QueryAddress;
16use crate::query_processor::Changes;
17
18pub type LinkReferenceValidator = GenericLinkReferenceValidator<u32>;
20
21pub struct GenericLinkReferenceValidator<T: QueryAddress> {
22 address: std::marker::PhantomData<T>,
23 trace: bool,
24 auto_create_missing_references: bool,
25 enveloped_names: bool,
26}
27
28#[derive(Debug, Default)]
29struct LinkReferencePlan<T> {
30 numeric_ids_to_be_created: HashSet<T>,
31 names_to_be_created: HashSet<String>,
32 composite_pairs_to_be_created: HashSet<(T, T)>,
39 missing_references: Vec<MissingLinkReference<T>>,
40 missing_reference_keys: HashSet<String>,
41}
42
43impl<T: QueryAddress> LinkReferencePlan<T> {
44 fn add_missing_reference(&mut self, reference: MissingLinkReference<T>) {
45 let key = reference.key();
46 if self.missing_reference_keys.insert(key) {
47 self.missing_references.push(reference);
48 }
49 }
50}
51
52#[derive(Debug, Clone)]
53struct MissingLinkReference<T> {
54 identifier: String,
55 pattern_type: &'static str,
56 numeric_id: Option<T>,
57}
58
59impl<T: QueryAddress> MissingLinkReference<T> {
60 fn key(&self) -> String {
61 self.numeric_id
62 .map(|id| format!("id:{id}"))
63 .unwrap_or_else(|| format!("name:{}", self.identifier))
64 }
65}
66
67impl<T: QueryAddress> GenericLinkReferenceValidator<T> {
68 pub fn new(trace: bool, auto_create_missing_references: bool) -> Self {
69 Self {
70 address: std::marker::PhantomData,
71 trace,
72 auto_create_missing_references,
73 enveloped_names: false,
74 }
75 }
76
77 pub(crate) fn for_query(trace: bool, auto_create_missing_references: bool) -> Self {
78 Self {
79 enveloped_names: true,
80 ..Self::new(trace, auto_create_missing_references)
81 }
82 }
83
84 fn name<'a>(&self, identifier: &'a str) -> &'a str {
85 if self.enveloped_names {
86 crate::query_parser::name(identifier)
87 } else {
88 identifier
89 }
90 }
91
92 pub fn validate_links_exist_or_will_be_created(
94 &self,
95 storage: &mut impl NamedTypeLinks<T>,
96 restriction_patterns: &[LinoLink],
97 substitution_patterns: &[LinoLink],
98 ) -> Result<Changes<T>> {
99 self.validate_with_plan(storage, restriction_patterns, substitution_patterns, |_| {
100 Ok(None)
101 })
102 }
103
104 pub(crate) fn validate_with_plan<S: NamedTypeLinks<T>>(
105 &self,
106 storage: &mut S,
107 restriction_patterns: &[LinoLink],
108 substitution_patterns: &[LinoLink],
109 mut reserve: impl FnMut(&mut S) -> Result<Option<HashSet<T>>>,
110 ) -> Result<Changes<T>> {
111 self.trace_msg("[ValidateLinksExistOrWillBeCreated] Starting validation");
112
113 let mut created = Vec::new();
114 loop {
115 let reserved = reserve(storage)?;
116 let plan = self.plan_references(
117 storage,
118 restriction_patterns,
119 substitution_patterns,
120 reserved,
121 )?;
122 if plan.missing_references.is_empty() {
123 self.trace_msg("[ValidateLinksExistOrWillBeCreated] Validation completed");
124 return Ok(created);
125 }
126
127 if !self.auto_create_missing_references {
128 let missing = &plan.missing_references[0];
129 return Err(LinkError::QueryError(format!(
130 "Invalid reference to non-existent link '{}' in {} pattern. Link '{}' does not exist and will not be created by this operation. Use --auto-create-missing-references to create missing references as point links.",
131 self.name(&missing.identifier), missing.pattern_type, self.name(&missing.identifier)
132 ))
133 .into());
134 }
135
136 created.extend(self.auto_create_missing_references(storage, &plan)?);
139 }
140 }
141
142 fn plan_references(
143 &self,
144 storage: &mut impl NamedTypeLinks<T>,
145 restriction_patterns: &[LinoLink],
146 substitution_patterns: &[LinoLink],
147 reserved: Option<HashSet<T>>,
148 ) -> Result<LinkReferencePlan<T>> {
149 let mut plan = self.build_link_reference_plan(storage, substitution_patterns, reserved)?;
150 self.trace_msg(&format!(
151 "[ValidateLinksExistOrWillBeCreated] Numeric links to be created: {:?}",
152 plan.numeric_ids_to_be_created
153 ));
154 self.trace_msg(&format!(
155 "[ValidateLinksExistOrWillBeCreated] Named links to be created: {:?}",
156 plan.names_to_be_created
157 ));
158
159 self.collect_missing_references(
160 storage,
161 &mut plan,
162 restriction_patterns,
163 false,
164 "restriction",
165 )?;
166 self.collect_missing_references(
167 storage,
168 &mut plan,
169 substitution_patterns,
170 true,
171 "substitution",
172 )?;
173 Ok(plan)
174 }
175
176 fn build_link_reference_plan(
177 &self,
178 storage: &mut impl NamedTypeLinks<T>,
179 substitution_patterns: &[LinoLink],
180 reserved: Option<HashSet<T>>,
181 ) -> Result<LinkReferencePlan<T>> {
182 let mut plan = LinkReferencePlan::default();
183 let mut anonymous_links = 0;
184 for pattern in substitution_patterns {
185 Self::collect_definitions(pattern, &mut plan, &mut anonymous_links);
186 }
187 if let Some(ids) = reserved {
188 plan.numeric_ids_to_be_created.extend(ids);
189 } else {
190 plan.numeric_ids_to_be_created
191 .extend(storage.next_created_addresses(anonymous_links)?);
192 }
193 Ok(plan)
194 }
195
196 fn collect_definitions(
200 pattern: &LinoLink,
201 plan: &mut LinkReferencePlan<T>,
202 anonymous_links: &mut usize,
203 ) {
204 if let Some(values) = &pattern.values {
205 for sub_pattern in values {
206 Self::collect_definitions(sub_pattern, plan, anonymous_links);
207 }
208 }
209 if !Self::is_composite_lino(pattern) {
210 return;
211 }
212 let Some(identifier) = Self::concrete_identifier(pattern.id.as_deref()) else {
213 *anonymous_links += 1;
214 return;
215 };
216 match identifier.parse::<T>() {
217 Ok(link_id) => plan.numeric_ids_to_be_created.insert(link_id),
218 Err(_) => plan.names_to_be_created.insert(identifier),
219 };
220 let values = pattern.values.as_deref().unwrap_or_default();
221 if let (Some(source), Some(target)) = (
222 Self::concrete_numeric_identifier(values[0].id.as_deref()),
223 Self::concrete_numeric_identifier(values[1].id.as_deref()),
224 ) {
225 plan.composite_pairs_to_be_created.insert((source, target));
226 }
227 }
228
229 fn collect_missing_references(
230 &self,
231 storage: &mut impl NamedTypeLinks<T>,
232 plan: &mut LinkReferencePlan<T>,
233 patterns: &[LinoLink],
234 is_substitution: bool,
235 pattern_type: &'static str,
236 ) -> Result<()> {
237 for pattern in patterns {
238 self.collect_missing_references_in_pattern(
239 storage,
240 plan,
241 pattern,
242 is_substitution,
243 pattern_type,
244 )?;
245 }
246 Ok(())
247 }
248
249 fn collect_missing_references_in_pattern(
250 &self,
251 storage: &mut impl NamedTypeLinks<T>,
252 plan: &mut LinkReferencePlan<T>,
253 pattern: &LinoLink,
254 is_substitution: bool,
255 pattern_type: &'static str,
256 ) -> Result<()> {
257 let pattern_id_is_definition = is_substitution
258 && Self::is_composite_lino(pattern)
259 && Self::concrete_identifier(pattern.id.as_deref()).is_some();
260
261 if !pattern_id_is_definition {
262 if let Some(identifier) = Self::concrete_identifier(pattern.id.as_deref()) {
263 self.validate_reference_identifier(storage, plan, &identifier, pattern_type)?;
264 }
265 }
266
267 if let Some(values) = &pattern.values {
268 for sub_pattern in values {
269 self.collect_missing_references_in_pattern(
270 storage,
271 plan,
272 sub_pattern,
273 is_substitution,
274 pattern_type,
275 )?;
276 }
277 }
278 Ok(())
279 }
280
281 fn validate_reference_identifier(
282 &self,
283 storage: &mut impl NamedTypeLinks<T>,
284 plan: &mut LinkReferencePlan<T>,
285 identifier: &str,
286 pattern_type: &'static str,
287 ) -> Result<()> {
288 if let Ok(link_id) = identifier.parse::<T>() {
289 if !storage.reference_exists(link_id)
290 && !plan.numeric_ids_to_be_created.contains(&link_id)
291 {
292 plan.add_missing_reference(MissingLinkReference {
293 identifier: identifier.to_string(),
294 pattern_type,
295 numeric_id: Some(link_id),
296 });
297 return Ok(());
298 }
299 self.trace_msg(&format!(
300 "[ValidateReferencesInPattern] Link {link_id} reference validated in {pattern_type} pattern"
301 ));
302 return Ok(());
303 }
304
305 if storage.get_by_name(self.name(identifier))?.is_none()
306 && !plan.names_to_be_created.contains(identifier)
307 {
308 plan.add_missing_reference(MissingLinkReference {
309 identifier: identifier.to_string(),
310 pattern_type,
311 numeric_id: None,
312 });
313 return Ok(());
314 }
315
316 self.trace_msg(&format!(
317 "[ValidateReferencesInPattern] Named link '{identifier}' reference validated in {pattern_type} pattern"
318 ));
319 Ok(())
320 }
321
322 fn auto_create_missing_references(
331 &self,
332 storage: &mut impl NamedTypeLinks<T>,
333 plan: &LinkReferencePlan<T>,
334 ) -> Result<Changes<T>> {
335 let missing_references = &plan.missing_references;
336 let mut created = Vec::new();
337 let mut numeric_references = missing_references
338 .iter()
339 .filter_map(|reference| reference.numeric_id)
340 .collect::<Vec<_>>();
341 numeric_references.sort_unstable();
342 numeric_references.dedup();
343
344 for link_id in numeric_references {
345 if storage.reference_exists(link_id) {
346 continue;
347 }
348
349 self.trace_msg(&format!(
350 "[ValidateLinksExistOrWillBeCreated] Auto-creating missing numeric reference {link_id}."
351 ));
352 storage.try_ensure_created(link_id)?;
353 let placeholder = Link::new(link_id, T::from_byte(0), T::from_byte(0));
354 created.push((None, Some(placeholder)));
355 if plan
356 .composite_pairs_to_be_created
357 .contains(&(link_id, link_id))
358 {
359 self.trace_msg(&format!(
360 "[ValidateLinksExistOrWillBeCreated] Link {link_id} exists as a placeholder because ({link_id}, {link_id}) is defined by the substitution."
361 ));
362 continue;
363 }
364 storage.update(link_id, link_id, link_id)?;
365 created.push((Some(placeholder), storage.get_link(link_id)));
366 }
367
368 let mut named_references = missing_references
369 .iter()
370 .filter(|reference| reference.numeric_id.is_none())
371 .map(|reference| reference.identifier.clone())
372 .collect::<Vec<_>>();
373 named_references.sort();
374 named_references.dedup();
375
376 for name in named_references {
377 if storage.get_by_name(self.name(&name))?.is_some() {
378 continue;
379 }
380
381 self.trace_msg(&format!(
382 "[ValidateLinksExistOrWillBeCreated] Auto-creating missing named reference '{name}' as point link."
383 ));
384 let link_id = storage.get_or_create_named(self.name(&name))?;
385 created.push((None, storage.get_link(link_id)));
386 }
387
388 Ok(created)
389 }
390
391 fn is_composite_lino(lino_link: &LinoLink) -> bool {
392 lino_link.values_count() == 2
393 }
394
395 fn concrete_numeric_identifier(id: Option<&str>) -> Option<T> {
396 Self::concrete_identifier(id).and_then(|identifier| identifier.parse::<T>().ok())
397 }
398
399 fn concrete_identifier(id: Option<&str>) -> Option<String> {
400 let identifier = id?.trim_end_matches(':');
401 if identifier.is_empty() || identifier == "*" || identifier.starts_with('$') {
402 None
403 } else {
404 Some(identifier.to_string())
405 }
406 }
407
408 fn trace_msg(&self, msg: &str) {
409 if self.trace {
410 crate::diagnostics::stderr!("{}", msg);
411 }
412 }
413}