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
use async_trait::async_trait;
use sqlparser::ast as sqlast;
use crate::compile::error::*;
use crate::compile::schema::*;
use crate::compile::traverse::{SQLVisitor, Visit, VisitSQL, Visitor};
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;
use super::sql::IntoTableFactor;
pub struct ContextInliner {
context: BTreeMap<Ident, Arc<Expr<CRef<MType>>>>,
}
impl SQLVisitor for ContextInliner {}
#[async_trait]
impl Visitor<CRef<MType>> for ContextInliner {
async fn visit_expr(&self, expr: &Expr<CRef<MType>>) -> Result<Option<Expr<CRef<MType>>>> {
Ok(match expr {
Expr::ContextRef(name) => {
if let Some(c) = self.context.get(name) {
Some(c.as_ref().clone())
} else {
None
}
}
_ => None,
})
}
}
pub async fn inline_context(
expr: Arc<Expr<CRef<MType>>>,
context: BTreeMap<Ident, Arc<Expr<CRef<MType>>>>,
) -> Result<Arc<Expr<CRef<MType>>>> {
let visitor = ContextInliner { context };
Ok(Arc::new(expr.visit(&visitor).await?))
}
pub struct ParamInliner {
context: BTreeMap<Ident, SQLBody>,
}
impl ParamInliner {
pub fn new(context: BTreeMap<Ident, SQLBody>) -> Self {
Self { context }
}
}
impl SQLVisitor for ParamInliner {
fn visit_sqlexpr(&self, expr: &sqlast::Expr) -> Option<sqlast::Expr> {
let ident = match expr {
sqlast::Expr::Identifier(x) => x.clone(),
sqlast::Expr::CompoundIdentifier(v) => {
if v.len() != 1 {
return None;
}
v[0].clone()
}
_ => return None,
}
.get()
.into();
if let Some(e) = self.context.get(&ident) {
e.as_expr().ok()
} else {
None
}
}
fn visit_sqltable(&self, table: &sqlast::TableFactor) -> Option<sqlast::TableFactor> {
match table {
sqlast::TableFactor::Table {
name, alias, args, ..
} => {
if name.0.len() != 1 || args.is_some() {
return None;
}
if let Some(e) = self.context.get(&name.0[0].get().into()) {
let new_alias = match alias {
Some(alias) => alias.clone(),
None => sqlast::TableAlias {
name: name.0[0].clone(),
columns: vec![],
},
};
e.as_table(Some(new_alias)).ok()
} else {
None
}
}
_ => None,
}
}
}
#[async_trait]
impl Visitor<CRef<MType>> for ParamInliner {
async fn visit_expr(&self, expr: &Expr<CRef<MType>>) -> Result<Option<Expr<CRef<MType>>>> {
Ok(match expr {
Expr::SQL(sql, url) => {
let SQL { names, body } = sql.as_ref();
let (mut names, params) = (
SQLNames {
params: BTreeMap::new(),
unbound: names.unbound.clone(),
},
names.params.clone(),
);
let mut context = BTreeMap::new();
let mut inlined_params = Vec::new(); // Each paramater, after inlining
let mut remaining_params = 0; // The aggregate number of remaining parameters
let mut conn_strings = BTreeSet::new(); // The connection string for any remote SQL expressions
if let Some(url) = url {
conn_strings.insert(url.clone());
}
for (_, param) in params.iter() {
let expr = inline_params(¶m.expr.unwrap_schema_entry().await?)
.await?
.unwrap_schema_entry()
.await?;
match &expr {
Expr::SQL(sql, inner_url) => {
if let Some(inner_url) = inner_url {
conn_strings.insert(inner_url.clone());
}
remaining_params += sql.names.params.len();
}
Expr::Materialize(MaterializeExpr { url: inner_url, .. }) => {
if let Some(inner_url) = inner_url {
conn_strings.insert(inner_url.clone());
}
}
_ => {
remaining_params += 1;
}
}
inlined_params.push(expr);
}
let can_inline_tables = remaining_params == 0 && conn_strings.len() <= 1;
for ((name, param), expr) in params.into_iter().zip(inlined_params) {
match &expr {
// Only inline SQL expressions that point to the same database.
Expr::SQL(sql, inner_url)
if matches!(inner_url, None) || can_inline_tables =>
{
names.extend(sql.names.clone());
context.insert(name.clone(), sql.body.clone());
}
Expr::Materialize(MaterializeExpr {
expr,
key,
url,
decl_name,
inlined: _,
}) => {
// If we can inline tables, then we can inline materialized expressions (we simply expect them
// to have been saved to the database at some point).
let mut inlined = false;
if can_inline_tables {
context.insert(
name.clone(),
SQLBody::Table(decl_name.to_table_factor()),
);
inlined = true;
}
// Either way, we still want to keep the materialized expression in the param list, to
// force ourselves to either compute or resolve it prior to executing this one
names.params.insert(
name.clone(),
TypedExpr {
type_: param.type_.clone(),
expr: Arc::new(Expr::Materialize(MaterializeExpr {
expr: expr.clone(),
key: key.clone(),
url: url.clone(),
decl_name: decl_name.clone(),
inlined,
})),
},
);
}
_ => {
names.params.insert(
name.clone(),
TypedExpr {
type_: param.type_.clone(),
expr: Arc::new(expr),
},
);
}
}
}
let url = if can_inline_tables {
conn_strings.into_iter().next()
} else {
url.clone()
};
let visitor = ParamInliner { context };
let body = body.visit_sql(&visitor);
Some(Expr::SQL(Arc::new(SQL { names, body }), url))
}
Expr::Materialize(MaterializeExpr {
expr,
key,
url,
decl_name,
inlined,
}) => {
let expr = TypedExpr {
type_: expr.type_.clone(),
expr: Arc::new(inline_params(&expr.expr).await?),
};
let url = match url {
Some(url) => Some(url.clone()),
None => match expr.expr.as_ref() {
Expr::SQL(_, url) => url.clone(),
Expr::Materialize(MaterializeExpr { url, .. }) => url.clone(),
_ => None,
},
};
Some(Expr::Materialize(MaterializeExpr {
expr,
key: key.clone(),
url: url.clone(),
decl_name: decl_name.clone(),
inlined: *inlined,
}))
}
_ => None,
})
}
}
pub async fn inline_params(expr: &Expr<CRef<MType>>) -> Result<Expr<CRef<MType>>> {
let visitor = ParamInliner {
context: BTreeMap::new(),
};
Ok(expr.visit(&visitor).await?)
}