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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// Copyright Materialize, Inc. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Replace operators on constants collections with constant collections.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::iter;

use expr::RelationExpr;
use repr::{Datum, RowArena};

use crate::{TransformArgs, TransformError};

pub use demorgans::DeMorgans;
pub use negate_predicate::NegatePredicate;
pub use undistribute_and::UndistributeAnd;

/// Replace operators on constants collections with constant collections.
#[derive(Debug)]
pub struct FoldConstants;

impl crate::Transform for FoldConstants {
    fn transform(
        &self,
        relation: &mut RelationExpr,
        _: TransformArgs,
    ) -> Result<(), TransformError> {
        relation.try_visit_mut(&mut |e| self.action(e))
    }
}

impl FoldConstants {
    /// Replace operators on constants collections with constant collections.
    pub fn action(&self, relation: &mut RelationExpr) -> Result<(), TransformError> {
        let relation_type = relation.typ();
        match relation {
            RelationExpr::Constant { .. } => { /* handled after match */ }
            RelationExpr::Get { .. } => {}
            RelationExpr::Let { .. } => { /* constant prop done in InlineLet */ }
            RelationExpr::Reduce {
                input,
                group_key,
                aggregates,
                monotonic: _,
                expected_group_size: _,
            } => {
                for aggregate in aggregates.iter_mut() {
                    aggregate.expr.reduce(&input.typ());
                }
                if let RelationExpr::Constant { rows, .. } = &**input {
                    // Build a map from `group_key` to `Vec<Vec<an, ..., a1>>)`,
                    // where `an` is the input to the nth aggregate function in
                    // `aggregates`.
                    let mut groups = BTreeMap::new();
                    let temp_storage2 = RowArena::new();
                    let mut row_packer = repr::RowPacker::new();
                    for (row, diff) in rows {
                        // We currently maintain the invariant that any negative
                        // multiplicities will be consolidated away before they
                        // arrive at a reduce.
                        assert!(
                            *diff > 0,
                            "constant folding encountered reduce on collection \
                             with non-positive multiplicities"
                        );
                        let datums = row.unpack();
                        let temp_storage = RowArena::new();
                        let key = group_key
                            .iter()
                            .map(|e| e.eval(&datums, &temp_storage2))
                            .collect::<Result<Vec<_>, _>>()?;
                        let val = aggregates
                            .iter()
                            .map(|agg| {
                                Ok::<_, TransformError>(
                                    row_packer.pack(&[agg.expr.eval(&datums, &temp_storage)?]),
                                )
                            })
                            .collect::<Result<Vec<_>, _>>()?;
                        let entry = groups.entry(key).or_insert_with(Vec::new);
                        for _ in 0..*diff {
                            entry.push(val.clone());
                        }
                    }

                    // For each group, apply the aggregate function to the rows
                    // in the group. The output is
                    // `Vec<Vec<k1, ..., kn, r1, ..., rn>>`
                    // where kn is the nth column of the key and rn is the
                    // result of the nth aggregate function for that group.
                    let new_rows = groups
                        .into_iter()
                        .map({
                            let mut row_packer = repr::RowPacker::new();
                            move |(key, vals)| {
                                let temp_storage = RowArena::new();
                                let row = row_packer.pack(key.into_iter().chain(
                                    aggregates.iter().enumerate().map(|(i, agg)| {
                                        if agg.distinct {
                                            agg.func.eval(
                                                vals.iter()
                                                    .map(|val| val[i].unpack_first())
                                                    .collect::<HashSet<_>>()
                                                    .into_iter(),
                                                &temp_storage,
                                            )
                                        } else {
                                            agg.func.eval(
                                                vals.iter().map(|val| val[i].unpack_first()),
                                                &temp_storage,
                                            )
                                        }
                                    }),
                                ));
                                (row, 1)
                            }
                        })
                        .collect();

                    *relation = RelationExpr::Constant {
                        rows: new_rows,
                        typ: relation.typ(),
                    };
                }
            }
            RelationExpr::TopK { .. } => { /*too complicated*/ }
            RelationExpr::Negate { input } => {
                if let RelationExpr::Constant { rows, .. } = &mut **input {
                    for (_row, diff) in rows {
                        *diff *= -1;
                    }
                    *relation = input.take_dangerous();
                }
            }
            RelationExpr::Threshold { input } => {
                if let RelationExpr::Constant { rows, .. } = &mut **input {
                    rows.retain(|(_, diff)| *diff > 0);
                    *relation = input.take_dangerous();
                }
            }
            RelationExpr::Map { input, scalars } => {
                // Before reducing the scalar expressions, we need to form an appropriate
                // RelationType to provide to each. Each expression needs a different
                // relation type; although we could in principle use `relation_type` here,
                // we shouldn't rely on `reduce` not looking at its cardinality to assess
                // the number of columns.
                let input_arity = input.arity();
                for (index, scalar) in scalars.iter_mut().enumerate() {
                    let mut current_type = repr::RelationType::new(
                        relation_type.column_types[..(input_arity + index)].to_vec(),
                    );
                    for key in relation_type.keys.iter() {
                        if key.iter().all(|i| *i < input_arity + index) {
                            current_type = current_type.with_key(key.clone());
                        }
                    }
                    scalar.reduce(&current_type);
                }

                if let RelationExpr::Constant { rows, .. } = &**input {
                    let mut row_packer = repr::RowPacker::new();
                    let new_rows = rows
                        .iter()
                        .cloned()
                        .map(|(input_row, diff)| {
                            let mut unpacked = input_row.unpack();
                            let temp_storage = RowArena::new();
                            for scalar in scalars.iter() {
                                unpacked.push(scalar.eval(&unpacked, &temp_storage)?)
                            }
                            Ok::<_, TransformError>((row_packer.pack(unpacked), diff))
                        })
                        .collect::<Result<_, _>>()?;
                    *relation = RelationExpr::Constant {
                        rows: new_rows,
                        typ: relation.typ(),
                    };
                }
            }
            RelationExpr::FlatMap {
                input,
                func,
                exprs,
                demand: _,
            } => {
                for expr in exprs.iter_mut() {
                    expr.reduce(&input.typ());
                }

                if let RelationExpr::Constant { rows, .. } = &**input {
                    let mut new_rows = Vec::new();
                    let mut row_packer = repr::RowPacker::new();
                    for (input_row, diff) in rows {
                        let datums = input_row.unpack();
                        let temp_storage = RowArena::new();
                        let output_rows = func.eval(
                            exprs
                                .iter()
                                .map(|expr| expr.eval(&datums, &temp_storage))
                                .collect::<Result<Vec<_>, _>>()?,
                            &temp_storage,
                        );
                        for (output_row, diff2) in output_rows {
                            let row = row_packer
                                .pack(input_row.clone().into_iter().chain(output_row.into_iter()));
                            new_rows.push((row, diff2 * *diff))
                        }
                    }
                    *relation = RelationExpr::Constant {
                        rows: new_rows,
                        typ: relation.typ(),
                    };
                }
            }
            RelationExpr::Filter { input, predicates } => {
                for predicate in predicates.iter_mut() {
                    predicate.reduce(&input.typ());
                }
                predicates.retain(|p| !p.is_literal_true());

                // If any predicate is false, reduce to the empty collection.
                if predicates
                    .iter()
                    .any(|p| p.is_literal_false() || p.is_literal_null())
                {
                    relation.take_safely();
                } else if let RelationExpr::Constant { rows, .. } = &**input {
                    let mut new_rows = Vec::new();
                    'outer: for (row, diff) in rows {
                        let datums = row.unpack();
                        let temp_storage = RowArena::new();
                        for p in &*predicates {
                            if p.eval(&datums, &temp_storage)? != Datum::True {
                                continue 'outer;
                            }
                        }
                        new_rows.push((row.clone(), *diff))
                    }
                    *relation = RelationExpr::Constant {
                        rows: new_rows,
                        typ: relation.typ(),
                    };
                }
            }
            RelationExpr::Project { input, outputs } => {
                if let RelationExpr::Constant { rows, .. } = &**input {
                    let mut row_packer = repr::RowPacker::new();
                    let new_rows = rows
                        .iter()
                        .map(|(input_row, diff)| {
                            let datums = input_row.unpack();
                            (row_packer.pack(outputs.iter().map(|i| &datums[*i])), *diff)
                        })
                        .collect();
                    *relation = RelationExpr::Constant {
                        rows: new_rows,
                        typ: relation.typ(),
                    };
                }
            }
            RelationExpr::Join {
                inputs,
                equivalences,
                ..
            } => {
                if inputs.iter().any(|e| e.is_empty()) {
                    relation.take_safely();
                } else if inputs
                    .iter()
                    .all(|i| matches!(i, RelationExpr::Constant { .. }))
                {
                    // We can fold all constant inputs together, but must apply the constraints to restrict them.
                    // We start with a single 0-ary row.
                    let mut old_rows = vec![(repr::Row::pack::<_, Datum>(None), 1)];
                    let mut row_packer = repr::RowPacker::new();
                    for input in inputs.iter() {
                        if let RelationExpr::Constant { rows, .. } = input {
                            let mut next_rows = Vec::new();
                            for (old_row, old_count) in old_rows {
                                for (new_row, new_count) in rows.iter() {
                                    let old_datums = old_row.unpack();
                                    let new_datums = new_row.unpack();
                                    next_rows.push((
                                        row_packer.pack(old_datums.iter().chain(new_datums.iter())),
                                        old_count * *new_count,
                                    ));
                                }
                            }
                            old_rows = next_rows;
                        }
                    }

                    // Now throw away anything that doesn't satisfy the requisite constraints.
                    old_rows.retain(|(row, _count)| {
                        let datums = row.unpack();
                        let temp_storage = RowArena::new();
                        equivalences.iter().all(|equivalence| {
                            let mut values =
                                equivalence.iter().map(|e| e.eval(&datums, &temp_storage));
                            if let Some(value) = values.next() {
                                values.all(|v| v == value)
                            } else {
                                true
                            }
                        })
                    });

                    let typ = relation.typ();
                    *relation = RelationExpr::Constant {
                        rows: old_rows,
                        typ,
                    };
                }
                // TODO: General constant folding for all constant inputs.
            }
            RelationExpr::Union { base, inputs } => {
                let mut rows = vec![];
                let mut new_inputs = vec![];

                for input in iter::once(&mut **base).chain(&mut *inputs) {
                    match input.take_dangerous() {
                        RelationExpr::Constant { rows: rs, typ: _ } => rows.extend(rs),
                        input => new_inputs.push(input),
                    }
                }
                if !rows.is_empty() {
                    new_inputs.push(RelationExpr::Constant {
                        rows,
                        typ: relation_type.clone(),
                    });
                }

                *relation = RelationExpr::union_many(new_inputs, relation_type);
            }
            RelationExpr::ArrangeBy { input, .. } => {
                if let RelationExpr::Constant { .. } = &**input {
                    *relation = input.take_dangerous();
                }
            }
        }

