darwen 1.3.0

A relational algebra library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use std::{collections::BTreeSet, fmt::Display};

use crate::{
    error::Error,
    types::{heading::Heading, tuple::Tuple},
};

/// Builds a [`Relation`] from a heading and a body of tuples.
///
/// # Example
///
/// ```rust
/// use darwen::prelude::{
///     AttributeName, HeadingBuilder, RelationBuilder, Scalar, ScalarType, TupleBuilder,
/// };
///
/// let relation = RelationBuilder::new()
///     .with_heading(
///         HeadingBuilder::new()
///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
///             .build()?,
///     )
///     .with_body(vec![
///         TupleBuilder::new()
///             .with_value(AttributeName::from("id"), Scalar::Integer(1))
///             .build()?,
///     ])
///     .build()?;
///
/// assert_eq!(
///     relation,
///     darwen::prelude::Relation::new_from_iter(
///         HeadingBuilder::new()
///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
///             .build()?,
///         vec![
///             TupleBuilder::new()
///                 .with_value(AttributeName::from("id"), Scalar::Integer(1))
///                 .build()?,
///         ],
///     )?,
/// );
/// # Ok::<(), darwen::prelude::Error>(())
/// ```
#[derive(Debug, Default)]
pub struct RelationBuilder {
    heading: Option<Heading>,
    body: Vec<Tuple>,
}

impl RelationBuilder {
    /// Creates an empty relation builder.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::prelude::RelationBuilder;
    ///
    /// let builder = RelationBuilder::new();
    ///
    /// let _ = builder;
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the relation heading.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::prelude::{AttributeName, HeadingBuilder, RelationBuilder, ScalarType};
    ///
    /// let relation = RelationBuilder::new()
    ///     .with_heading(
    ///         HeadingBuilder::new()
    ///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///             .build()?,
    ///     )
    ///     .build()?;
    ///
    /// let _ = relation;
    /// # Ok::<(), darwen::prelude::Error>(())
    /// ```
    #[must_use]
    pub fn with_heading(mut self, heading: Heading) -> Self {
        self.heading = Some(heading);
        self
    }

    /// Replaces the builder body with tuples from the iterator.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::prelude::{
    ///     AttributeName, HeadingBuilder, RelationBuilder, Scalar, ScalarType, TupleBuilder,
    /// };
    ///
    /// let relation = RelationBuilder::new()
    ///     .with_heading(
    ///         HeadingBuilder::new()
    ///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///             .build()?,
    ///     )
    ///     .with_body(vec![
    ///         TupleBuilder::new()
    ///             .with_value(AttributeName::from("id"), Scalar::Integer(1))
    ///             .build()?,
    ///     ])
    ///     .build()?;
    ///
    /// let _ = relation;
    /// # Ok::<(), darwen::prelude::Error>(())
    /// ```
    #[must_use]
    pub fn with_body<T>(mut self, body: T) -> Self
    where
        T: IntoIterator<Item = Tuple>,
    {
        self.body = body.into_iter().collect();
        self
    }

    /// Builds a [`Relation`] from the collected heading and tuples.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::prelude::{
    ///     AttributeName, HeadingBuilder, RelationBuilder, Scalar, ScalarType, TupleBuilder,
    /// };
    ///
    /// let relation = RelationBuilder::new()
    ///     .with_heading(
    ///         HeadingBuilder::new()
    ///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///             .build()?,
    ///     )
    ///     .with_body(vec![
    ///         TupleBuilder::new()
    ///             .with_value(AttributeName::from("id"), Scalar::Integer(1))
    ///             .build()?,
    ///     ])
    ///     .build()?;
    ///
    /// let _ = relation;
    /// # Ok::<(), darwen::prelude::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::HeadingMissing`] if the heading was not provided.
    /// Returns [`Error::InvalidWidth`] if one of the body tuples has a
    /// different arity than the heading degree.
    /// Returns [`Error::AttributeNotFound`] if one of the body tuples is
    /// missing an attribute required by the heading.
    /// Returns [`Error::ScalarTypeMismatch`] if one of the body tuples
    /// contains a value with a different scalar type than the heading
    /// requires.
    pub fn build(self) -> Result<Relation, Error> {
        let heading = self.heading.ok_or(Error::HeadingMissing)?;
        let mut relation = Relation::new(heading);
        for tuple in self.body {
            relation.insert(tuple)?;
        }
        Ok(relation)
    }
}

