Skip to main content

GroupedRelation

Struct GroupedRelation 

Source
pub struct GroupedRelation<T: Ord> { /* private fields */ }
Expand description

Deterministic exact grouping of an n-ary relation. A deterministic exact grouping of an n-ary relation by named key columns.

GroupedRelation<T> is the first G2 grouping surface for exact n-ary relations. Groups are keyed by projected key rows and stored in a BTreeMap, so group iteration order is deterministic.

In this first exact grouping slice, each grouped member relation keeps the original relation schema rather than removing key columns. This avoids introducing zero-ary relation semantics while keeping the grouped output relation-first and easy to inspect.

The first exact aggregate on grouped output is Self::counts, which returns the number of stored rows in each group.

§Examples

use relmath::NaryRelation;

let completed = NaryRelation::from_rows(
    ["student", "course", "term"],
    [
        ["Alice", "Math", "Fall"],
        ["Alice", "Physics", "Fall"],
        ["Bob", "Math", "Spring"],
    ],
)?;

let grouped = completed.group_by(["term", "student"])?;

assert_eq!(
    grouped.key_schema(),
    &["term".to_string(), "student".to_string()]
);
assert_eq!(
    grouped.counts(),
    vec![(vec!["Fall", "Alice"], 2), (vec!["Spring", "Bob"], 1)]
);

Implementations§

Source§

impl<T: Ord> GroupedRelation<T>

Source

pub fn key_schema(&self) -> &[String]

Returns the grouping key schema in order.

Examples found in repository?
examples/curriculum.rs (line 70)
7fn main() -> Result<(), relmath::NaryRelationError> {
8    let progress = NaryRelation::from_named_rows(
9        ["student", "course", "status"],
10        [
11            BTreeMap::from([
12                ("course", "Math"),
13                ("status", "passed"),
14                ("student", "Alice"),
15            ]),
16            BTreeMap::from([
17                ("course", "Physics"),
18                ("status", "passed"),
19                ("student", "Alice"),
20            ]),
21            BTreeMap::from([("course", "Math"), ("status", "passed"), ("student", "Bob")]),
22            BTreeMap::from([
23                ("course", "Physics"),
24                ("status", "in_progress"),
25                ("student", "Bob"),
26            ]),
27            BTreeMap::from([
28                ("course", "Math"),
29                ("status", "passed"),
30                ("student", "Cara"),
31            ]),
32        ],
33    )?;
34    let course_rooms = NaryRelation::from_named_rows(
35        ["course", "room"],
36        [
37            BTreeMap::from([("course", "Math"), ("room", "R101")]),
38            BTreeMap::from([("course", "Physics"), ("room", "R201")]),
39            BTreeMap::from([("course", "History"), ("room", "R301")]),
40        ],
41    )?;
42
43    let completed = progress
44        .select(|row| row[2] == "passed")
45        .project(["student", "course"])?;
46    let scheduled = completed.natural_join(&course_rooms);
47    let by_room = scheduled.group_by(["room"])?;
48    let room_r101 = by_room.group(&["R101"]).expect("expected R101 group");
49    let room_assignments = scheduled.project(["room", "student"])?;
50    let exported_assignments = room_assignments.to_named_rows();
51
52    assert!(completed.contains_row(&["Alice", "Math"]));
53    assert_eq!(
54        scheduled.schema(),
55        &[
56            "student".to_string(),
57            "course".to_string(),
58            "room".to_string(),
59        ]
60    );
61    assert_eq!(
62        scheduled.to_rows(),
63        vec![
64            vec!["Alice", "Math", "R101"],
65            vec!["Alice", "Physics", "R201"],
66            vec!["Bob", "Math", "R101"],
67            vec!["Cara", "Math", "R101"],
68        ]
69    );
70    assert_eq!(by_room.key_schema(), &["room".to_string()]);
71    assert_eq!(by_room.member_schema(), scheduled.schema());
72    assert_eq!(by_room.counts(), vec![(vec!["R101"], 3), (vec!["R201"], 1)]);
73    assert_eq!(
74        room_r101.to_rows(),
75        vec![
76            vec!["Alice", "Math", "R101"],
77            vec!["Bob", "Math", "R101"],
78            vec!["Cara", "Math", "R101"],
79        ]
80    );
81    assert_eq!(
82        room_assignments.to_rows(),
83        vec![
84            vec!["R101", "Alice"],
85            vec!["R101", "Bob"],
86            vec!["R101", "Cara"],
87            vec!["R201", "Alice"],
88        ]
89    );
90    assert_eq!(
91        exported_assignments[0],
92        BTreeMap::from([
93            ("room".to_string(), "R101"),
94            ("student".to_string(), "Alice"),
95        ])
96    );
97
98    println!("scheduled course completions: {:?}", scheduled.to_rows());
99
100    Ok(())
101}
Source

