Skip to content

Commit a9e63bb

Browse files
committed
feat(native): recover CTE facts natively behind the preview engine
1 parent 762eac9 commit a9e63bb

19 files changed

Lines changed: 1947 additions & 45 deletions

File tree

‎crates/sqlbuild-analysis/src/assembly/analysis_session/_helpers/cte_facts.rs‎

Lines changed: 1297 additions & 0 deletions
Large diffs are not rendered by default.

‎crates/sqlbuild-analysis/src/assembly/analysis_session/_helpers/dict_walk.rs‎

Lines changed: 242 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1-
//! Python's dict walk over a parsed query's `to_dict()` payload, on the same serde values.
1+
//! Python's view of a parsed query: the wheel's expression accessors and its dict walk.
22
3-
use serde_json::{Map, Value};
3+
use polyglot_sql::expressions::Cte;
4+
use polyglot_sql::traversal::ExpressionWalk;
5+
use polyglot_sql::{ComplexityGuardOptions, Dialect, Expression, ParseOptions, ast_json};
6+
use serde_json::{Map, Value, json};
47

58
use crate::assembly::analysis_session::constants::{
6-
COLUMN_AST_KIND, DEPENDENCY_FUNCTION_NAMES, FUNCTION_AST_KIND, RENDERED_TYPE_NAMES,
7-
STAR_AST_KIND, TABLE_AST_KIND,
9+
ALIAS_AST_KIND, ANNOTATED_AST_KIND, COLUMN_AST_KIND, DEPENDENCY_FUNCTION_NAMES,
10+
FUNCTION_AST_KIND, MAX_FUNCTION_CALL_DEPTH, RENDERED_TYPE_NAMES, STAR_AST_KIND, TABLE_AST_KIND,
11+
WILDCARD,
812
};
913

1014
/// Python's `bool(value)`.
@@ -142,7 +146,7 @@ pub(crate) fn render_type(node: Option<&Value>) -> Option<String> {
142146
}
143147