/// Represents a relation with a heading and a set of tuples.
///
/// # Example
///
/// ```rust
/// use darwen::prelude::{AttributeName, HeadingBuilder, Relation, ScalarType};
///
/// let relation = Relation::new(
///     HeadingBuilder::new()
///         .with_attribute(AttributeName::from("id"), ScalarType::Integer)
///         .build()?,
/// );
///
/// assert_eq!(
///     relation,
///     Relation::new_from_iter(
///         HeadingBuilder::new()
///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
///             .build()?,
///         Vec::new(),
///     )?,
/// );
/// # Ok::<(), darwen::prelude::Error>(())
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct Relation {
    pub(crate) heading: Heading,
    pub(crate) body: BTreeSet<Tuple>,
}

impl Relation {
    /// Creates an empty relation with the given heading.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::prelude::{AttributeName, HeadingBuilder, Relation, ScalarType};
    ///
    /// let relation = Relation::new(
    ///     HeadingBuilder::new()
    ///         .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///         .build()?,
    /// );
    ///
    /// assert_eq!(
    ///     relation,
    ///     Relation::new_from_iter(
    ///         HeadingBuilder::new()
    ///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///             .build()?,
    ///         Vec::new(),
    ///     )?,
    /// );
    /// # Ok::<(), darwen::prelude::Error>(())
    /// ```
    #[must_use]
    pub fn new(heading: Heading) -> Self {
        Self {
            heading,
            body: BTreeSet::new(),
        }
    }

    /// Builds a relation from a heading and an iterator of tuples.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::prelude::{
    ///     AttributeName, HeadingBuilder, Relation, Scalar, ScalarType, TupleBuilder,
    /// };
    ///
    /// let relation = Relation::new_from_iter(
    ///     HeadingBuilder::new()
    ///         .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///         .build()?,
    ///     vec![
    ///         TupleBuilder::new()
    ///             .with_value(AttributeName::from("id"), Scalar::Integer(1))
    ///             .build()?,
    ///     ],
    /// )?;
    ///
    /// let _ = relation;
    /// # Ok::<(), darwen::prelude::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidWidth`] if any tuple has a different arity than
    /// the provided heading degree.
    /// Returns [`Error::AttributeNotFound`] if any tuple is missing an
    /// attribute required by the provided heading.
    /// Returns [`Error::ScalarTypeMismatch`] if any tuple contains a value with
    /// a different scalar type than the provided heading requires.
    pub fn new_from_iter<T>(heading: Heading, body: T) -> Result<Self, Error>
    where
        T: IntoIterator<Item = Tuple>,
    {
        let mut relation = Self::new(heading);
        for item in body {
            relation.insert(item)?;
        }
        Ok(relation)
    }

    /// Inserts a tuple into the relation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::prelude::{
    ///     AttributeName, HeadingBuilder, Relation, Scalar, ScalarType, TupleBuilder,
    /// };
    ///
    /// let mut relation = Relation::new(
    ///     HeadingBuilder::new()
    ///         .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///         .build()?,
    /// );
    /// relation.insert(
    ///     TupleBuilder::new()
    ///         .with_value(AttributeName::from("id"), Scalar::Integer(1))
    ///         .build()?,
    /// )?;
    ///
    /// assert_eq!(
    ///     relation,
    ///     Relation::new_from_iter(
    ///         HeadingBuilder::new()
    ///             .with_attribute(AttributeName::from("id"), ScalarType::Integer)
    ///             .build()?,
    ///         vec![
    ///             TupleBuilder::new()
    ///                 .with_value(AttributeName::from("id"), Scalar::Integer(1))
    ///                 .build()?,
    ///         ],
    ///     )?,
    /// );
    /// # Ok::<(), darwen::prelude::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidWidth`] if the tuple arity does not match the
    /// relation heading degree.
    /// Returns [`Error::AttributeNotFound`] if the tuple is missing an
    /// attribute required by the relation heading.
    /// Returns [`Error::ScalarTypeMismatch`] if the tuple contains a value with
    /// a different scalar type than the relation heading requires.
    pub fn insert(&mut self, tuple: Tuple) -> Result<(), Error> {
        self.heading.validate_tuple(&tuple)?;
        self.body.insert(tuple);
        Ok(())
    }