pub fn member_schema(&self) -> &[String]

Returns the schema of each member relation.

In the current exact grouping slice this is the full original relation schema.

Examples found in repository?
examples/curriculum.rs (line 71)
7fn main() -> Result<(), relmath::NaryRelationError> {
8    let progress = NaryRelation::from_named_rows(
9        ["student", "course", "status"],
10        [
11            BTreeMap::from([
12                ("course", "Math"),
13                ("status", "passed"),
14                ("student", "Alice"),
15            ]),
16            BTreeMap::from([
17                ("course", "Physics"),
18                ("status", "passed"),
19                ("student", "Alice"),
20            ]),
21            BTreeMap::from([("course", "Math"), ("status", "passed"), ("student", "Bob")]),
22            BTreeMap::from([
23                ("course", "Physics"),
24                ("status", "in_progress"),
25                ("student", "Bob"),
26            ]),
27            BTreeMap::from([
28                ("course", "Math"),
29                ("status", "passed"),
30                ("student", "Cara"),
31            ]),
32        ],
33    )?;
34    let course_rooms = NaryRelation::from_named_rows(
35        ["course", "room"],
36        [
37            BTreeMap::from([("course", "Math"), ("room", "R101")]),
38            BTreeMap::from([("course", "Physics"), ("room", "R201")]),
39            BTreeMap::from([("course", "History"), ("room", "R301")]),
40        ],
41    )?;
42
43    let completed = progress
44        .select(|row| row[2] == "passed")
45        .project(["student", "course"])?;
46    let scheduled = completed.natural_join(&course_rooms);
47    let by_room = scheduled.group_by(["room"])?;
48    let room_r101 = by_room.group(&["R101"]).expect("expected R101 group");
49    let room_assignments = scheduled.project(["room", "student"])?;
50    let exported_assignments = room_assignments.to_named_rows();
51
52    assert!(completed.contains_row(&["Alice", "Math"]));
53    assert_eq!(
54        scheduled.schema(),
55        &[
56            "student".to_string(),
57            "course".to_string(),
58            "room".to_string(),
59        ]
60    );
61    assert_eq!(
62        scheduled.to_rows(),
63        vec![
64            vec!["Alice", "Math", "R101"],
65            vec!["Alice", "Physics", "R201"],
66            vec!["Bob", "Math", "R101"],
67            vec!["Cara", "Math", "R101"],
68        ]
69    );
70    assert_eq!(by_room.key_schema(), &["room".to_string()]);
71    assert_eq!(by_room.member_schema(), scheduled.schema());
72    assert_eq!(by_room.counts(), vec![(vec!["R101"], 3), (vec!["R201"], 1)]);
73    assert_eq!(
74        room_r101.to_rows(),
75        vec![
76            vec!["Alice", "Math", "R101"],
77            vec!["Bob", "Math", "R101"],
78            vec!["Cara", "Math", "R101"],
79        ]
80    );
81    assert_eq!(
82        room_assignments.to_rows(),
83        vec![
84            vec!["R101", "Alice"],
85            vec!["R101", "Bob"],
86            vec!["R101", "Cara"],
87            vec!["R201", "Alice"],
88        ]
89    );
90    assert_eq!(
91        exported_assignments[0],
92        BTreeMap::from([
93            ("room".to_string(), "R101"),
94            ("student".to_string(), "Alice"),
95        ])
96    );
97
98    println!("scheduled course completions: {:?}", scheduled.to_rows());
99
100    Ok(())
101}
Source

pub fn len(&self) -> usize

Returns the number of groups.

Source

