forked from databendlabs/databend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtual_column.rs
More file actions
780 lines (723 loc) · 27.8 KB
/
Copy pathvirtual_column.rs
File metadata and controls
780 lines (723 loc) · 27.8 KB
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
// Copyright 2021 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use databend_common_ast::ast::BinaryOperator;
use databend_common_ast::ast::CTE;
use databend_common_ast::ast::ColumnID;
use databend_common_ast::ast::ColumnRef;
use databend_common_ast::ast::Expr;
use databend_common_ast::ast::Identifier;
use databend_common_ast::ast::Literal;
use databend_common_ast::ast::MapAccessor;
use databend_common_ast::ast::RefreshVirtualColumnStmt;
use databend_common_ast::ast::SelectStmt;
use databend_common_ast::ast::SelectTarget;
use databend_common_ast::ast::SetExpr;
use databend_common_ast::ast::ShowLimit;
use databend_common_ast::ast::ShowVirtualColumnsStmt;
use databend_common_ast::ast::TableReference;
use databend_common_ast::ast::VacuumVirtualColumnStmt;
use databend_common_ast::ast::With;
use databend_common_ast::ast::quote::QuotedString;
use databend_common_ast::visit::VisitControl;
use databend_common_ast::visit::Visitor;
use databend_common_ast::visit::VisitorMut;
use databend_common_ast::visit::Walk;
use databend_common_ast::visit::WalkMut;
use databend_common_exception::ErrorCode;
use databend_common_exception::Result;
use log::debug;
use crate::BindContext;
use crate::NameResolutionContext;
use crate::SelectBuilder;
use crate::binder::Binder;
use crate::normalize_identifier;
use crate::plans::Plan;
use crate::plans::RefreshSelection;
use crate::plans::RefreshVirtualColumnPlan;
use crate::plans::RewriteKind;
use crate::plans::VacuumVirtualColumnPlan;
const MATERIALIZED_CTE_VIRTUAL_COLUMN_PREFIX: &str = "__databend_virtual_column__";
impl Binder {
#[async_backtrace::framed]
pub(in crate::planner::binder) async fn bind_refresh_virtual_column(
&mut self,
stmt: &RefreshVirtualColumnStmt,
) -> Result<Plan> {
let RefreshVirtualColumnStmt {
catalog,
database,
table,
selection,
limit,
overwrite,
} = stmt;
let (catalog, database, table) =
self.normalize_object_identifier_triple(catalog, database, table);
let parsed_selection = if let Some(selection) = selection {
Some(self.parse_refresh_virtual_column_selection(selection)?)
} else {
None
};
Ok(Plan::RefreshVirtualColumn(Box::new(
RefreshVirtualColumnPlan {
catalog,
database,
table,
limit: *limit,
overwrite: *overwrite,
selection: parsed_selection,
},
)))
}
#[async_backtrace::framed]
pub(in crate::planner::binder) async fn bind_show_virtual_columns(
&mut self,
bind_context: &mut BindContext,
stmt: &ShowVirtualColumnsStmt,
) -> Result<Plan> {
let ShowVirtualColumnsStmt {
catalog,
database,
table,
limit,
} = stmt;
let catalog_name = match catalog {
None => self.ctx.get_current_catalog(),
Some(ident) => {
let catalog = normalize_identifier(ident, &self.name_resolution_ctx).name;
self.ctx.get_catalog(&catalog).await?;
catalog
}
};
let catalog = self.ctx.get_catalog(&catalog_name).await?;
let database = match database {
None => self.ctx.get_current_database(),
Some(ident) => {
let database = normalize_identifier(ident, &self.name_resolution_ctx).name;
catalog
.get_database(&self.ctx.get_tenant(), &database)
.await?;
database
}
};
let mut select_builder = SelectBuilder::from("default.system.virtual_columns");
select_builder
.with_column("database")
.with_column("table")
.with_column("source_column")
.with_column("virtual_column_id")
.with_column("virtual_column_name")
.with_column("virtual_column_type");
select_builder.with_filter(format!("database = {}", QuotedString(&database, '\'')));
if let Some(table) = table {
let table = normalize_identifier(table, &self.name_resolution_ctx).name;
select_builder.with_filter(format!("table = {}", QuotedString(table, '\'')));
}
let query = match limit {
None => select_builder.build(),
Some(ShowLimit::Like { pattern }) => {
select_builder.with_filter(format!(
"virtual_column_name LIKE {}",
QuotedString(pattern, '\'')
));
select_builder.build()
}
Some(ShowLimit::Where { selection }) => {
select_builder.with_filter(format!("({selection})"));
select_builder.build()
}
};
debug!("show virtual columns rewrite to: {:?}", query);
self.bind_rewrite_to_query(bind_context, &query, RewriteKind::ShowVirtualColumns)
.await
}
#[async_backtrace::framed]
pub(in crate::planner::binder) async fn bind_vacuum_virtual_column(
&mut self,
stmt: &VacuumVirtualColumnStmt,
) -> Result<Plan> {
let VacuumVirtualColumnStmt {
catalog,
database,
table,
} = stmt;
let (catalog, database, table) =
self.normalize_object_identifier_triple(catalog, database, table);
Ok(Plan::VacuumVirtualColumn(Box::new(
VacuumVirtualColumnPlan {
catalog,
database,
table,
},
)))
}
fn parse_refresh_virtual_column_selection(&self, expr: &Expr) -> Result<RefreshSelection> {
match expr {
Expr::BinaryOp {
op, left, right, ..
} if op == &BinaryOperator::Eq => {
if let Some(selection) =
self.try_build_selection_from_operands(left.as_ref(), right.as_ref())?
{
return Ok(selection);
}
if let Some(selection) =
self.try_build_selection_from_operands(right.as_ref(), left.as_ref())?
{
return Ok(selection);
}
Err(ErrorCode::BadArguments(
"Only equality predicate between segment_location, block_location and string literal is supported",
))
}
_ => Err(ErrorCode::BadArguments(
"Only equality predicate between segment_location, block_location and string literal is supported",
)),
}
}
fn try_build_selection_from_operands(
&self,
column_expr: &Expr,
literal_expr: &Expr,
) -> Result<Option<RefreshSelection>> {
let column_name = match column_expr {
Expr::ColumnRef {
column:
ColumnRef {
database: None,
table: None,
column: ColumnID::Name(ident),
},
..
} => normalize_identifier(ident, &self.name_resolution_ctx).name,
_ => {
return Ok(None);
}
};
let literal_value = match literal_expr {
Expr::Literal {
value: Literal::String(value),
..
} => value.clone(),
_ => {
return Ok(None);
}
};
let column_name_lower = column_name.to_lowercase();
match column_name_lower.as_str() {
"block_location" => Ok(Some(RefreshSelection::BlockLocation(literal_value))),
"segment_location" => Ok(Some(RefreshSelection::SegmentLocation(literal_value))),
_ => Ok(None),
}
}
/// Rewrites JSON path accesses on materialized CTE outputs back into the CTE producer.
///
/// Materializing a CTE can hide the original base-table variant column from later binding.
/// For example, after `logs` is materialized, the consumer only sees `message`:
///
/// ```sql
/// WITH logs AS (
/// SELECT v['message'] AS message
/// FROM t
/// )
/// SELECT message['attribute']['user_id']
/// FROM logs;
/// ```
///
/// Without this rewrite, the final access is bound against the materialized CTE output
/// `message`, so the virtual-column rewrite can no longer see the full source-table path
/// `v['message']['attribute']['user_id']`. This function rewrites the query shape to:
///
/// ```sql
/// WITH logs AS (
/// SELECT
/// v['message'] AS message,
/// v['message']['attribute']['user_id']
/// AS __databend_virtual_column__0
/// FROM t
/// )
/// SELECT __databend_virtual_column__0
/// FROM logs;
/// ```
///
/// The rewrite runs in three steps:
/// 1. Collect auto-materialized CTEs whose producers can safely add hidden static JSON
/// extraction outputs. This does not require source tables to have virtual columns enabled:
/// the hidden expression is still evaluated earlier inside the CTE producer, and normal
/// variant binding can push it to a Fuse virtual column when one exists.
/// 2. Visit downstream CTEs and the query body. When a consumer reads a static JSON path
/// from a materialized CTE output, record the corresponding full producer expression and
/// replace the consumer expression with a generated virtual-column output.
/// 3. Append all recorded hidden expressions to the producer CTE select list, so normal
/// variant virtual-column binding can still resolve the full base-table path later.
pub(crate) fn rewrite_materialized_cte_virtual_columns(
&mut self,
bind_context: &BindContext,
with: &mut With,
body: &mut SetExpr,
) -> HashMap<String, HashSet<String>> {
if !bind_context.allow_virtual_column || with.recursive {
return HashMap::new();
}
let mut materialized_ctes = Vec::new();
for (index, cte) in with.ctes.iter().enumerate() {
// Explicit `AS MATERIALIZED` currently creates a temporary table before the outer
// query is bound. Rewriting it here could leak hidden columns into that temp table
// schema, so only auto-materialized CTEs participate in this rewrite.
if cte.user_specified_materialized || !cte.materialized {
continue;
}
let cte_name = self.normalize_identifier(&cte.alias.name).name;
if let Some(outputs) = self.collect_materialized_cte_virtual_column_outputs(cte) {
materialized_ctes.push((index, cte_name, outputs));
}
}
if materialized_ctes.is_empty() {
return HashMap::new();
}
let mut rewriter = MaterializedCteVirtualColumnRewriter {
ctes: HashMap::new(),
table_aliases: HashMap::new(),
unqualified_cte_name: None,
requirements: HashMap::new(),
next_id: 0,
name_resolution_ctx: self.name_resolution_ctx.clone(),
};
for (consumer_index, consumer_cte) in with.ctes.iter_mut().enumerate() {
let visible_materialized_cte_count = materialized_ctes
.iter()
.position(|(index, _, _)| *index >= consumer_index)
.unwrap_or(materialized_ctes.len());
Self::rewrite_materialized_cte_consumer_with_visible_ctes(
&materialized_ctes[..visible_materialized_cte_count],
&mut rewriter,
&mut consumer_cte.query.body,
self.name_resolution_ctx.clone(),
);
}
Self::rewrite_materialized_cte_consumer_with_visible_ctes(
&materialized_ctes,
&mut rewriter,
body,
self.name_resolution_ctx.clone(),
);
if rewriter.requirements.is_empty() {
return HashMap::new();
}
let mut virtual_column_outputs = HashMap::new();
for cte in &mut with.ctes {
let cte_name = normalize_identifier(&cte.alias.name, &self.name_resolution_ctx).name;
let Some(requirements) = rewriter.requirements.remove(&cte_name) else {
continue;
};
let select = match &mut cte.query.body {
SetExpr::Select(select) => select.as_mut(),
_ => continue,
};
virtual_column_outputs.insert(
cte_name,
requirements
.values()
.map(|requirement| requirement.output_column.clone())
.collect(),
);
for requirement in requirements.into_values() {
select.select_list.push(SelectTarget::AliasedExpr {
expr: Box::new(requirement.expr),
alias: Some(Identifier::from_name(None, requirement.output_column)),
});
}
}
virtual_column_outputs
}
fn collect_materialized_cte_virtual_column_outputs(
&self,
cte: &CTE,
) -> Option<HashMap<String, Expr>> {
let select = match &cte.query.body {
SetExpr::Select(select) => select.as_ref(),
_ => return None,
};
let mut source_checker = MaterializedCteSourceChecker { has_source: false };
if select.from.walk(&mut source_checker).is_err() {
return None;
}
if !source_checker.has_source {
return None;
}
let mut outputs = HashMap::new();
for (index, item) in select.select_list.iter().enumerate() {
let SelectTarget::AliasedExpr { expr, alias } = item else {
continue;
};
if extract_static_column_map_access(expr.as_ref()).is_none() {
continue;
}
let column = if !cte.alias.columns.is_empty() {
let Some(column) = cte.alias.columns.get(index) else {
continue;
};
column
} else if let Some(alias) = alias {
alias
} else {
continue;
};
let output_name = self.normalize_identifier(column).name;
outputs.insert(output_name, expr.as_ref().clone());
}
if outputs.is_empty() {
None
} else {
Some(outputs)
}
}
fn rewrite_materialized_cte_consumer_with_visible_ctes(
visible_ctes: &[(usize, String, HashMap<String, Expr>)],
rewriter: &mut MaterializedCteVirtualColumnRewriter,
body: &mut SetExpr,
name_resolution_ctx: NameResolutionContext,
) -> bool {
let ctes = visible_ctes
.iter()
.map(|(_, name, outputs)| (name.clone(), outputs.clone()))
.collect::<HashMap<_, _>>();
if ctes.is_empty() {
return false;
}
let cte_names = ctes.keys().cloned().collect();
Self::rewrite_materialized_cte_consumer(
rewriter,
ctes,
cte_names,
body,
name_resolution_ctx,
)
}
fn rewrite_materialized_cte_consumer(
rewriter: &mut MaterializedCteVirtualColumnRewriter,
ctes: HashMap<String, HashMap<String, Expr>>,
cte_names: HashSet<String>,
body: &mut SetExpr,
name_resolution_ctx: NameResolutionContext,
) -> bool {
rewriter.ctes = ctes;
Self::rewrite_materialized_cte_set_expr(rewriter, &cte_names, body, name_resolution_ctx)
}
fn rewrite_materialized_cte_set_expr(
rewriter: &mut MaterializedCteVirtualColumnRewriter,
cte_names: &HashSet<String>,
body: &mut SetExpr,
name_resolution_ctx: NameResolutionContext,
) -> bool {
match body {
SetExpr::Select(select) => Self::rewrite_materialized_cte_select(
rewriter,
cte_names,
select.as_mut(),
name_resolution_ctx,
),
SetExpr::Query(query) => Self::rewrite_materialized_cte_set_expr(
rewriter,
cte_names,
&mut query.body,
name_resolution_ctx,
),
SetExpr::SetOperation(set_op) => {
let left = Self::rewrite_materialized_cte_set_expr(
rewriter,
cte_names,
&mut set_op.left,
name_resolution_ctx.clone(),
);
let right = Self::rewrite_materialized_cte_set_expr(
rewriter,
cte_names,
&mut set_op.right,
name_resolution_ctx,
);
left || right
}
SetExpr::Values { .. } => false,
}
}
fn rewrite_materialized_cte_select(
rewriter: &mut MaterializedCteVirtualColumnRewriter,
cte_names: &HashSet<String>,
select: &mut SelectStmt,
name_resolution_ctx: NameResolutionContext,
) -> bool {
let mut alias_collector = MaterializedCteAliasCollector {
cte_names,
aliases: HashMap::new(),
source_count: 0,
name_resolution_ctx,
};
if select.from.walk(&mut alias_collector).is_err() || alias_collector.aliases.is_empty() {
return false;
}
rewriter.unqualified_cte_name =
if alias_collector.source_count == 1 && alias_collector.aliases.len() == 1 {
alias_collector.aliases.values().next().cloned()
} else {
None
};
rewriter.table_aliases = alias_collector.aliases;
select.walk_mut(rewriter).is_ok()
}
}
/// Collects aliases that refer to visible materialized CTEs in a consumer query.
///
/// The rewriter uses this map to resolve both direct CTE references (`FROM logs`) and aliased
/// references (`FROM logs AS l`) back to the producer CTE name.
/// `source_count` tracks the current SELECT block only, so unqualified columns are rewritten only
/// when binder would see a single source and therefore cannot report a cross-source ambiguity.
struct MaterializedCteAliasCollector<'a> {
cte_names: &'a HashSet<String>,
aliases: HashMap<String, String>,
source_count: usize,
name_resolution_ctx: NameResolutionContext,
}
impl Visitor for MaterializedCteAliasCollector<'_> {
fn visit_table_reference(
&mut self,
table_ref: &TableReference,
) -> std::result::Result<VisitControl, !> {
match table_ref {
TableReference::Table { table, alias, .. } => {
self.source_count += 1;
let table_name = normalize_identifier(&table.table, &self.name_resolution_ctx).name;
if self.cte_names.contains(&table_name) {
let alias_name = alias
.as_ref()
.map(|alias| {
normalize_identifier(&alias.name, &self.name_resolution_ctx).name
})
.unwrap_or_else(|| table_name.clone());
self.aliases.insert(alias_name, table_name);
}
return Ok(VisitControl::SkipChildren);
}
TableReference::Subquery { .. }
| TableReference::TableFunction { .. }
| TableReference::Location { .. } => {
self.source_count += 1;
return Ok(VisitControl::SkipChildren);
}
_ => {}
}
Ok(VisitControl::Continue)
}
fn visit_expr(&mut self, expr: &Expr) -> std::result::Result<VisitControl, !> {
if is_nested_query_expr(expr) {
return Ok(VisitControl::SkipChildren);
}
Ok(VisitControl::Continue)
}
}
struct MaterializedCteRequirement {
output_column: String,
expr: Expr,
}
/// Checks whether a materialized CTE producer can safely add hidden JSON extraction outputs.
///
/// This checker does not require the source table to have Fuse virtual columns enabled. If virtual
/// columns exist, normal variant binding can still push the hidden expression to the scan; otherwise
/// the hidden expression is evaluated inside the materialized CTE producer, reducing the size of
/// data passed to later consumers.
struct MaterializedCteSourceChecker {
has_source: bool,
}
impl Visitor for MaterializedCteSourceChecker {
fn visit_table_reference(
&mut self,
table_ref: &TableReference,
) -> std::result::Result<VisitControl, !> {
match table_ref {
TableReference::Table { .. } => {
self.has_source = true;
}
TableReference::TableFunction { .. } | TableReference::Location { .. } => {
self.has_source = false;
return Ok(VisitControl::Break(()));
}
_ => {}
}
Ok(VisitControl::Continue)
}
}
/// Rewrites static JSON path accesses on materialized CTE outputs into hidden CTE columns.
///
/// When a consumer reads `message['a']` from a materialized CTE output, this visitor records the
/// full producer expression, assigns it a virtual-column output, and replaces the consumer
/// expression with that output column. The caller later appends all recorded expressions to the
/// producer CTE select list.
struct MaterializedCteVirtualColumnRewriter {
ctes: HashMap<String, HashMap<String, Expr>>,
table_aliases: HashMap<String, String>,
unqualified_cte_name: Option<String>,
requirements: HashMap<String, BTreeMap<String, MaterializedCteRequirement>>,
next_id: usize,
name_resolution_ctx: NameResolutionContext,
}
impl VisitorMut for MaterializedCteVirtualColumnRewriter {
fn visit_expr(&mut self, expr: &mut Expr) -> std::result::Result<VisitControl, !> {
if is_nested_query_expr(expr) {
return Ok(VisitControl::SkipChildren);
}
let Some((column, accessors)) = extract_static_column_map_access(expr) else {
return Ok(VisitControl::Continue);
};
let column_name = normalize_column_id(&column.column, &self.name_resolution_ctx);
let Some(cte_name) = self.resolve_cte_name(&column, &column_name) else {
return Ok(VisitControl::Continue);
};
let Some(producer_outputs) = self.ctes.get(&cte_name) else {
return Ok(VisitControl::Continue);
};
let Some(producer_expr) = producer_outputs.get(&column_name) else {
return Ok(VisitControl::Continue);
};
// Rewrite a consumer JSON path back to the full producer JSON path and use
// `requirement_key` to deduplicate generated columns.
// For example, if the producer outputs `v['message'] AS message`,
// consumer `message['a']` becomes `v['message']['a']`.
let requirement_expr = Self::append_map_accessors(producer_expr.clone(), &accessors);
let requirement_key = requirement_expr.to_string();
if !self
.requirements
.get(&cte_name)
.is_some_and(|requirements| requirements.contains_key(&requirement_key))
{
let output_column = self.next_virtual_column_output(&cte_name);
self.requirements
.entry(cte_name.clone())
.or_default()
.insert(requirement_key.clone(), MaterializedCteRequirement {
output_column,
expr: requirement_expr,
});
}
let Some(output_column) = self
.requirements
.get(&cte_name)
.and_then(|requirements| requirements.get(&requirement_key))
.map(|requirement| requirement.output_column.clone())
else {
return Ok(VisitControl::Continue);
};
*expr = Expr::ColumnRef {
span: expr.span(),
column: ColumnRef {
database: None,
table: column.table.clone(),
column: ColumnID::Name(Identifier::from_name(None, output_column)),
},
};
Ok(VisitControl::SkipChildren)
}
fn visit_table_reference(
&mut self,
table_ref: &mut TableReference,
) -> std::result::Result<VisitControl, !> {
if matches!(table_ref, TableReference::Subquery { .. }) {
return Ok(VisitControl::SkipChildren);
}
Ok(VisitControl::Continue)
}
}
impl MaterializedCteVirtualColumnRewriter {
fn next_virtual_column_output(&mut self, cte_name: &str) -> String {
loop {
let output_column = format!("{MATERIALIZED_CTE_VIRTUAL_COLUMN_PREFIX}{}", self.next_id);
self.next_id += 1;
// The generated output name must not collide with user-defined CTE outputs.
if self
.ctes
.get(cte_name)
.is_none_or(|outputs| !outputs.contains_key(&output_column))
{
return output_column;
}
}
}
fn append_map_accessors(mut expr: Expr, accessors: &[MapAccessor]) -> Expr {
for accessor in accessors {
expr = Expr::MapAccess {
span: None,
expr: Box::new(expr),
accessor: accessor.clone(),
};
}
expr
}
fn resolve_cte_name(&self, column: &ColumnRef, column_name: &str) -> Option<String> {
if let Some(table) = &column.table {
let table_name = normalize_identifier(table, &self.name_resolution_ctx).name;
return self.table_aliases.get(&table_name).cloned();
}
let cte_name = self.unqualified_cte_name.as_ref()?;
let outputs = self.ctes.get(cte_name)?;
outputs.contains_key(column_name).then(|| cte_name.clone())
}
}
fn normalize_column_id(
column_id: &ColumnID,
name_resolution_ctx: &NameResolutionContext,
) -> String {
match column_id {
ColumnID::Name(ident) => normalize_identifier(ident, name_resolution_ctx).name,
ColumnID::Position(pos) => pos.name(),
}
}
fn is_nested_query_expr(expr: &Expr) -> bool {
matches!(
expr,
Expr::Exists { .. }
| Expr::Subquery { .. }
| Expr::InSubquery { .. }
| Expr::LikeSubquery { .. }
)
}
fn extract_static_column_map_access(expr: &Expr) -> Option<(ColumnRef, Vec<MapAccessor>)> {
if !matches!(expr, Expr::MapAccess { .. }) {
return None;
}
let mut accessors = Vec::new();
let mut current = expr;
while let Expr::MapAccess { expr, accessor, .. } = current {
match accessor {
MapAccessor::Bracket { key } => {
if !matches!(key.as_ref(), Expr::Literal {
value: Literal::String(_) | Literal::UInt64(_),
..
}) {
return None;
}
}
MapAccessor::DotNumber { .. } | MapAccessor::Colon { .. } => {}
}
accessors.push(accessor.clone());
current = expr;
}
accessors.reverse();
if let Expr::ColumnRef { column, .. } = current {
Some((column.clone(), accessors))
} else {
None
}
}