        // This transformation maintains the invariant that all constant nodes
        // will be consolidated. We have to make a separate check for constant
        // nodes here, since the match arm above might install new constant
        // nodes.
        if let RelationExpr::Constant { rows, typ } = relation {
            // Reduce down to canonical representation.
            let mut accum = HashMap::new();
            for (row, cnt) in rows.iter() {
                *accum.entry(row.clone()).or_insert(0) += cnt;
            }
            accum.retain(|_k, v| v != &0);
            rows.clear();
            rows.extend(accum.into_iter());
            rows.sort();

            // Re-establish nullability of each column.
            for col_type in typ.column_types.iter_mut() {
                col_type.nullable = false;
            }
            for (row, _) in rows.iter_mut() {
                let datums = row.unpack();
                for (index, datum) in datums.iter().enumerate() {
                    if datum.is_null() {
                        typ.column_types[index].nullable = true;
                    }
                }
            }
        }

        Ok(())
    }
}

/// Transforms !(a && b) into !a || !b and !(a || b) into !a && !b
pub mod demorgans {

    use expr::{BinaryFunc, RelationExpr, ScalarExpr, UnaryFunc};

    use crate::{TransformArgs, TransformError};

    /// Transforms !(a && b) into !a || !b and !(a || b) into !a && !b
    #[derive(Debug)]
    pub struct DeMorgans;
    impl crate::Transform for DeMorgans {
        fn transform(
            &self,
            relation: &mut RelationExpr,
            _: TransformArgs,
        ) -> Result<(), TransformError> {
            relation.visit_mut_pre(&mut |e| {
                self.action(e);
            });
            Ok(())
        }
    }

