Skip to main content

qualia_core_db/q42/chebi_query/
query.rs

1//! Core ChEBI query operations over an in-memory Quin slice (AST-05).
2
3use crate::q_hash;
4use crate::NQuin;
5
6use super::access::normalize_accession_query;
7use super::error::QueryError;
8use super::scan::{
9    accession_from_records, count_release, resolve_licence_note, view_subject, PredHashes,
10};
11use super::types::{
12    ChemicalHit, EvidenceHit, QueryLimits, RelationHit, ReleaseDescription, Uncertainty,
13};
14use crate::q42::chebi_parse::ChebiRecord;
15
16/// Describe one release / asset slice: counts + licence obligation stub.
17///
18/// Empty Quin input yields zero counts (still returns a description). Licence
19/// note comes from `licence_note` when non-empty, otherwise the catalogue
20/// `chebi` stub.
21pub fn describe_release(
22    quins: &[NQuin],
23    release_label: &str,
24    licence_note: &str,
25) -> ReleaseDescription {
26    let preds = PredHashes::load();
27    let release_hash = q_hash(release_label);
28    let (record_count, quin_count) = count_release(quins, &preds, release_hash);
29    let note = resolve_licence_note(licence_note);
30    let licence_obligation_present = !note.is_empty();
31    ReleaseDescription {
32        release_label: release_label.to_owned(),
33        release_hash,
34        record_count,
35        quin_count,
36        licence_note: note,
37        licence_obligation_present,
38    }
39}
40
41/// Resolve a chemical by accession (`CHEBI:{id}`) or bare numeric id into `out`.
42///
43/// Fail-closed:
44/// - empty quins → [`QueryError::EmptyInput`]
45/// - empty / bad query → [`QueryError::EmptyQuery`]
46/// - zero hits → [`QueryError::NotFound`]
47/// - more than one distinct (subject, context) → [`QueryError::Ambiguous`]
48/// - capacity / max_hits too small → [`QueryError::LimitExceeded`]
49pub fn resolve_chemical_into(
50    quins: &[NQuin],
51    query: &str,
52    licence_note: &str,
53    limits: QueryLimits,
54    records: Option<&[ChebiRecord]>,
55    out: &mut [ChemicalHit],
56) -> Result<usize, QueryError> {
57    let limits = limits.validate()?;
58    if quins.is_empty() {
59        return Err(QueryError::EmptyInput);
60    }
61    let accession = normalize_accession_query(query).ok_or(QueryError::EmptyQuery)?;
62    let subject = q_hash(&accession);
63    let preds = PredHashes::load();
64    let note = resolve_licence_note(licence_note);
65
66    let mut matches = [(0u64, 0u64); 32];
67    let mut match_n = 0usize;
68    for q in quins {
69        if q.predicate != preds.accession || q.subject != subject {
70            continue;
71        }
72        let pair = (q.subject, q.context);
73        if matches[..match_n].contains(&pair) {
74            continue;
75        }
76        if match_n >= matches.len() {
77            return Err(QueryError::LimitExceeded {
78                limit: matches.len(),
79                needed: match_n + 1,
80            });
81        }
82        matches[match_n] = pair;
83        match_n += 1;
84    }
85
86    if match_n == 0 {
87        return Err(QueryError::NotFound);
88    }
89    if match_n > 1 {
90        return Err(QueryError::Ambiguous { hits: match_n });
91    }
92
93    let capacity = out.len().min(limits.max_hits);
94    if capacity == 0 {
95        return Err(QueryError::LimitExceeded {
96            limit: 0,
97            needed: 1,
98        });
99    }
100
101    let (subj, ctx) = matches[0];
102    let view = view_subject(quins, &preds, subj, Some(ctx));
103    let surface = accession_from_records(records, subj).unwrap_or(accession);
104    out[0] = ChemicalHit {
105        subject_hash: view.subject_hash,
106        name_hash: view.name_hash,
107        parent_hash: view.parent_hash,
108        release_hash: if view.release_hash != 0 {
109            view.release_hash
110        } else {
111            ctx
112        },
113        source_line: view.source_line,
114        uncertainty: view.uncertainty(),
115        accession: surface,
116        licence_note: note,
117    };
118    Ok(1)
119}
120
121/// Look up parent edges (`chebi:hasParent`) for a child accession.
122pub fn lookup_parents_into(
123    quins: &[NQuin],
124    child_accession: &str,
125    licence_note: &str,
126    limits: QueryLimits,
127    records: Option<&[ChebiRecord]>,
128    out: &mut [RelationHit],
129) -> Result<usize, QueryError> {
130    let limits = limits.validate()?;
131    if quins.is_empty() {
132        return Err(QueryError::EmptyInput);
133    }
134    let accession = normalize_accession_query(child_accession).ok_or(QueryError::EmptyQuery)?;
135    let child = q_hash(&accession);
136    let preds = PredHashes::load();
137    let note = resolve_licence_note(licence_note);
138    let capacity = out.len().min(limits.max_hits);
139
140    let mut written = 0usize;
141    let mut needed = 0usize;
142    for q in quins {
143        if q.predicate != preds.has_parent || q.subject != child {
144            continue;
145        }
146        needed += 1;
147        if written >= capacity {
148            continue;
149        }
150        let child_view = view_subject(quins, &preds, child, Some(q.context));
151        let parent_surface = accession_from_records(records, q.object).unwrap_or_else(|| {
152            // Parent object is q_hash("CHEBI:{id}"); recover surface from child record.
153            records
154                .and_then(|rs| {
155                    rs.iter()
156                        .find(|r| q_hash(&r.accession) == child)
157                        .and_then(|r| r.parent_id)
158                })
159                .map(|pid| {
160                    let mut buf = [0u8; 32];
161                    super::access::format_chebi_accession(pid, &mut buf).to_owned()
162                })
163                .unwrap_or_default()
164        });
165        out[written] = RelationHit {
166            child_hash: child,
167            parent_hash: q.object,
168            release_hash: if child_view.release_hash != 0 {
169                child_view.release_hash
170            } else {
171                q.context
172            },
173            source_line: child_view.source_line,
174            uncertainty: if child_view.has_provenance {
175                Uncertainty::Known
176            } else {
177                Uncertainty::Partial
178            },
179            child_accession: accession.clone(),
180            parent_accession: parent_surface,
181            licence_note: note.clone(),
182        };
183        written += 1;
184    }
185
186    if needed == 0 {
187        return Err(QueryError::NotFound);
188    }
189    if needed > capacity {
190        return Err(QueryError::LimitExceeded {
191            limit: capacity,
192            needed,
193        });
194    }
195    Ok(written)
196}
197
198/// Look up children that declare `chebi:hasParent` pointing at `parent_accession`.
199pub fn lookup_children_into(
200    quins: &[NQuin],
201    parent_accession: &str,
202    licence_note: &str,
203    limits: QueryLimits,
204    records: Option<&[ChebiRecord]>,
205    out: &mut [RelationHit],
206) -> Result<usize, QueryError> {
207    let limits = limits.validate()?;
208    if quins.is_empty() {
209        return Err(QueryError::EmptyInput);
210    }
211    let accession = normalize_accession_query(parent_accession).ok_or(QueryError::EmptyQuery)?;
212    let parent = q_hash(&accession);
213    let preds = PredHashes::load();
214    let note = resolve_licence_note(licence_note);
215    let capacity = out.len().min(limits.max_hits);
216
217    let mut written = 0usize;
218    let mut needed = 0usize;
219    for q in quins {
220        if q.predicate != preds.has_parent || q.object != parent {
221            continue;
222        }
223        needed += 1;
224        if written >= capacity {
225            continue;
226        }
227        let child_view = view_subject(quins, &preds, q.subject, Some(q.context));
228        let child_surface = accession_from_records(records, q.subject).unwrap_or_default();
229        out[written] = RelationHit {
230            child_hash: q.subject,
231            parent_hash: parent,
232            release_hash: if child_view.release_hash != 0 {
233                child_view.release_hash
234            } else {
235                q.context
236            },
237            source_line: child_view.source_line,
238            uncertainty: if child_view.has_provenance {
239                Uncertainty::Known
240            } else {
241                Uncertainty::Partial
242            },
243            child_accession: child_surface,
244            parent_accession: accession.clone(),
245            licence_note: note.clone(),
246        };
247        written += 1;
248    }
249
250    if needed == 0 {
251        return Err(QueryError::NotFound);
252    }
253    if needed > capacity {
254        return Err(QueryError::LimitExceeded {
255            limit: capacity,
256            needed,
257        });
258    }
259    Ok(written)
260}
261
262/// Look up `chebi:fromRelease` provenance for an accession.
263pub fn lookup_evidence_into(
264    quins: &[NQuin],
265    accession_query: &str,
266    licence_note: &str,
267    limits: QueryLimits,
268    out: &mut [EvidenceHit],
269) -> Result<usize, QueryError> {
270    let limits = limits.validate()?;
271    if quins.is_empty() {
272        return Err(QueryError::EmptyInput);
273    }
274    let accession = normalize_accession_query(accession_query).ok_or(QueryError::EmptyQuery)?;
275    let subject = q_hash(&accession);
276    let preds = PredHashes::load();
277    let note = resolve_licence_note(licence_note);
278    let capacity = out.len().min(limits.max_hits);
279
280    let mut written = 0usize;
281    let mut needed = 0usize;
282    for q in quins {
283        if q.predicate != preds.from_release || q.subject != subject {
284            continue;
285        }
286        needed += 1;
287        if written >= capacity {
288            continue;
289        }
290        out[written] = EvidenceHit {
291            subject_hash: subject,
292            release_hash: q.object,
293            source_line: (q.metadata & 0xFFFF_FFFF) as u32,
294            uncertainty: Uncertainty::Known,
295            accession: accession.clone(),
296            licence_note: note.clone(),
297        };
298        written += 1;
299    }
300
301    if needed == 0 {
302        return Err(QueryError::NotFound);
303    }
304    if needed > capacity {
305        return Err(QueryError::LimitExceeded {
306            limit: capacity,
307            needed,
308        });
309    }
310    Ok(written)
311}