pub fn is_empty(&self) -> bool

Returns true when the grouping contains no groups.

Source

pub fn group(&self, key: &[T]) -> Option<&NaryRelation<T>>

Returns the member relation for the given grouping key.

Examples found in repository?
examples/curriculum.rs (line 48)
7fn main() -> Result<(), relmath::NaryRelationError> {
8    let progress = NaryRelation::from_named_rows(
9        ["student", "course", "status"],
10        [
11            BTreeMap::from([
12                ("course", "Math"),
13                ("status", "passed"),
14                ("student", "Alice"),
15            ]),
16            BTreeMap::from([
17                ("course", "Physics"),
18                ("status", "passed"),
19                ("student", "Alice"),
20            ]),
21            BTreeMap::from([("course", "Math"), ("status", "passed"), ("student", "Bob")]),
22            BTreeMap::from([
23                ("course", "Physics"),
24                ("status", "in_progress"),
25                ("student", "Bob"),
26            ]),
27            BTreeMap::from([
28                ("course", "Math"),
29                ("status", "passed"),
30                ("student", "Cara"),
31            ]),
32        ],
33    )?;
34    let course_rooms = NaryRelation::from_named_rows(
35        ["course", "room"],
36        [
37            BTreeMap::from([("course", "Math"), ("room", "R101")]),
38            BTreeMap::from([("course", "Physics"), ("room", "R201")]),
39            BTreeMap::from([("course", "History"), ("room", "R301")]),
40        ],
41    )?;
42
43    let completed = progress
44        .select(|row| row[2] == "passed")
45        .project(["student", "course"])?;
46    let scheduled = completed.natural_join(&course_rooms);
47    let by_room = scheduled.group_by(["room"])?;
48    let room_r101 = by_room.group(&["R101"]).expect("expected R101 group");
49    let room_assignments = scheduled.project(["room", "student"])?;
50    let exported_assignments = room_assignments.to_named_rows();
51
52    assert!(completed.contains_row(&["Alice", "Math"]));
53    assert_eq!(
54        scheduled.schema(),
55        &[
56            "student".to_string(),
57            "course".to_string(),
58            "room".to_string(),
59        ]
60    );
61    assert_eq!(
62        scheduled.to_rows(),
63        vec![
64            vec!["Alice", "Math", "R101"],
65            vec!["Alice", "Physics", "R201"],
66            vec!["Bob", "Math", "R101"],
67            vec!["Cara", "Math", "R101"],
68        ]
69    );
70    assert_eq!(by_room.key_schema(), &["room".to_string()]);
71    assert_eq!(by_room.member_schema(), scheduled.schema());
72    assert_eq!(by_room.counts(), vec![(vec!["R101"], 3), (vec!["R201"], 1)]);
73    assert_eq!(
74        room_r101.to_rows(),
75        vec![
76            vec!["Alice", "Math", "R101"],
77            vec!["Bob", "Math", "R101"],
78            vec!["Cara", "Math", "R101"],
79        ]
80    );
81    assert_eq!(
82        room_assignments.to_rows(),
83        vec![
84            vec!["R101", "Alice"],
85            vec!["R101", "Bob"],
86            vec!["R101", "Cara"],
87            vec!["R201", "Alice"],
88        ]
89    );
90    assert_eq!(
91        exported_assignments[0],
92        BTreeMap::from([
93            ("room".to_string(), "R101"),
94            ("student".to_string(), "Alice"),
95        ])
96    );
97
98    println!("scheduled course completions: {:?}", scheduled.to_rows());
99
100    Ok(())
101}
Source

pub fn iter(&self) -> impl Iterator<Item = (&[T], &NaryRelation<T>)>

Returns an iterator over groups in deterministic key order.

Source

pub fn counts(&self) -> Vec<(Vec<T>, usize)>
where T: Clone,

Returns the first exact aggregate over the grouped relation: row counts.

Each count is the number of stored rows in the corresponding group after the base relation’s set semantics have already deduplicated equal rows. Results follow the deterministic key order of the grouping.

