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
use mz_compute_client::command::{BuildDesc, DataflowDesc, IndexDesc};
use mz_compute_client::controller::{ComputeController, ComputeInstanceId};
use mz_expr::visit::Visit;
use mz_expr::{
CollectionPlan, MapFilterProject, MirRelationExpr, MirScalarExpr, OptimizedMirRelationExpr,
UnmaterializableFunc,
};
use mz_ore::stack::maybe_grow;
use mz_repr::adt::array::ArrayDimension;
use mz_repr::adt::numeric::Numeric;
use mz_repr::{Datum, GlobalId, Row};
use mz_stash::Append;
use mz_storage::client::sinks::SinkDesc;
use crate::catalog::{CatalogItem, CatalogState};
use crate::coord::{CatalogTxn, Coordinator};
use crate::session::{Session, SERVER_MAJOR_VERSION, SERVER_MINOR_VERSION};
use crate::CoordError;
pub struct DataflowBuilder<'a, T> {
pub catalog: &'a CatalogState,
pub compute: ComputeController<'a, T>,
}
#[derive(Clone, Copy, Debug)]
pub enum ExprPrepStyle<'a> {
Index,
OneShot {
logical_time: Option<u64>,
session: &'a Session,
},
AsOf,
}
impl<S: Append> Coordinator<S> {
pub fn dataflow_builder(
&self,
instance: ComputeInstanceId,
) -> DataflowBuilder<mz_repr::Timestamp> {
let compute = self.dataflow_client.compute(instance).unwrap();
DataflowBuilder {
catalog: self.catalog.state(),
compute,
}
}
}
impl CatalogTxn<'_, mz_repr::Timestamp> {
pub fn dataflow_builder(
&self,
instance: ComputeInstanceId,
) -> DataflowBuilder<mz_repr::Timestamp> {
let compute = self.dataflow_client.compute(instance).unwrap();
DataflowBuilder {
catalog: self.catalog,
compute,
}
}
}
impl<'a> DataflowBuilder<'a, mz_repr::Timestamp> {
fn import_into_dataflow(
&mut self,
id: &GlobalId,
dataflow: &mut DataflowDesc,
) -> Result<(), CoordError> {
maybe_grow(|| {
if dataflow.is_imported(id) {
return Ok(());
}
let index_oracle = self.index_oracle();
let mut valid_indexes = index_oracle.indexes_on(*id).peekable();
if valid_indexes.peek().is_some() {
let mut valid_indexes = valid_indexes.collect::<Vec<_>>();
valid_indexes.sort_by_key(|(_, idx)| &idx.keys);
valid_indexes.dedup_by_key(|(_, idx)| &idx.keys);
for (index_id, idx) in valid_indexes {
let index_desc = IndexDesc {
on_id: *id,
key: idx.keys.to_vec(),
};
let entry = self.catalog.get_entry(id);
let desc = entry
.desc(
&self
.catalog
.resolve_full_name(entry.name(), entry.conn_id()),
)
.expect("indexes can only be built on items with descs");
dataflow.import_index(index_id, index_desc, desc.typ().clone());
}
} else {
drop(valid_indexes);
let entry = self.catalog.get_entry(id);
match entry.item() {
CatalogItem::Table(table) => {
dataflow.import_source(*id, table.desc.typ().clone(), false);
}
CatalogItem::Source(source) => {
dataflow.import_source(
*id,
source.desc.typ().clone(),
source.source_desc.append_only(),
);
}
CatalogItem::View(view) => {
let expr = view.optimized_expr.clone();
self.import_view_into_dataflow(id, &expr, dataflow)?;
}
_ => unreachable!(),
}
}
Ok(())
})
}
pub fn import_view_into_dataflow(
&mut self,
view_id: &GlobalId,
view: &OptimizedMirRelationExpr,
dataflow: &mut DataflowDesc,
) -> Result<(), CoordError> {
for get_id in view.depends_on() {
self.import_into_dataflow(&get_id, dataflow)?;
}
dataflow.insert_plan(*view_id, view.clone());
Ok(())
}
pub fn build_index_dataflow(&mut self, id: GlobalId) -> Result<DataflowDesc, CoordError> {
let index_entry = self.catalog.get_entry(&id);
let index = match index_entry.item() {
CatalogItem::Index(index) => index,
_ => unreachable!("cannot create index dataflow on non-index"),
};
let on_entry = self.catalog.get_entry(&index.on);
let on_type = on_entry
.desc(
&self
.catalog
.resolve_full_name(on_entry.name(), on_entry.conn_id()),
)
.unwrap()
.typ()
.clone();
let name = index_entry.name().to_string();
let mut dataflow = DataflowDesc::new(name);
self.import_into_dataflow(&index.on, &mut dataflow)?;
for BuildDesc { plan, .. } in &mut dataflow.objects_to_build {
prep_relation_expr(self.catalog, plan, ExprPrepStyle::Index)?;
}
let mut index_description = mz_compute_client::command::IndexDesc {
on_id: index.on,
key: index.keys.clone(),
};
for key in &mut index_description.key {
prep_scalar_expr(self.catalog, key, ExprPrepStyle::Index)?;
}
dataflow.export_index(id, index_description, on_type);
mz_transform::optimize_dataflow(&mut dataflow, &self.index_oracle())?;
Ok(dataflow)
}
pub fn build_sink_dataflow(
&mut self,
name: String,
id: GlobalId,
sink_description: SinkDesc,
) -> Result<DataflowDesc, CoordError> {
let mut dataflow = DataflowDesc::new(name);
self.build_sink_dataflow_into(&mut dataflow, id, sink_description)?;
Ok(dataflow)
}
pub fn build_sink_dataflow_into(
&mut self,
dataflow: &mut DataflowDesc,
id: GlobalId,
sink_description: SinkDesc,
) -> Result<(), CoordError> {
dataflow.set_as_of(sink_description.as_of.frontier.clone());
self.import_into_dataflow(&sink_description.from, dataflow)?;
for BuildDesc { plan, .. } in &mut dataflow.objects_to_build {
prep_relation_expr(self.catalog, plan, ExprPrepStyle::Index)?;
}
dataflow.export_sink(id, sink_description);
mz_transform::optimize_dataflow(dataflow, &self.index_oracle())?;
Ok(())
}
}
pub fn prep_relation_expr(
catalog: &CatalogState,
expr: &mut OptimizedMirRelationExpr,
style: ExprPrepStyle,
) -> Result<(), CoordError> {
match style {
ExprPrepStyle::Index => {
expr.0.try_visit_mut_post(&mut |e| {
if let MirRelationExpr::Filter { input, predicates } = &*e {
let mfp =
MapFilterProject::new(input.arity()).filter(predicates.iter().cloned());
match mfp.into_plan() {
Err(e) => coord_bail!("{:?}", e),
Ok(_) => Ok(()),
}
} else {
e.try_visit_scalars_mut1(&mut |s| prep_scalar_expr(catalog, s, style))
}
})
}
ExprPrepStyle::OneShot { .. } | ExprPrepStyle::AsOf => expr
.0
.try_visit_scalars_mut(&mut |s| prep_scalar_expr(catalog, s, style)),
}
}
pub fn prep_scalar_expr(
state: &CatalogState,
expr: &mut MirScalarExpr,
style: ExprPrepStyle,
) -> Result<(), CoordError> {
match style {
ExprPrepStyle::OneShot {
logical_time,
session,
} => {
let mut res = Ok(());
#[allow(deprecated)]
expr.visit_mut_post_nolimit(&mut |e| {
if let MirScalarExpr::CallUnmaterializable(f) = e {
match eval_unmaterializable_func(state, f, logical_time, session) {
Ok(evaled) => *e = evaled,
Err(e) => res = Err(e),
}
}
});
res
}
ExprPrepStyle::Index | ExprPrepStyle::AsOf => {
let mut last_observed_unmaterializable_func = None;
#[allow(deprecated)]
expr.visit_mut_post_nolimit(&mut |e| {
if let MirScalarExpr::CallUnmaterializable(f) = e {
last_observed_unmaterializable_func = Some(f.clone());
}
});
if let Some(f) = last_observed_unmaterializable_func {
let err = match style {
ExprPrepStyle::Index => CoordError::UnmaterializableFunction(f),
ExprPrepStyle::AsOf => CoordError::UncallableFunction {
func: f,
context: "AS OF",
},
_ => unreachable!(),
};
return Err(err);
}
Ok(())
}
}
}
fn eval_unmaterializable_func(
state: &CatalogState,
f: &UnmaterializableFunc,
logical_time: Option<u64>,
session: &Session,
) -> Result<MirScalarExpr, CoordError> {
let pack_1d_array = |datums: Vec<Datum>| {
let mut row = Row::default();
row.packer()
.push_array(
&[ArrayDimension {
lower_bound: 1,
length: datums.len(),
}],
datums,
)
.expect("known to be a valid array");
Ok(MirScalarExpr::Literal(Ok(row), f.output_type()))
};
let pack = |datum| {
Ok(MirScalarExpr::literal_ok(
datum,
f.output_type().scalar_type,
))
};
match f {
UnmaterializableFunc::CurrentDatabase => pack(Datum::from(session.vars().database())),
UnmaterializableFunc::CurrentSchemasWithSystem => {
let search_path = session.vars().search_path();
let mut v = Vec::with_capacity(search_path.len() + 2);
let default_schemas = ["mz_catalog", "pg_catalog"];
for schema in default_schemas {
if !search_path.contains(&schema) {
v.push(Datum::String(schema))
}
}
for schema in search_path {
v.push(Datum::String(schema))
}
pack_1d_array(v)
}
UnmaterializableFunc::CurrentSchemasWithoutSystem => {
use crate::catalog::builtin::{
INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_TEMP_SCHEMA,
PG_CATALOG_SCHEMA,
};
pack_1d_array(
session
.vars()
.search_path()
.iter()
.filter(|s| {
(**s != PG_CATALOG_SCHEMA)
&& (**s != INFORMATION_SCHEMA)
&& (**s != MZ_CATALOG_SCHEMA)
&& (**s != MZ_TEMP_SCHEMA)
&& (**s != MZ_INTERNAL_SCHEMA)
})
.map(|s| Datum::String(s))
.collect(),
)
}
UnmaterializableFunc::CurrentTimestamp => pack(Datum::from(session.pcx().wall_time)),
UnmaterializableFunc::CurrentUser => pack(Datum::from(session.user())),
UnmaterializableFunc::MzClusterId => pack(Datum::from(state.config().cluster_id)),
UnmaterializableFunc::MzLogicalTimestamp => match logical_time {
None => coord_bail!("cannot call mz_logical_timestamp in this context"),
Some(logical_time) => pack(Datum::from(Numeric::from(logical_time))),
},
UnmaterializableFunc::MzSessionId => pack(Datum::from(state.config().session_id)),
UnmaterializableFunc::MzUptime => {
let uptime = state.config().start_instant.elapsed();
let uptime = chrono::Duration::from_std(uptime).map_or(Datum::Null, Datum::from);
pack(uptime)
}
UnmaterializableFunc::MzVersion => {
pack(Datum::from(&*state.config().build_info.human_version()))
}
UnmaterializableFunc::MzVersionNum => {
pack(Datum::Int32(state.config().build_info.version_num()))
}
UnmaterializableFunc::PgBackendPid => pack(Datum::Int32(session.conn_id() as i32)),
UnmaterializableFunc::PgPostmasterStartTime => pack(Datum::from(state.config().start_time)),
UnmaterializableFunc::Version => {
let build_info = state.config().build_info;
let version = format!(
"PostgreSQL {}.{} on {} (materialized {})",
SERVER_MAJOR_VERSION,
SERVER_MINOR_VERSION,
mz_build_info::TARGET_TRIPLE,
build_info.version,
);
pack(Datum::from(&*version))
}
}
}