1#[cfg(feature = "vectordata")]
26use std::sync::Arc;
27
28use crate::ast::PortType;
29
30#[cfg(feature = "vectordata")]
31pub use self::types::{PredicateForms, PredicateFragment, RecordForms, RecordFragment};
32#[cfg(feature = "vectordata")]
33pub use self::wires::Shared;
34
35#[derive(Debug, Clone)]
37pub enum DatasetValue {
38 #[cfg(feature = "vectordata")]
42 AdmittedRows(Arc<vectordata::ground_truth::OrdinalSet>),
43 #[cfg(feature = "vectordata")]
45 PredicateForms(Arc<PredicateForms>),
46 #[cfg(feature = "vectordata")]
48 RecordForms(Arc<RecordForms>),
49 #[cfg(feature = "vectordata")]
51 Predicate(PredicateFragment),
52 #[cfg(feature = "vectordata")]
54 Record(RecordFragment),
55}
56
57impl DatasetValue {
58 pub fn port_type(&self) -> PortType {
60 match self {
61 #[cfg(feature = "vectordata")]
62 DatasetValue::AdmittedRows(_) => PortType::AdmittedRows,
63 #[cfg(feature = "vectordata")]
64 DatasetValue::PredicateForms(_) | DatasetValue::RecordForms(_) => PortType::Forms,
65 #[cfg(feature = "vectordata")]
66 DatasetValue::Predicate(_) | DatasetValue::Record(_) => PortType::Fragment,
67 #[cfg(not(feature = "vectordata"))]
68 _ => match *self {},
69 }
70 }
71
72 pub fn display(&self) -> String {
76 match self {
77 #[cfg(feature = "vectordata")]
78 DatasetValue::AdmittedRows(set) => format!("{set:?}"),
79 #[cfg(feature = "vectordata")]
80 DatasetValue::PredicateForms(forms) => format!(
81 "forms of {}: {} over {} predicates",
82 forms.origin,
83 forms.census.forms().len(),
84 forms.census.count()
85 ),
86 #[cfg(feature = "vectordata")]
87 DatasetValue::RecordForms(forms) => format!(
88 "forms of {}: 1 over {} fields",
89 forms.origin,
90 forms.layout.names().len()
91 ),
92 #[cfg(feature = "vectordata")]
93 DatasetValue::Predicate(fragment) => format!(
94 "predicate {} of {}, form {}",
95 fragment.ordinal, fragment.forms.origin, fragment.form
96 ),
97 #[cfg(feature = "vectordata")]
98 DatasetValue::Record(fragment) => {
99 format!("record {} of {}", fragment.ordinal, fragment.forms.origin)
100 }
101 #[cfg(not(feature = "vectordata"))]
102 _ => match *self {},
103 }
104 }
105}
106
107impl PartialEq for DatasetValue {
112 fn eq(&self, other: &Self) -> bool {
113 match (self, other) {
114 #[cfg(feature = "vectordata")]
115 (DatasetValue::AdmittedRows(a), DatasetValue::AdmittedRows(b)) => {
116 Arc::ptr_eq(a, b) || a == b
117 }
118 #[cfg(feature = "vectordata")]
119 (DatasetValue::PredicateForms(a), DatasetValue::PredicateForms(b)) => Arc::ptr_eq(a, b),
120 #[cfg(feature = "vectordata")]
121 (DatasetValue::RecordForms(a), DatasetValue::RecordForms(b)) => Arc::ptr_eq(a, b),
122 #[cfg(feature = "vectordata")]
123 (DatasetValue::Predicate(a), DatasetValue::Predicate(b)) => {
124 Arc::ptr_eq(&a.forms, &b.forms) && a.form == b.form && a.ordinal == b.ordinal
125 }
126 #[cfg(feature = "vectordata")]
127 (DatasetValue::Record(a), DatasetValue::Record(b)) => {
128 Arc::ptr_eq(&a.forms, &b.forms) && a.ordinal == b.ordinal
129 }
130 #[cfg(feature = "vectordata")]
131 _ => false,
132 #[cfg(not(feature = "vectordata"))]
133 _ => match *self {},
134 }
135 }
136}
137
138#[cfg(feature = "vectordata")]
139mod types {
140 use std::sync::Arc;
141
142 use vectordata::binding::{Binder, Layout};
143 use vectordata::predicate_forms::FormCensus;
144 use vectordata::records::RecordFacet;
145
146 #[non_exhaustive]
159 pub struct PredicateForms {
160 pub census: FormCensus,
164 pub layout: Layout,
167 pub predicates: RecordFacet,
170 pub origin: String,
172 unkeyed: Option<(String, String)>,
175 }
176
177 impl PredicateForms {
178 pub(crate) fn new(
179 census: FormCensus,
180 layout: Layout,
181 predicates: RecordFacet,
182 origin: String,
183 ) -> Self {
184 let unkeyed = first_unkeyed(&census);
185 Self {
186 census,
187 layout,
188 predicates,
189 origin,
190 unkeyed,
191 }
192 }
193
194 pub fn form_key_at(&self, ordinal: u64) -> Result<&str, String> {
205 form_key_at(&self.census, self.unkeyed.as_ref(), &self.origin, ordinal)
206 }
207
208 pub fn form_keys(&self) -> Result<Vec<&str>, String> {
212 form_keys(&self.census, self.unkeyed.as_ref(), &self.origin)
213 }
214 }
215
216 fn first_unkeyed(census: &FormCensus) -> Option<(String, String)> {
219 census.forms().iter().find_map(|form| {
220 form.unkeyed()
221 .map(|reason| (form.form().to_string(), reason.to_string()))
222 })
223 }
224
225 fn keyed(unkeyed: Option<&(String, String)>, origin: &str) -> Result<(), String> {
227 match unkeyed {
228 Some((form, reason)) => Err(format!(
229 "the predicates of '{origin}' hold a form with no key, `{form}`: {reason}"
230 )),
231 None => Ok(()),
232 }
233 }
234
235 fn form_keys<'a>(
237 census: &'a FormCensus,
238 unkeyed: Option<&(String, String)>,
239 origin: &str,
240 ) -> Result<Vec<&'a str>, String> {
241 keyed(unkeyed, origin)?;
242 let keys: std::collections::BTreeSet<&str> = census
243 .forms()
244 .iter()
245 .filter_map(|form| form.key())
246 .collect();
247 Ok(keys.into_iter().collect())
248 }
249
250 fn form_key_at<'a>(
252 census: &'a FormCensus,
253 unkeyed: Option<&(String, String)>,
254 origin: &str,
255 ordinal: u64,
256 ) -> Result<&'a str, String> {
257 keyed(unkeyed, origin)?;
258 census
259 .form_at(ordinal)
260 .and_then(|form| census.forms()[form].key())
261 .ok_or_else(|| format!("'{origin}' has no predicate {ordinal}"))
262 }
263
264 #[cfg(test)]
265 mod form_key_tests {
266 use super::{first_unkeyed, form_key_at, form_keys};
267 use vectordata::formats::pnode::{
268 Comparand, ConjugateNode, ConjugateType, FieldRef, OpType, PNode, PredicateNode,
269 };
270 use vectordata::predicate_forms::FormCensus;
271
272 fn leaf(field: &str, op: OpType) -> PNode {
273 PNode::Predicate(PredicateNode {
274 field: FieldRef::Named(field.into()),
275 op,
276 comparands: vec![Comparand::Int(1)],
277 })
278 }
279
280 fn junction(conjugate_type: ConjugateType, children: Vec<PNode>) -> PNode {
281 PNode::Conjugate(ConjugateNode {
282 conjugate_type,
283 children,
284 })
285 }
286
287 #[test]
291 fn a_keyed_facet_gives_each_predicate_its_forms_key() {
292 let mut census = FormCensus::new();
293 let both = junction(
294 ConjugateType::And,
295 vec![leaf("topic", OpType::Eq), leaf("rank", OpType::Ge)],
296 );
297 census.record(&leaf("topic", OpType::Eq), None, None);
298 census.record(&both, None, None);
299 census.record(&leaf("topic", OpType::Eq), None, None);
300 let unkeyed = first_unkeyed(&census);
301 assert_eq!(unkeyed, None);
302 let key = |ordinal| form_key_at(&census, unkeyed.as_ref(), "ds:p", ordinal);
303 assert_eq!(key(0), Ok("topic.eq"));
304 assert_eq!(key(1), Ok("rank.range_topic.eq"));
305 assert_eq!(key(2), Ok("topic.eq"));
306 assert_eq!(key(3), Err("'ds:p' has no predicate 3".to_string()));
307 assert_eq!(
308 form_keys(&census, unkeyed.as_ref(), "ds:p"),
309 Ok(vec!["rank.range_topic.eq", "topic.eq"])
310 );
311 }
312
313 #[test]
316 fn a_facet_holding_an_unkeyed_form_gives_no_keys() {
317 let mut census = FormCensus::new();
318 let either = junction(
319 ConjugateType::Or,
320 vec![leaf("a", OpType::Eq), leaf("b", OpType::Eq)],
321 );
322 census.record(&leaf("topic", OpType::Eq), None, None);
323 census.record(&either, None, None);
324 let unkeyed = first_unkeyed(&census);
325 let refusals = (0..2)
326 .map(|ordinal| {
327 form_key_at(&census, unkeyed.as_ref(), "ds:p", ordinal)
328 .expect_err("a facet with an unkeyed form has no keys")
329 })
330 .chain([form_keys(&census, unkeyed.as_ref(), "ds:p")
331 .expect_err("a facet with an unkeyed form lists no keys")]);
332 for err in refusals {
333 assert!(
334 err.starts_with(
335 "the predicates of 'ds:p' hold a form with no key, `(a = ? OR b = ?)`: "
336 ) && err.contains("disjunction"),
337 "{err}"
338 );
339 }
340 }
341 }
342
343 impl std::fmt::Debug for PredicateForms {
344 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345 f.debug_struct("PredicateForms")
346 .field("origin", &self.origin)
347 .field("forms", &self.census.forms().len())
348 .field("predicates", &self.census.count())
349 .finish()
350 }
351 }
352
353 #[non_exhaustive]
357 pub struct RecordForms {
358 pub layout: Layout,
360 pub binder: Binder,
362 pub records: RecordFacet,
364 pub origin: String,
366 }
367
368 impl RecordForms {
369 pub(crate) fn new(layout: Layout, records: RecordFacet, origin: String) -> Self {
370 Self {
371 binder: Binder::all(&layout),
372 layout,
373 records,
374 origin,
375 }
376 }
377 }
378
379 impl std::fmt::Debug for RecordForms {
380 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381 f.debug_struct("RecordForms")
382 .field("origin", &self.origin)
383 .field("fields", &self.layout.names())
384 .finish()
385 }
386 }
387
388 #[derive(Debug, Clone)]
396 #[non_exhaustive]
397 pub struct PredicateFragment {
398 pub forms: Arc<PredicateForms>,
400 pub form: u32,
402 pub ordinal: u64,
404 }
405
406 impl PredicateFragment {
407 pub(crate) fn new(forms: Arc<PredicateForms>, form: u32, ordinal: u64) -> Self {
408 Self {
409 forms,
410 form,
411 ordinal,
412 }
413 }
414 }
415
416 #[derive(Debug, Clone)]
422 #[non_exhaustive]
423 pub struct RecordFragment {
424 pub forms: Arc<RecordForms>,
426 pub ordinal: u64,
428 }
429
430 impl RecordFragment {
431 pub(crate) fn new(forms: Arc<RecordForms>, ordinal: u64) -> Self {
432 Self { forms, ordinal }
433 }
434 }
435}
436
437#[cfg(feature = "vectordata")]
449pub mod vectordata {
450 pub mod formats {
452 pub mod anode {
454 pub use ::vectordata::formats::anode::{ANode, decode, encode};
455 }
456 pub mod mnode {
458 pub use ::vectordata::formats::mnode::{MNode, MValue, TypeTag};
459 pub mod scan {
461 pub use ::vectordata::formats::mnode::scan::Field;
462 }
463 }
464 pub mod pnode {
467 pub use ::vectordata::formats::pnode::{
468 Comparand, ConjugateNode, ConjugateType, FieldRef, OpType, PNode, PredicateNode,
469 };
470 pub mod template {
473 pub use ::vectordata::formats::pnode::template::{
474 PredicateTemplate, parse_template,
475 };
476 }
477 }
478 }
479 pub mod binding {
481 pub use ::vectordata::binding::{
482 BindError, BindType, Binder, Condition, Layout, LayoutSource, Nullability,
483 PredicateBinder,
484 };
485 }
486 pub mod predicate_forms {
488 pub use ::vectordata::predicate_forms::{
489 Access, FormCensus, PredicateForm, PredicateStrata,
490 };
491 }
492 pub mod records {
494 pub use ::vectordata::records::{
495 RecordCodec, RecordError, RecordFacet, SharedBytes, codec_by_name, codec_names,
496 };
497 }
498 pub mod ground_truth {
500 pub use ::vectordata::ground_truth::OrdinalSet;
501 }
502}
503
504#[cfg(feature = "vectordata")]
505mod wires {
506 use std::sync::Arc;
507
508 use vectordata::ground_truth::OrdinalSet;
509
510 use super::{DatasetValue, PredicateForms, PredicateFragment, RecordForms, RecordFragment};
511 use crate::ast::{PortType, Value};
512 use crate::derive_support::{Wire, extract_mismatch};
513
514 #[derive(Debug)]
522 pub struct Shared<T>(pub Arc<T>);
523
524 impl<T> Clone for Shared<T> {
525 fn clone(&self) -> Self {
526 Shared(self.0.clone())
527 }
528 }
529
530 impl<T> std::ops::Deref for Shared<T> {
531 type Target = T;
532 fn deref(&self) -> &T {
533 &self.0
534 }
535 }
536
537 fn wrong_kind(wanted: &str, got: &DatasetValue) -> ! {
542 let got = match got {
543 DatasetValue::AdmittedRows(_) => "the rows a predicate admits",
544 DatasetValue::PredicateForms(_) => "the forms of a predicate facet",
545 DatasetValue::RecordForms(_) => "the forms of a record facet",
546 DatasetValue::Predicate(_) => "a predicate fragment",
547 DatasetValue::Record(_) => "a record fragment",
548 };
549 panic!("expected {wanted}, got {got}")
550 }
551
552 impl Wire for Shared<OrdinalSet> {
554 const PORT: PortType = PortType::AdmittedRows;
555 fn extract(v: &Value) -> Self {
556 match v {
557 Value::Dataset(DatasetValue::AdmittedRows(set)) => Shared(set.clone()),
558 other => extract_mismatch("Shared<OrdinalSet>", Self::PORT, other),
559 }
560 }
561 fn inject(self) -> Value {
562 Value::Dataset(DatasetValue::AdmittedRows(self.0))
563 }
564 }
565
566 impl Wire for Shared<PredicateForms> {
568 const PORT: PortType = PortType::Forms;
569 fn extract(v: &Value) -> Self {
570 match v {
571 Value::Dataset(DatasetValue::PredicateForms(forms)) => Shared(forms.clone()),
572 Value::Dataset(d @ DatasetValue::RecordForms(_)) => {
573 wrong_kind("the forms of a predicate facet", d)
574 }
575 other => extract_mismatch("Shared<PredicateForms>", Self::PORT, other),
576 }
577 }
578 fn inject(self) -> Value {
579 Value::Dataset(DatasetValue::PredicateForms(self.0))
580 }
581 }
582
583 impl Wire for Shared<RecordForms> {
585 const PORT: PortType = PortType::Forms;
586 fn extract(v: &Value) -> Self {
587 match v {
588 Value::Dataset(DatasetValue::RecordForms(forms)) => Shared(forms.clone()),
589 Value::Dataset(d @ DatasetValue::PredicateForms(_)) => {
590 wrong_kind("the forms of a record facet", d)
591 }
592 other => extract_mismatch("Shared<RecordForms>", Self::PORT, other),
593 }
594 }
595 fn inject(self) -> Value {
596 Value::Dataset(DatasetValue::RecordForms(self.0))
597 }
598 }
599
600 impl Wire for PredicateFragment {
602 const PORT: PortType = PortType::Fragment;
603 fn extract(v: &Value) -> Self {
604 match v {
605 Value::Dataset(DatasetValue::Predicate(fragment)) => fragment.clone(),
606 Value::Dataset(d @ DatasetValue::Record(_)) => {
607 wrong_kind("a predicate fragment", d)
608 }
609 other => extract_mismatch("PredicateFragment", Self::PORT, other),
610 }
611 }
612 fn inject(self) -> Value {
613 Value::Dataset(DatasetValue::Predicate(self))
614 }
615 }
616
617 impl Wire for RecordFragment {
619 const PORT: PortType = PortType::Fragment;
620 fn extract(v: &Value) -> Self {
621 match v {
622 Value::Dataset(DatasetValue::Record(fragment)) => fragment.clone(),
623 Value::Dataset(d @ DatasetValue::Predicate(_)) => {
624 wrong_kind("a record fragment", d)
625 }
626 other => extract_mismatch("RecordFragment", Self::PORT, other),
627 }
628 }
629 fn inject(self) -> Value {
630 Value::Dataset(DatasetValue::Record(self))
631 }
632 }
633}