    impl DeMorgans {
        /// Transforms !(a && b) into !a || !b and !(a || b) into !a && !b
        pub fn action(&self, relation: &mut RelationExpr) {
            if let RelationExpr::Filter {
                input: _,
                predicates,
            } = relation
            {
                for predicate in predicates.iter_mut() {
                    demorgans(predicate);
                }
            }
        }
    }

    /// Transforms !(a && b) into !a || !b and !(a || b) into !a && !b
    pub fn demorgans(expr: &mut ScalarExpr) {
        if let ScalarExpr::CallUnary {
            expr: inner,
            func: UnaryFunc::Not,
        } = expr
        {
            if let ScalarExpr::CallBinary { expr1, expr2, func } = &mut **inner {
                match func {
                    BinaryFunc::And => {
                        let inner0 = ScalarExpr::CallUnary {
                            expr: Box::new(expr1.take()),
                            func: UnaryFunc::Not,
                        };
                        let inner1 = ScalarExpr::CallUnary {
                            expr: Box::new(expr2.take()),
                            func: UnaryFunc::Not,
                        };
                        *expr = ScalarExpr::CallBinary {
                            expr1: Box::new(inner0),
                            expr2: Box::new(inner1),
                            func: BinaryFunc::Or,
                        }
                    }
                    BinaryFunc::Or => {
                        let inner0 = ScalarExpr::CallUnary {
                            expr: Box::new(expr1.take()),
                            func: UnaryFunc::Not,
                        };
                        let inner1 = ScalarExpr::CallUnary {
                            expr: Box::new(expr2.take()),
                            func: UnaryFunc::Not,
                        };
                        *expr = ScalarExpr::CallBinary {
                            expr1: Box::new(inner0),
                            expr2: Box::new(inner1),
                            func: BinaryFunc::And,
                        }
                    }
                    _ => {}
                }
            }
        }
    }
}