Examples found in repository?
examples/curriculum.rs (line 72)
7fn main() -> Result<(), relmath::NaryRelationError> {
8    let progress = NaryRelation::from_named_rows(
9        ["student", "course", "status"],
10        [
11            BTreeMap::from([
12                ("course", "Math"),
13                ("status", "passed"),
14                ("student", "Alice"),
15            ]),
16            BTreeMap::from([
17                ("course", "Physics"),
18                ("status", "passed"),
19                ("student", "Alice"),
20            ]),
21            BTreeMap::from([("course", "Math"), ("status", "passed"), ("student", "Bob")]),
22            BTreeMap::from([
23                ("course", "Physics"),
24                ("status", "in_progress"),
25                ("student", "Bob"),
26            ]),
27            BTreeMap::from([
28                ("course", "Math"),
29                ("status", "passed"),
30                ("student", "Cara"),
31            ]),
32        ],
33    )?;
34    let course_rooms = NaryRelation::from_named_rows(
35        ["course", "room"],
36        [
37            BTreeMap::from([("course", "Math"), ("room", "R101")]),
38            BTreeMap::from([("course", "Physics"), ("room", "R201")]),
39            BTreeMap::from([("course", "History"), ("room", "R301")]),
40        ],
41    )?;
42
43    let completed = progress
44        .select(|row| row[2] == "passed")
45        .project(["student", "course"])?;
46    let scheduled = completed.natural_join(&course_rooms);
47    let by_room = scheduled.group_by(["room"])?;
48    let room_r101 = by_room.group(&["R101"]).expect("expected R101 group");
49    let room_assignments = scheduled.project(["room", "student"])?;
50    let exported_assignments = room_assignments.to_named_rows();
51
52    assert!(completed.contains_row(&["Alice", "Math"]));
53    assert_eq!(
54        scheduled.schema(),
55        &[
56            "student".to_string(),
57            "course".to_string(),
58            "room".to_string(),
59        ]
60    );
61    assert_eq!(
62        scheduled.to_rows(),
63        vec![
64            vec!["Alice", "Math", "R101"],
65            vec!["Alice", "Physics", "R201"],
66            vec!["Bob", "Math", "R101"],
67            vec!["Cara", "Math", "R101"],
68        ]
69    );
70    assert_eq!(by_room.key_schema(), &["room".to_string()]);
71    assert_eq!(by_room.member_schema(), scheduled.schema());
72    assert_eq!(by_room.counts(), vec![(vec!["R101"], 3), (vec!["R201"], 1)]);
73    assert_eq!(
74        room_r101.to_rows(),
75        vec![
76            vec!["Alice", "Math", "R101"],
77            vec!["Bob", "Math", "R101"],
78            vec!["Cara", "Math", "R101"],
79        ]
80    );
81    assert_eq!(
82        room_assignments.to_rows(),
83        vec![
84            vec!["R101", "Alice"],
85            vec!["R101", "Bob"],
86            vec!["R101", "Cara"],
87            vec!["R201", "Alice"],
88        ]
89    );
90    assert_eq!(
91        exported_assignments[0],
92        BTreeMap::from([
93            ("room".to_string(), "R101"),
94            ("student".to_string(), "Alice"),
95        ])
96    );
97
98    println!("scheduled course completions: {:?}", scheduled.to_rows());
99
100    Ok(())
101}

Trait Implementations§

Source§

impl<T: Clone + Ord> Clone for GroupedRelation<T>

Source§

fn clone(&self) -> GroupedRelation<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + Ord> Debug for GroupedRelation<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: PartialEq + Ord> PartialEq for GroupedRelation<T>

Source§

fn eq(&self, other: &GroupedRelation<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: Eq + Ord> Eq for GroupedRelation<T>

Source§

impl<T: Ord> StructuralPartialEq for GroupedRelation<T>

Auto Trait Implementations§

§

impl<T> Freeze for GroupedRelation<T>

§

impl<T> RefUnwindSafe for GroupedRelation<T>
where T: RefUnwindSafe,

§

impl<T> Send for GroupedRelation<T>
where T: Send,

§

impl<T> Sync for GroupedRelation<T>
where T: Sync,

§

impl<T> Unpin for GroupedRelation<T>

§

impl<T> UnsafeUnpin for GroupedRelation<T>

§

impl<T> UnwindSafe for GroupedRelation<T>
where T: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.