Skip to content

Commit a2ee71a

Browse files
committed
refactor: keep SQL macro probe helpers to plain loops
1 parent e61666a commit a2ee71a

2 files changed

Lines changed: 87 additions & 70 deletions

File tree

‎crates/sqlbuild-analysis/src/query_analysis/main/output_types.rs‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,27 @@ pub fn output_types(
1111
dialect: &str,
1212
schema: &ValidationSchema,
1313
) -> Option<Vec<(String, Option<String>)>> {
14-
let dialect: DialectType = dialect.parse().ok()?;
14+
let dialect: DialectType = match dialect.parse() {
15+
Ok(dialect) => dialect,
16+
Err(_) => return None,
17+
};
1518
let mut statements: Vec<Expression> =
16-
polyglot_sql::parse_with_options(sql, dialect, &ParseOptions::default()).ok()?;
19+
match polyglot_sql::parse_with_options(sql, dialect, &ParseOptions::default()) {
20+
Ok(statements) => statements,
21+
Err(_) => return None,
22+
};
1723
if statements.len() != 1 {
1824
return None;
1925
}
2026
let expression: Expression = statements.pop()?;
21-
let outputs = infer_outputs(&expression, Some(schema), &HashMap::new(), dialect);
22-
Some(
23-
outputs
24-
.into_iter()
25-
.map(|(name, data_type)| (name, data_type.filter(|value| value != NULL_TYPE)))
26-
.collect(),
27-
)
27+
let mut outputs: Vec<(String, Option<String>)> = Vec::new();
28+
for (name, data_type) in infer_outputs(&expression, Some(schema), &HashMap::new(), dialect) {
29+
outputs.push((name, data_type.filter(|value| !is_null_type(value))));
30+
}
31+
Some(outputs)
32+
}
33+
34+
/// Whether `value` is the placeholder inference uses for a `NULL` literal's type.
35+
fn is_null_type(value: &str) -> bool {
36+
value == NULL_TYPE
2837
}

‎crates/sqlbuild-analysis/src/sql_macros/_helpers/probes.rs‎

Lines changed: 69 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -137,25 +137,31 @@ fn defines_alias(tail: &str, name: &str) -> bool {
137137
let Ok(scanned) = tokens(tail) else {
138138
return true;
139139
};
140-
scanned.iter().enumerate().any(|(index, token)| {
140+
for (index, token) in scanned.iter().enumerate() {
141141
let named: bool = matches!(token.kind, TokenKind::Word | TokenKind::Quoted)
142142
&& unquoted(token.text(tail)).eq_ignore_ascii_case(name);
143143
let qualifies: bool = scanned
144144
.get(index + 1)
145145
.is_some_and(|next| next.is(tail, "."));
146-
let after_relation: bool = index
147-
.checked_sub(1)
148-
.and_then(|previous| scanned.get(previous))
149-
.is_some_and(|previous| {
150-
previous.is_word(tail, "AS")
151-
|| previous.is(tail, ")")
152-
|| matches!(previous.kind, TokenKind::Word | TokenKind::Quoted)
153-
&& !ALIAS_PRECEDING_KEYWORDS
154-
.iter()
155-
.any(|keyword| previous.is_word(tail, keyword))
156-
});
157-
named && !qualifies && after_relation
158-
})
146+
let previous: Option<&Token> = index.checked_sub(1).and_then(|before| scanned.get(before));
147+
if named && !qualifies && previous.is_some_and(|before| ends_relation(tail, before)) {
148+
return true;
149+
}
150+
}
151+
false
152+
}
153+
154+
/// Whether `token` can end the relation an alias follows: `AS`, `)` or a relation name.
155+
fn ends_relation(tail: &str, token: &Token) -> bool {
156+
if token.is_word(tail, "AS") || token.is(tail, ")") {
157+
return true;
158+
}
159+
if !matches!(token.kind, TokenKind::Word | TokenKind::Quoted) {
160+
return false;
161+
}
162+
!ALIAS_PRECEDING_KEYWORDS
163+
.iter()
164+
.any(|keyword| token.is_word(tail, keyword))
159165
}
160166