/// Transforms predicates from (a && b) || (a && c) into a && (b || c).
pub mod undistribute_and {

    use expr::{BinaryFunc, RelationExpr, ScalarExpr};
    use repr::{Datum, ScalarType};

    use crate::{TransformArgs, TransformError};

    /// Transforms predicates from (a && b) || (a && c) into a && (b || c).
    #[derive(Debug)]
    pub struct UndistributeAnd;

    impl crate::Transform for UndistributeAnd {
        fn transform(
            &self,
            relation: &mut RelationExpr,
            _: TransformArgs,
        ) -> Result<(), TransformError> {
            relation.visit_mut(&mut |e| {
                self.action(e);
            });
            Ok(())
        }
    }

    impl UndistributeAnd {
        /// Transforms predicates from (a && b) || (a && c) into a && (b || c).
        pub fn action(&self, relation: &mut RelationExpr) {
            if let RelationExpr::Filter {
                input: _,
                predicates,
            } = relation
            {
                for predicate in predicates.iter_mut() {
                    undistribute_and(predicate);
                }
            }
        }
    }

    /// Collects undistributable terms from AND expressions.
    fn harvest_ands(expr: &ScalarExpr, ands: &mut Vec<ScalarExpr>) {
        if let ScalarExpr::CallBinary {
            expr1,
            expr2,
            func: BinaryFunc::And,
        } = expr
        {
            harvest_ands(expr1, ands);
            harvest_ands(expr2, ands);
        } else {
            ands.push(expr.clone())
        }
    }

