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
// Copyright Materialize, Inc. and contributors. 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.

//! Hoist projections through operators.
//!
//! Projections can be re-introduced in the physical planning stage.

use std::collections::HashMap;
use std::mem;

use crate::TransformArgs;
use mz_expr::{Id, MirRelationExpr, RECURSION_LIMIT};
use mz_ore::stack::{CheckedRecursion, RecursionGuard};

/// Hoist projections through operators.
#[derive(Debug)]
pub struct ProjectionLifting {
    recursion_guard: RecursionGuard,
}

impl Default for ProjectionLifting {
    fn default() -> ProjectionLifting {
        ProjectionLifting {
            recursion_guard: RecursionGuard::with_limit(RECURSION_LIMIT),
        }
    }
}

impl CheckedRecursion for ProjectionLifting {
    fn recursion_guard(&self) -> &RecursionGuard {
        &self.recursion_guard
    }
}

impl crate::Transform for ProjectionLifting {
    fn transform(
        &self,
        relation: &mut MirRelationExpr,
        _: TransformArgs,
    ) -> Result<(), crate::TransformError> {
        self.action(relation, &mut HashMap::new())
    }
}

impl ProjectionLifting {
    /// Hoist projections through operators.
    pub fn action(
        &self,
        relation: &mut MirRelationExpr,
        // Map from names to new get type and projection required at use.
        gets: &mut HashMap<Id, (mz_repr::RelationType, Vec<usize>)>,
    ) -> Result<(), crate::TransformError> {
        self.checked_recur(|_| {
            match relation {
                MirRelationExpr::Constant { .. } => Ok(()),
                MirRelationExpr::Get { id, .. } => {
                    if let Some((typ, columns)) = gets.get(id) {
                        *relation = MirRelationExpr::Get {
                            id: *id,
                            typ: typ.clone(),
                        }
                        .project(columns.clone());
                    }
                    Ok(())
                }
                MirRelationExpr::Let { id, value, body } => {
                    self.action(value, gets)?;
                    let id = Id::Local(*id);
                    if let MirRelationExpr::Project { input, outputs } = &mut **value {
                        let typ = input.typ();
                        let prior = gets.insert(id, (typ, outputs.clone()));
                        assert!(!prior.is_some());
                        **value = input.take_dangerous();
                    }

                    self.action(body, gets)?;
                    gets.remove(&id);
                    Ok(())
                }
                MirRelationExpr::Project { input, outputs } => {
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs: inner_outputs,
                    } = &mut **input
                    {
                        for output in outputs.iter_mut() {
                            *output = inner_outputs[*output];
                        }
                        **input = inner.take_dangerous();
                    }
                    Ok(())
                }
                MirRelationExpr::Map { input, scalars } => {
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs,
                    } = &mut **input
                    {
                        // Retain projected columns and scalar columns.
                        let mut new_outputs = outputs.clone();
                        let inner_arity = inner.arity();
                        new_outputs.extend(inner_arity..(inner_arity + scalars.len()));

                        // Rewrite scalar expressions using inner columns.
                        for scalar in scalars.iter_mut() {
                            scalar.permute(&new_outputs);
                        }

                        *relation = inner
                            .take_dangerous()
                            .map(scalars.clone())
                            .project(new_outputs);
                    }
                    Ok(())
                }
                MirRelationExpr::FlatMap { input, func, exprs } => {
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs,
                    } = &mut **input
                    {
                        // Retain projected columns and scalar columns.
                        let mut new_outputs = outputs.clone();
                        let inner_arity = inner.arity();
                        new_outputs.extend(inner_arity..(inner_arity + func.output_arity()));

                        // Rewrite scalar expression using inner columns.
                        for expr in exprs.iter_mut() {
                            expr.permute(&new_outputs);
                        }

                        *relation = inner
                            .take_dangerous()
                            .flat_map(func.clone(), exprs.clone())
                            .project(new_outputs);
                    }
                    Ok(())
                }
                MirRelationExpr::Filter { input, predicates } => {
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs,
                    } = &mut **input
                    {
                        // Rewrite scalar expressions using inner columns.
                        for predicate in predicates.iter_mut() {
                            predicate.permute(outputs);
                        }
                        *relation = inner
                            .take_dangerous()
                            .filter(predicates.clone())
                            .project(outputs.clone());
                    }
                    Ok(())
                }
                MirRelationExpr::Join {
                    inputs,
                    equivalences,
                    implementation,
                } => {
                    for input in inputs.iter_mut() {
                        self.action(input, gets)?;
                    }

                    // Track the location of the projected columns in the un-projected join.
                    let mut projection = Vec::new();
                    let mut temp_arity = 0;

                    for join_input in inputs.iter_mut() {
                        if let MirRelationExpr::Project { input, outputs } = join_input {
                            for output in outputs.iter() {
                                projection.push(temp_arity + *output);
                            }
                            temp_arity += input.arity();
                            *join_input = input.take_dangerous();
                        } else {
                            let arity = join_input.arity();
                            projection.extend(temp_arity..(temp_arity + arity));
                            temp_arity += arity;
                        }
                    }

                    if projection.len() != temp_arity || (0..temp_arity).any(|i| projection[i] != i)
                    {
                        // Update equivalences and implementation.
                        for equivalence in equivalences.iter_mut() {
                            for expr in equivalence {
                                expr.permute(&projection[..]);
                            }
                        }

                        *implementation = mz_expr::JoinImplementation::Unimplemented;

                        *relation = relation.take_dangerous().project(projection);
                    }
                    Ok(())
                }
                MirRelationExpr::Reduce {
                    input,
                    group_key,
                    aggregates,
                    monotonic: _,
                    expected_group_size: _,
                } => {
                    // Reduce *absorbs* projections, which is amazing!
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs,
                    } = &mut **input
                    {
                        for key in group_key.iter_mut() {
                            key.permute(outputs);
                        }
                        for aggregate in aggregates.iter_mut() {
                            aggregate.expr.permute(outputs);
                        }
                        **input = inner.take_dangerous();
                    }
                    Ok(())
                }
                MirRelationExpr::TopK {
                    input,
                    group_key,
                    order_key,
                    limit,
                    offset,
                    monotonic: _,
                } => {
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs,
                    } = &mut **input
                    {
                        for key in group_key.iter_mut() {
                            *key = outputs[*key];
                        }
                        for key in order_key.iter_mut() {
                            key.column = outputs[key.column];
                        }
                        *relation = inner
                            .take_dangerous()
                            .top_k(
                                group_key.clone(),
                                order_key.clone(),
                                limit.clone(),
                                offset.clone(),
                            )
                            .project(outputs.clone());
                    }
                    Ok(())
                }
                MirRelationExpr::Negate { input } => {
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs,
                    } = &mut **input
                    {
                        *relation = inner.take_dangerous().negate().project(outputs.clone());
                    }
                    Ok(())
                }
                MirRelationExpr::Threshold { input } => {
                    // We cannot, in general, lift projections out of threshold.
                    // If we could reason that the input cannot be negative, we
                    // would be able to lift the projection, but otherwise our
                    // action on weights need to accumulate the restricted rows.
                    self.action(input, gets)
                }
                MirRelationExpr::Union { base, inputs } => {
                    // We cannot, in general, lift projections out of unions.
                    self.action(base, gets)?;
                    for input in &mut *inputs {
                        self.action(input, gets)?;
                    }

                    if let MirRelationExpr::Project {
                        input: base_input,
                        outputs: base_outputs,
                    } = &mut **base
                    {
                        let base_typ = base_input.typ();

                        let mut can_lift = true;
                        for input in &mut *inputs {
                            match input {
                                MirRelationExpr::Project { input, outputs }
                                    if input.typ() == base_typ && outputs == base_outputs => {}
                                _ => {
                                    can_lift = false;
                                    break;
                                }
                            }
                        }

                        if can_lift {
                            let base_outputs = mem::take(base_outputs);
                            **base = base_input.take_dangerous();
                            for inp in inputs {
                                match inp {
                                    MirRelationExpr::Project { input, .. } => {
                                        *inp = input.take_dangerous();
                                    }
                                    _ => unreachable!(),
                                }
                            }
                            *relation = relation.take_dangerous().project(base_outputs);
                        }
                    }
                    Ok(())
                }
                MirRelationExpr::ArrangeBy { input, keys } => {
                    self.action(input, gets)?;
                    if let MirRelationExpr::Project {
                        input: inner,
                        outputs,
                    } = &mut **input
                    {
                        for key_set in keys.iter_mut() {
                            for key in key_set.iter_mut() {
                                key.permute(outputs);
                            }
                        }
                        *relation = inner
                            .take_dangerous()
                            .arrange_by(keys)
                            .project(outputs.clone());
                    }
                    Ok(())
                }
            }
        })
    }
}