144148
/// Python's `str(value)` for a value `isinstance(value, int)` accepts.
145-
fn python_int(value: Option<&Value>) -> Option<String> {
149+
pub(crate) fn python_int(value: Option<&Value>) -> Option<String> {
146150
match value? {
147151
Value::Bool(flag) => Some(if *flag { "True" } else { "False" }.to_owned()),
148152
Value::Number(number) if number.is_i64() || number.is_u64() => Some(number.to_string()),
@@ -154,3 +158,236 @@ fn python_int(value: Option<&Value>) -> Option<String> {
154158
pub(crate) fn casefold(text: &str) -> String {
155159
text.to_ascii_lowercase()
156160
}
161+
162+
/// A value the wheel hands Python for one payload key: an expression, a list of them, or data.
163+
#[derive(Debug, Clone)]
164+
pub(crate) enum PyValue {
165+
Expr(Expression),
166+
Exprs(Vec<Expression>),
167+
Raw(Value),
168+
}
169+
170+
/// The wheel's guarded `parse_one`; Ok(None) is the `PolyglotError` Python catches.
171+
pub(crate) fn parse_one(sql: &str, dialect: &str) -> Result<Option<Expression>, String> {
172+
let guard: ComplexityGuardOptions =
173+
serde_json::from_value(json!({"maxFunctionCallDepth": MAX_FUNCTION_CALL_DEPTH}))
174+
.map_err(|error| error.to_string())?;
175+
let options: ParseOptions = ParseOptions {
176+
complexity_guard: Some(guard),
177+
};
178+
let parsed: Result<Vec<Expression>, _> = Dialect::get_by_name(dialect)
179+
.ok_or_else(|| format!("unknown dialect {dialect}"))?
180+
.parse_with_options(sql, &options);
181+
let mut expressions: Vec<Expression> = match parsed {
182+
Ok(expressions) => expressions,
183+
Err(_) => return Ok(None),
184+
};
185+
if expressions.len() != 1 {
186+
return Ok(None);
187+
}
188+
Ok(expressions.pop())
189+
}
190+
191+
/// `str(getattr(node, "kind", ""))`.
192+
pub(crate) fn kind(node: Option<&Expression>) -> &'static str {
193+
node.map_or("", Expression::variant_name)
194+
}
195+
196+
/// `node.name`, "" for None.
197+
pub(crate) fn name(node: Option<&Expression>) -> &str {
198+
node.map_or("", Expression::get_name)
199+
}
200+
201+
/// `node.output_name`, "" for None.
202+
pub(crate) fn output_name(node: Option<&Expression>) -> &str {
203+
node.map_or("", Expression::get_output_name)
204+
}
205+
206+
/// `node.alias_or_name`.
207+
pub(crate) fn alias_or_name(node: &Expression) -> &str {
208+
let alias: &str = node.get_alias();
209+
if alias.is_empty() {
210+
node.get_name()
211+
} else {
212+
alias
213+
}
214+
}
215+
216+
/// `node.is_star`.
217+
pub(crate) fn is_star(node: Option<&Expression>) -> bool {
218+
match node {
219+
Some(Expression::Star(_)) => true,
220+
Some(Expression::Column(column)) => column.name.name == WILDCARD,
221+
_ => false,
222+
}
223+
}
224+
225+
/// Python's `_unwrap_polyglot_annotations`.
226+
pub(crate) fn unwrap_annotations(mut node: Option<&Expression>) -> Option<&Expression> {
227+
while kind(node) == ANNOTATED_AST_KIND {
228+
node = node.and_then(Expression::get_this);
229+
}
230+
node
231+
}
232+
233+
/// A projection's expression: an alias's `this`, otherwise the projection.
234+
pub(crate) fn projected_expression(projection: Option<&Expression>) -> Option<&Expression> {
235+
if kind(projection) == ALIAS_AST_KIND {
236+
return projection.and_then(Expression::get_this);
237+
}
238+
projection
239+
}
240+
241+
/// `node.this` then `node.expressions`: Python's `_polyglot_expression_args`.
242+
pub(crate) fn expression_args(node: Option<&Expression>) -> Vec<&Expression> {
243+
let Some(node) = node else {
244+
return Vec::new();
245+
};
246+
node.get_this()
247+
.into_iter()
248+
.chain(node.get_expressions())
249+
.collect()
250+
}
251+
252+
/// `node.children()`.
253+
pub(crate) fn children(node: &Expression) -> Vec<&Expression> {
254+
ExpressionWalk::children(node)
255+
}
256+
257+
/// Python's `_polyglot_direct_select_tables`: the table children.
258+
pub(crate) fn direct_tables(node: &Expression) -> Vec<&Expression> {
259+
children(node)
260+
.into_iter()
261+
.filter(|child| child.variant_name() == TABLE_AST_KIND)
262+
.collect()
263+
}
264+
265+
/// `node.find_all(kind)`: descendants in depth-first order, the node itself excluded.
266+
pub(crate) fn find_all<'a>(node: &'a Expression, wanted: &str) -> Vec<&'a Expression> {
267+
node.dfs()
268+
.skip(1)
269+
.filter(|descendant| descendant.variant_name() == wanted)
270+
.collect()
271+
}
272+
273+
/// `node.to_dict()`.
274+
pub(crate) fn to_dict(node: &Expression) -> Result<Value, String> {
275+
serde_json::to_value(node).map_err(|error| error.to_string())
276+
}
277+
278+
/// The wheel's `expression_payload`: the tagged value's fields.
279+
pub(crate) fn expression_payload(node: &Expression) -> Result<Map<String, Value>, String> {
280+
Ok(match to_dict(node)? {
281+
Value::Object(map) => match map.into_iter().next() {
282+
Some((_, Value::Object(payload))) => payload,
283+
_ => Map::new(),
284+
},
285+
_ => Map::new(),
286+
})
287+
}
288+
289+
/// `node.args.get(key)` (and `node.arg(key)` outside its special keys); None for Python's None.
290+
pub(crate) fn arg(node: Option<&Expression>, key: &str) -> Result<Option<PyValue>, String> {
291+
let Some(node) = node else {
292+
return Ok(None);
293+
};
294+
Ok(expression_payload(node)?.remove(key).and_then(py_value))
295+
}
296+
297+
/// The wheel's `value_to_python_object`; None where Python sees None.
298+
fn py_value(value: Value) -> Option<PyValue> {
299+
if let Ok(expression) = ast_json::expression_from_value(value.clone()) {
300+
return Some(PyValue::Expr(expression));
301+
}
302+
if let Ok(expressions) = ast_json::expressions_from_value(value.clone()) {
303+
return Some(PyValue::Exprs(expressions));
304+
}
305+
(!value.is_null()).then_some(PyValue::Raw(value))
306+
}
307+
308+
/// Python's `bool()` of a converted value: expressions are always truthy.
309+
pub(crate) fn py_truthy(value: Option<&PyValue>) -> bool {
310+
match value {
311+
None => false,
312+
Some(PyValue::Expr(_)) => true,
313+
Some(PyValue::Exprs(items)) => !items.is_empty(),
314+
Some(PyValue::Raw(raw)) => truthy(Some(raw)),
315+
}
316+
}
317+
318+
/// Python's `_polyglot_name_payload_value` of a converted value.
319+
pub(crate) fn name_payload(value: Option<&PyValue>) -> String {
320+
match value {
321+
Some(PyValue::Raw(raw)) => raw_name_payload(Some(raw)),
322+
_ => String::new(),
323+
}
324+
}
325+
326+
/// Python's `_polyglot_name_payload_value` of plain data.
327+
pub(crate) fn raw_name_payload(value: Option<&Value>) -> String {
328+
match value {
329+
Some(Value::String(text)) => text.clone(),
330+
Some(Value::Object(object)) => object
331+
.get("name")
332+
.and_then(Value::as_str)
333+
.unwrap_or_default()
334+
.to_owned(),
335+
_ => String::new(),
336+
}
337+
}
338+
339+
/// Python's `_polyglot_column_table_name`: `to_dict()["column"]["table"]["name"]`.
340+
pub(crate) fn column_table_name(node: &Expression) -> Result<String, String> {
341+
let value: Value = to_dict(node)?;
342+
let table: Option<&Value> = value
343+
.get("column")
344+
.filter(|column| column.is_object())
345+
.and_then(|column| column.get("table"))
346+
.filter(|table| table.is_object());
347+
Ok(raw_name_payload(table))
348+
}
349+
350+
/// The top-level CTEs `with_ctes()` returns: name, whether it has column aliases, and its body.
351+
pub(crate) fn top_level_ctes(node: &Expression) -> Vec<(&str, bool, &Expression)> {
352+
let with = match node {
353+
Expression::Select(select) => select.with.as_ref(),
354+
Expression::Union(union) => union.with.as_ref(),
355+
Expression::Intersect(intersect) => intersect.with.as_ref(),
356+
Expression::Except(except) => except.with.as_ref(),
357+
_ => None,
358+
};
359+
with.map(|with| with.ctes.iter().map(cte_entry).collect())
360+
.unwrap_or_default()
361+
}
362+
363+
fn cte_entry(cte: &Cte) -> (&str, bool, &Expression) {
364+
(cte.alias.name.as_str(), !cte.columns.is_empty(), &cte.this)
365+
}
366+
367+
/// A set operation's `arg("left")`, `arg("right")` and `arg("by_name")`.
368+
pub(crate) fn set_operation(node: &Expression) -> Option<(&Expression, &Expression, bool)> {
369+
match node {
370+
Expression::Union(operation) => {
371+
Some((&operation.left, &operation.right, operation.by_name))
372+
}
373+
Expression::Intersect(operation) => {
374+
Some((&operation.left, &operation.right, operation.by_name))
375+
}
376+
Expression::Except(operation) => {
377+
Some((&operation.left, &operation.right, operation.by_name))
378+
}
379+
_ => None,
380+
}
381+
}
382+
383+
/// A select's `arg("where_clause")` as plain data.
384+
pub(crate) fn where_clause(node: &Expression) -> Result<Option<Value>, String> {
385+
let Expression::Select(select) = node else {
386+
return Ok(None);
387+
};
388+
select
389+
.where_clause
390+
.as_ref()
391+
.map(|clause| serde_json::to_value(clause).map_err(|error| error.to_string()))
392+
.transpose()
393+
}

‎crates/sqlbuild-analysis/src/assembly/analysis_session/_helpers/dynamic_pivot.rs‎

Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@
22
33
use std::collections::{HashMap, HashSet};
44

5-
use polyglot_sql::{ComplexityGuardOptions, Dialect, Expression, ParseOptions};
6-
use serde_json::{Map, Value, json};
5+
use serde_json::{Map, Value};
76
use sqlbuild_core::panics::main::catch_compiler_panic::catch_compiler_panic;
87

98
use crate::assembly::analysis_session::_helpers::dict_walk::{
109
casefold, column_name, dict_list, identifier_name, is_single_wildcard, nested, node_key,
11-
payload, relation_name, render_type, truthy,
10+
parse_one, payload, relation_name, render_type, to_dict, truthy,
1211
};
1312
use crate::assembly::analysis_session::constants::{
1413
ALIAS_AST_KIND, CAST_AST_KIND, CTE_AST_KIND, DUCKDB_DIALECT, DYNAMIC_VALUE_SOURCE_KINDS,
15-
MAX_FUNCTION_CALL_DEPTH, MOTHERDUCK_DIALECT, PIVOT_AST_KIND, QUERY_AST_KINDS, SELECT_AST_KIND,
14+
MOTHERDUCK_DIALECT, PIVOT_AST_KIND, QUERY_AST_KINDS, SELECT_AST_KIND,
1615
SIMPLIFIED_PIVOT_DIALECTS, SUPPORTED_PIVOT_DIALECTS, TYPE_PRESERVING_AGGREGATES,
1716
UNKNOWN_NULLABILITY, UNKNOWN_TYPE,
1817
};
@@ -80,25 +79,9 @@ pub(crate) fn pivot_outcome(
8079

8180
/// Python's `parse_one(...).to_dict()`, or None where Python reports a parse error.
8281
fn parsed(sql: &str, dialect: &str) -> Result<Option<Value>, String> {
83-
let guard: ComplexityGuardOptions =
84-
serde_json::from_value(json!({"maxFunctionCallDepth": MAX_FUNCTION_CALL_DEPTH}))
85-
.map_err(|error| error.to_string())?;
86-
let options: ParseOptions = ParseOptions {
87-
complexity_guard: Some(guard),
88-
};
89-
let parsed: Result<Vec<Expression>, _> = Dialect::get_by_name(dialect)
90-
.ok_or_else(|| format!("unknown dialect {dialect}"))?
91-
.parse_with_options(sql, &options);
92-
let expressions: Vec<Expression> = match parsed {
93-
Ok(expressions) => expressions,
94-
Err(_) => return Ok(None),
95-
};
96-
let [expression] = expressions.as_slice() else {
97-
return Ok(None);
98-
};
99-
serde_json::to_value(expression)
100-
.map(Some)
101-
.map_err(|error| error.to_string())
82+
parse_one(sql, dialect)?
83+
.map(|expression| to_dict(&expression))
84+
.transpose()
10285
}
10386

10487
/// Casefolding equals Python's only for ASCII text.

0 commit comments

Comments
 (0)