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
//! The [`PlanRewriter`] trait and the [`RewriterPipeline`] that chains
//! rewrite rules together.
//!
//! A rewriter takes a validated [`QueryPlan`] and returns a
//! semantically-equivalent plan that is cheaper to execute. Rules are
//! deliberately small and composable; [`RewriterPipeline`] applies a
//! sequence of them in order, threading each rule's output into the
//! next.
use crateVlorQLError;
use crateQueryPlan;
use fmt;
/// [`QueryPlan`](crate::schema::QueryPlan).
///
/// Implementations must preserve query semantics: the rewritten plan
/// must return the same rows as the input for every database state. A
/// rule that cannot safely rewrite part of a plan must leave that part
/// unchanged rather than guess.
/// Applies an ordered list of [`PlanRewriter`]s, feeding each rule's
/// output into the next.
///
/// The pipeline owns its rules as boxed trait objects so heterogeneous
/// rewriters can be combined. Order matters: constant folding, for
/// example, is usually run before pushdown so folded literals can be
/// analyzed as constants.
///
/// # Examples
///
/// ```
/// use vlorql_core::optimizer::{ConstantFolding, PlanRewriter, RewriterPipeline};
/// use vlorql_core::schema::{
/// BinaryOperator, DataType, Expression, FromClause, Projection, QueryPlan,
/// };
///
/// let plan = QueryPlan {
/// select: vec![Projection::Expr {
/// expression: Expression::BinaryOp {
/// left: Box::new(Expression::Literal { value: 20.into(), data_type: DataType::Int }),
/// op: BinaryOperator::Add,
/// right: Box::new(Expression::Literal { value: 5.into(), data_type: DataType::Int }),
/// },
/// alias: Some("total".to_owned()),
/// }],
/// from: FromClause::table("t".to_owned(), None),
/// r#where: None, group_by: None, having: None,
/// order_by: None, limit: None, offset: None, joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
/// };
///
/// let pipeline = RewriterPipeline::new().with(ConstantFolding);
/// let rewritten = pipeline.rewrite(&plan).unwrap();
/// assert_eq!(
/// rewritten.select[0],
/// Projection::Expr {
/// expression: Expression::Literal { value: 25.into(), data_type: DataType::Int },
/// alias: Some("total".to_owned()),
/// },
/// );
/// ```