    /// Removes undistributed terms from AND expressions.
    fn suppress_ands(expr: &mut ScalarExpr, ands: &[ScalarExpr]) {
        if let ScalarExpr::CallBinary {
            expr1,
            expr2,
            func: BinaryFunc::And,
        } = expr
        {
            // Suppress the ands in children.
            suppress_ands(expr1, ands);
            suppress_ands(expr2, ands);

            // If either argument is in our list, replace it by `true`.
            let tru = ScalarExpr::literal_ok(Datum::True, ScalarType::Bool.nullable(false));
            if ands.contains(expr1) {
                *expr = std::mem::replace(expr2, tru);
            } else if ands.contains(expr2) {
                *expr = std::mem::replace(expr1, tru);
            }
        }
    }

    /// Transforms (a && b) || (a && c) into a && (b || c)
    pub fn undistribute_and(expr: &mut ScalarExpr) {
        expr.visit_mut(&mut |x| undistribute_and_helper(x));
    }

    /// AND undistribution to apply at each `ScalarExpr`.
    pub fn undistribute_and_helper(expr: &mut ScalarExpr) {
        if let ScalarExpr::CallBinary {
            expr1,
            expr2,
            func: BinaryFunc::Or,
        } = expr
        {
            let mut ands0 = Vec::new();
            harvest_ands(expr1, &mut ands0);

            let mut ands1 = Vec::new();
            harvest_ands(expr2, &mut ands1);

            let mut intersection = Vec::new();
            for expr in ands0.into_iter() {
                if ands1.contains(&expr) {
                    intersection.push(expr);
                }
            }

            if !intersection.is_empty() {
                suppress_ands(expr1, &intersection[..]);
                suppress_ands(expr2, &intersection[..]);
            }

            for and_term in intersection.into_iter() {
                *expr = ScalarExpr::CallBinary {
                    expr1: Box::new(expr.take()),
                    expr2: Box::new(and_term),
                    func: BinaryFunc::And,
                };
            }
        }
    }
}

/// Transforms `NOT(a <op> b)` to `a negate(<op>) b` if it exists.
pub mod negate_predicate {
    use expr::{BinaryFunc, RelationExpr, ScalarExpr, UnaryFunc};

    use crate::{TransformArgs, TransformError};

    /// Transforms `NOT(a <op> b)` to `a negate(<op>) b`.
    #[derive(Debug)]
    pub struct NegatePredicate;

    impl crate::Transform for NegatePredicate {
        fn transform(
            &self,
            relation: &mut RelationExpr,
            _: TransformArgs,
        ) -> Result<(), TransformError> {
            self.action(relation);
            Ok(())
        }
    }

    /// Returns the negation of the given binary function, if it exists.
    fn negate(f: &BinaryFunc) -> Option<BinaryFunc> {
        match f {
            BinaryFunc::Eq => Some(BinaryFunc::NotEq),
            BinaryFunc::NotEq => Some(BinaryFunc::Eq),
            BinaryFunc::Lt => Some(BinaryFunc::Gte),
            BinaryFunc::Gte => Some(BinaryFunc::Lt),
            BinaryFunc::Gt => Some(BinaryFunc::Lte),
            BinaryFunc::Lte => Some(BinaryFunc::Gt),
            _ => None,
        }
    }

    impl NegatePredicate {
        /// Transforms `NOT(a <op> b)` to `a negate(<op>) b` if it exists.
        pub fn action(&self, relation: &mut RelationExpr) {
            relation.visit_scalars_mut(&mut |x| x.visit_mut(&mut negate_predicate))
        }
    }

    /// Transforms `NOT(a <op> b)` to `a negate(<op>) b` if it exists.
    pub fn negate_predicate(expr: &mut ScalarExpr) {
        if let ScalarExpr::CallUnary {
            expr: not_input,
            func: UnaryFunc::Not,
        } = expr
        {
            match &mut **not_input {
                ScalarExpr::CallBinary { expr1, expr2, func } => {
                    if let Some(negated_func) = negate(func) {
                        *expr = ScalarExpr::CallBinary {
                            expr1: Box::new(expr1.take()),
                            expr2: Box::new(expr2.take()),
                            func: negated_func,
                        }
                    }
                }
                ScalarExpr::CallUnary {
                    expr: inner_expr,
                    func: UnaryFunc::Not,
                } => *expr = inner_expr.take(),
                _ => {}
            }
        }
    }
}