161167
/// The probes reading every check's evidence from the analysed query `sql`.
@@ -188,7 +194,18 @@ pub(crate) fn probe_plan(sql: &str, checks: &[SqlMacroCheck]) -> ProbePlan {
188194
}
189195
}
190196
ArgumentExpectation::Typed { .. } => {
191-
let probe: &mut TypedProbe<'_> = typed_probe(&mut scopes, &check.scope);
197+
let group: usize = match typed_probe_index(&scopes, &check.scope) {
198+
Some(group) => group,
199+
None => {
200+
scopes.push(TypedProbe {
201+
scope: &check.scope,
202+
columns: Vec::new(),
203+
arguments: Vec::new(),
204+
});
205+
scopes.len() - 1
206+
}
207+
};
208+
let probe: &mut TypedProbe<'_> = &mut scopes[group];
192209
probe.columns.push(format!(
193210
"({}) AS {PROBE_COLUMN_PREFIX}{}",
194211
argument.text,
@@ -220,21 +237,9 @@ pub(crate) fn probe_plan(sql: &str, checks: &[SqlMacroCheck]) -> ProbePlan {
220237
plan
221238
}
222239

223-
/// The typed probe of `scope` among `scopes`, added empty when it is the first.
224-
fn typed_probe<'s, 'c>(
225-
scopes: &'s mut Vec<TypedProbe<'c>>,
226-
scope: &'c CallScope,
227-
) -> &'s mut TypedProbe<'c> {
228-
let found: Option<usize> = scopes.iter().position(|probe| probe.scope == scope);
229-
let index: usize = found.unwrap_or_else(|| {
230-
scopes.push(TypedProbe {
231-
scope,
232-
columns: Vec::new(),
233-
arguments: Vec::new(),
234-
});
235-
scopes.len() - 1
236-
});
237-
&mut scopes[index]
240+
/// The index of `scope`'s typed probe in `scopes`, if one was started.
241+
fn typed_probe_index(scopes: &[TypedProbe<'_>], scope: &CallScope) -> Option<usize> {
242+
scopes.iter().position(|probe| probe.scope == scope)
238243
}
239244

240245
/// The column type of `name` in `columns`, matching names without case or quotes.
@@ -381,27 +386,30 @@ pub(crate) fn analysed_probes(
381386
dialect: &str,
382387
models: &[(&[String], &RelationShapes)],
383388
) -> Vec<Vec<ProbeColumns>> {
384-
models
385-
.iter()
386-
.map(|(probes, schema)| {
387-
if probes.is_empty() {
388-
return Vec::new();
389-
}
390-
let tables: Vec<Value> = schema
391-
.iter()
392-
.map(|(name, columns)| table(name, columns))
393-
.collect();
394-
let Ok(schema) =
395-
serde_json::from_value::<ValidationSchema>(json!({ "tables": tables }))
396-
else {
397-
return vec![None; probes.len()];
398-
};
399-
probes
400-
.iter()
401-
.map(|sql| output_types(sql, dialect, &schema).and_then(probe_columns))
402-
.collect()
403-
})
404-
.collect()
389+
let mut analysed: Vec<Vec<ProbeColumns>> = Vec::with_capacity(models.len());
390+
for (probes, schema) in models {
391+
analysed.push(model_probes(dialect, probes, schema));
392+
}
393+
analysed
394+
}
395+
396+
/// One model's probes' output columns, inferred against its bound relations.
397+
fn model_probes(dialect: &str, probes: &[String], schema: &RelationShapes) -> Vec<ProbeColumns> {
398+
if probes.is_empty() {
399+
return Vec::new();
400+
}
401+
let mut tables: Vec<Value> = Vec::with_capacity(schema.len());
402+
for (name, columns) in schema {
403+
tables.push(table(name, columns));
404+
}
405+
let Ok(schema) = serde_json::from_value::<ValidationSchema>(json!({ "tables": tables })) else {
406+
return vec![None; probes.len()];
407+
};
408+
let mut columns: Vec<ProbeColumns> = Vec::with_capacity(probes.len());
409+
for sql in probes {
410+
columns.push(output_types(sql, dialect, &schema).and_then(probe_columns));
411+
}
412+
columns
405413
}
406414

407415
/// One bound relation as a validation schema table, its qualified name split into parts.
@@ -427,14 +435,14 @@ fn probe_columns(outputs: Vec<(String, Option<String>)>) -> ProbeColumns {
427435
if outputs.is_empty() || outputs.iter().any(|(name, _)| name == STAR_PROJECTION) {
428436
return None;
429437
}
430-
Some(
431-
outputs
432-
.into_iter()
433-
.map(|(name, data_type)| {
434-
let known: Option<String> =
435-
data_type.filter(|hint| !hint.eq_ignore_ascii_case(UNKNOWN_TYPE_HINT));
436-
(name, known)
437-
})
438-
.collect(),
439-
)
438+
let mut columns: Vec<(String, Option<String>)> = Vec::with_capacity(outputs.len());
439+
for (name, data_type) in outputs {
440+
columns.push((name, data_type.filter(|hint| known_type(hint))));
441+
}
442+
Some(columns)
443+
}
444+
445+
/// Whether inference reported a type rather than its unknown placeholder.
446+
fn known_type(hint: &str) -> bool {
447+
!hint.eq_ignore_ascii_case(UNKNOWN_TYPE_HINT)
440448
}

0 commit comments

Comments
 (0)