    /// Iterates over relation tuples in key order.
    ///
    /// # Example
    ///
    /// ```rust
    /// use darwen::{
    ///     heading,
    ///     tuple,
    ///     prelude::{RelationBuilder, ScalarType},
    /// };
    ///
    /// let relation = RelationBuilder::new()
    ///     .with_heading(heading!(id = ScalarType::Integer)?)
    ///     .with_body(vec![
    ///         tuple!(id = 2)?,
    ///         tuple!(id = 1)?,
    ///     ])
    ///     .build()?;
    ///
    /// let tuples = relation.iter().cloned().collect::<Vec<_>>();
    ///
    /// assert_eq!(tuples.len(), 2);
    /// assert_eq!(tuples[0], tuple!(id = 1)?);
    /// assert_eq!(tuples[1], tuple!(id = 2)?);
    /// # Ok::<(), darwen::prelude::Error>(())
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = &Tuple> {
        self.body.iter()
    }
}

impl Display for Relation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RELATION ")?;
        write!(f, "{}", self.heading)?;
        for tuple in &self.body {
            write!(f, "\n\t{tuple}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::{AttributeName, Scalar, ScalarType};

    use super::*;

    #[test]
    fn test_insert() {
        let mut relation = Relation::new(
            Heading::try_from(vec![
                ("a".to_string(), ScalarType::Integer),
                ("b".to_string(), ScalarType::Integer),
            ])
            .unwrap(),
        );
        let tuple =
            Tuple::try_from(vec![("a", Scalar::Integer(1)), ("b", Scalar::Integer(2))]).unwrap();
        assert!(relation.insert(tuple).is_ok());
    }

    #[test]
    fn test_insert_invalid_tuple() {
        let mut relation = Relation::new(
            Heading::try_from(vec![
                ("a".to_string(), ScalarType::Integer),
                ("b".to_string(), ScalarType::Integer),
            ])
            .unwrap(),
        );
        let tuple = Tuple::try_from(vec![
            ("a".to_string(), Scalar::Integer(1)),
            ("b".to_string(), Scalar::Boolean(true)),
        ])
        .unwrap();
        assert!(relation.insert(tuple).is_err());
    }

    #[test]
    fn test_new_creates_empty_body() {
        let relation = Relation::new(
            Heading::try_from(vec![(AttributeName::from("a"), ScalarType::Integer)]).unwrap(),
        );

        assert!(relation.body.is_empty());
    }

    #[test]
    fn test_new_from_iter_rejects_invalid_tuple() {
        assert_eq!(
            Relation::new_from_iter(
                Heading::try_from(vec![(AttributeName::from("a"), ScalarType::Integer)]).unwrap(),
                vec![
                    Tuple::try_from(vec![(AttributeName::from("a"), Scalar::Boolean(true))])
                        .unwrap(),
                ],
            ),
            Err(Error::ScalarTypeMismatch {
                lhs: ScalarType::Boolean,
                rhs: ScalarType::Integer
            })
        );
    }

    #[test]
    fn test_new_from_iter_deduplicates_duplicate_tuples() -> Result<(), Error> {
        let relation = Relation::new_from_iter(
            Heading::try_from(vec![(AttributeName::from("a"), ScalarType::Integer)]).unwrap(),
            vec![
                Tuple::try_from(vec![(AttributeName::from("a"), Scalar::Integer(1))]).unwrap(),
                Tuple::try_from(vec![(AttributeName::from("a"), Scalar::Integer(1))]).unwrap(),
            ],
        )?;

        assert_eq!(relation.body.len(), 1);
        Ok(())
    }

    #[test]
    fn test_iter_returns_tuples_in_sorted_order() -> Result<(), Error> {
        let relation = Relation::new_from_iter(
            Heading::try_from(vec![(AttributeName::from("a"), ScalarType::Integer)]).unwrap(),
            vec![
                Tuple::try_from(vec![(AttributeName::from("a"), Scalar::Integer(2))]).unwrap(),
                Tuple::try_from(vec![(AttributeName::from("a"), Scalar::Integer(1))]).unwrap(),
            ],
        )?;

        let tuples = relation.iter().cloned().collect::<Vec<_>>();

        assert_eq!(
            tuples,
            vec![
                Tuple::try_from(vec![(AttributeName::from("a"), Scalar::Integer(1))]).unwrap(),
                Tuple::try_from(vec![(AttributeName::from("a"), Scalar::Integer(2))]).unwrap(),
            ]
        );
        Ok(())
    }
}