Skip to content

Commit 0a86a2d

Browse files
committed
fix(lineage): give a merged column its strongest branch's transform kind
A column merged from alternative branches (a set operation, a VALUES column, an UNPIVOT value) now takes the most significant kind among the branches that read a column or aggregate, when every branch's type is known, instead of becoming an expression whenever it reads more than one column. A constant branch is no step, so branches that each pass a column through are direct, with all their sources. A computed branch still outranks a cast. When a branch's type is unknown, the merge stays an expression unless it passes one column through, as before. A branch that reads a column counts as a cast when the dialect converts its value on the merge, and so does EXCEPT's left column when the right side converts it. Type spellings that name one type, such as INT4 and INTEGER on DuckDB, are no conversion, and neither is dropping a type's modifiers. On SQLite, integers merged into a REAL column are a cast, as a compound read through a subquery gives every branch its leftmost column's affinity. No existing lineage test expectation changes.
1 parent e7cf60f commit 0a86a2d

13 files changed

Lines changed: 490 additions & 38 deletions

File tree

‎crates/sqlquack-semantics/src/duckdb/profile/models.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,14 @@ impl DialectRules for DuckDbRules {
229229
combined.map(|combined| Rc::from(combined.spelling()))
230230
}
231231

232+
/// A conversion unless both spellings name the same DuckDB type, such as INT4 and INTEGER.
233+
fn merge_converts(&self, from: &str, to: &str, profile: &dyn DialectProfile) -> bool {
234+
match (parsed_type(from), parsed_type(to)) {
235+
(Some(from), Some(to)) => from != to,
236+
_ => !profile.same_type(from, to),
237+
}
238+
}
239+
232240
fn cast_spelling(&self, data_type: &DataType) -> Option<String> {
233241
cast_spelling(data_type)
234242
}

‎crates/sqlquack-semantics/src/duckdb/profile/tests/test_query_lineage.rs‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ use crate::duckdb::profile::tests::test_types::{
33
};
44

55
use crate::lineage::main::statement_lineage::statement_lineage;
6-
use crate::lineage::tests::helpers::typed_duckdb_shop_schema;
6+
use std::collections::HashMap;
7+
8+
use crate::lineage::tests::helpers::{typed_column, typed_duckdb_shop_schema};
79
use crate::lineage::tests::test_types::TypedShopSchema;
810

911
use sqlquack_parse::parse_statements_with;
@@ -361,3 +363,77 @@ fn given_select_aliases_read_at_several_levels_when_analysing_together_then_line
361363
);
362364
}
363365
}
366+
367+
#[test]
368+
fn given_union_branches_of_one_type_spelled_two_ways_when_tracing_duckdb_lineage_then_no_cast_is_reported()
369+
{
370+
let test_cases = [QueryLineageTestCase {
371+
description: "INT4 and INTEGER spell one DuckDB type, so the union converts nothing",
372+
sql: "SELECT id FROM orders UNION ALL SELECT customer_id FROM orders",
373+
dialect: Dialect::DuckDB,
374+
profile: &DUCKDB,
375+
expected_outputs: &[(
376+
"id",
377+
TransformKind::Direct,
378+
&["orders.customer_id", "orders.id"],
379+
)],
380+
expected_open_star: false,
381+
}];
382+
let schema = TypedShopSchema {
383+
closed: HashMap::from([(
384+
"orders".to_owned(),
385+
vec![
386+
typed_column("id", "INT4"),
387+
typed_column("customer_id", "INTEGER"),
388+
],
389+
)]),
390+
..TypedShopSchema::default()
391+
};
392+
for test_case in test_cases {
393+
let context = LineageContext {
394+
profile: test_case.profile,
395+
schema: &schema,
396+
sql: None,
397+
};
398+
let traced: Vec<(String, TransformKind, Vec<String>)> = query_lineage(
399+
test_case.sql,
400+
test_case.dialect,
401+
&ParseOptions::default(),
402+
context,
403+
)
404+
.unwrap_or_else(|error| panic!("{}: {error}", test_case.description))
405+
.outputs
406+
.iter()
407+
.map(|output| {
408+
let sources = output.sources.iter();
409+
(
410+
output.name.clone(),
411+
output.kind,
412+
sources
413+
.map(|source| format!("{}.{}", source.relation, source.column))
414+
.collect(),
415+
)
416+
})
417+
.collect();
418+
let traced: Vec<(&str, TransformKind, Vec<&str>)> = traced
419+
.iter()
420+
.map(|(name, kind, sources)| {
421+
(
422+
name.as_str(),
423+
*kind,
424+
sources.iter().map(String::as_str).collect(),
425+
)
426+
})
427+
.collect();
428+
assert_eq!(
429+
traced,
430+
test_case
431+
.expected_outputs
432+
.iter()
433+
.map(|(name, kind, sources)| (*name, *kind, sources.to_vec()))
434+
.collect::<Vec<_>>(),
435+
"{}",
436+
test_case.description
437+
);
438+
}
439+
}

‎crates/sqlquack-semantics/src/lineage/_helpers/tracing/lineages.rs‎

Lines changed: 65 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -54,16 +54,21 @@ pub(crate) fn traced_if(lineage: Lineage, traced: bool) -> Lineage {
5454
}
5555
}
5656

57+
/// The most significant kind among parts that read a column or aggregate; none when none does.
58+
fn strongest_step(parts: &[Lineage]) -> Option<TransformKind> {
59+
parts
60+
.iter()
61+
.filter(|part| !part.sources.is_empty() || part.kind == TransformKind::Aggregation)
62+
.map(|part| part.kind)
63+
.max()
64+
}
65+
5766
/// The parts read together into one value derived at least as `floor`.
5867
pub(crate) fn combined(parts: Vec<Lineage>, floor: TransformKind) -> Lineage {
5968
let resolved = parts.iter().all(|part| part.resolved);
6069
let lost: bool = parts.iter().any(|part| part.lost);
6170
let rows_lost: bool = parts.iter().any(|part| part.rows_lost);
62-
let strongest = parts
63-
.iter()
64-
.filter(|part| !part.sources.is_empty() || part.kind == TransformKind::Aggregation)
65-
.map(|part| part.kind)
66-
.max();
71+
let strongest: Option<TransformKind> = strongest_step(&parts);
6772
let (sources, rows) = unions(parts);
6873
let kind = match (strongest, floor) {
6974
(_, TransformKind::Aggregation) => TransformKind::Aggregation,
@@ -104,6 +109,49 @@ fn untyped_null(part: &Lineage) -> bool {
104109
&& part.sources.is_empty()
105110
}
106111

112+
/// Whether a branch that reads a column has a known type other than the merged one.
113+
fn implicitly_cast(branch: &Lineage, merged: &str, profile: &dyn DialectProfile) -> bool {
114+
match branch.data_type.as_deref() {
115+
Some(own) => {
116+
!branch.sources.is_empty()
117+
&& dialect_rules(profile).merge_converts(own, merged, profile)
118+
}
119+
None => false,
120+
}
121+
}
122+
123+
/// `lineage` at least a cast when a branch it merges, reading a column, is implicitly coerced.
124+
pub(crate) fn coerced(
125+
mut lineage: Lineage,
126+
branches: &[Lineage],
127+
profile: &dyn DialectProfile,
128+
) -> Lineage {
129+
let cast: bool = match lineage.data_type.as_deref() {
130+
Some(merged) => branches
131+
.iter()
132+
.any(|branch| implicitly_cast(branch, merged, profile)),
133+
None => {
134+
let read: Vec<&str> = branches
135+
.iter()
136+
.filter(|branch| !branch.sources.is_empty())
137+
.filter_map(|branch| branch.data_type.as_deref())
138+
.collect();
139+
read.iter()
140+
.any(|own| converts_into_any(own, &read, profile))
141+
}
142+
};
143+
if cast {
144+
lineage.kind = lineage.kind.max(TransformKind::Cast);
145+
}
146+
lineage
147+
}
148+
149+
/// Whether the dialect converts a value typed `own` when merging it with any of `read`.
150+
fn converts_into_any(own: &str, read: &[&str], profile: &dyn DialectProfile) -> bool {
151+
read.iter()
152+
.any(|other| dialect_rules(profile).merge_converts(own, other, profile))
153+
}
154+
107155
/// A set operation's branches merged, typed as the dialect types set operations.
108156
pub(crate) fn set_merged(parts: Vec<Lineage>, profile: &dyn DialectProfile) -> Lineage {
109157
let branches: Vec<Lineage> = parts
@@ -115,10 +163,10 @@ pub(crate) fn set_merged(parts: Vec<Lineage>, profile: &dyn DialectProfile) -> L
115163
let mut lineage: Lineage = merged(parts, profile);
116164
lineage.data_type =
117165
dialect_rules(profile).set_type(lineage.data_type.take(), &branches, &parts_typed);
118-
lineage
166+
coerced(lineage, &parts_typed, profile)
119167
}
120168

121-
/// Alternative branches merged into one column: direct only when each is one same source unchanged.
169+
/// Alternative branches merged into one column, which takes the most significant branch's kind.
122170
pub(crate) fn merged(parts: Vec<Lineage>, profile: &dyn DialectProfile) -> Lineage {
123171
let resolved = parts.iter().all(|part| part.resolved);
124172
let lost: bool = parts.iter().any(|part| part.lost);
@@ -141,19 +189,18 @@ pub(crate) fn merged(parts: Vec<Lineage>, profile: &dyn DialectProfile) -> Linea
141189
(_, true) => Nullability::Nullable,
142190
_ => Nullability::Unknown,
143191
};
144-
let aggregated = parts
192+
let strongest: Option<TransformKind> = strongest_step(&parts);
193+
let unknown: bool = parts
145194
.iter()
146-
.any(|part| part.kind == TransformKind::Aggregation);
147-
let all_direct = parts.iter().all(|part| part.kind == TransformKind::Direct);
148-
let strongest = parts.iter().map(|part| part.kind).max();
195+
.any(|part| !untyped_null(part) && part.data_type.is_none());
196+
let all_direct: bool = parts.iter().all(|part| part.kind == TransformKind::Direct);
149197
let (sources, rows) = unions(parts);
150-
let kind = match (sources.len(), all_direct, aggregated, strongest) {
151-
(_, _, true, _) => TransformKind::Aggregation,
152-
(0, _, _, _) => TransformKind::Constant,
153-
(1, true, _, _) => TransformKind::Direct,
154-
(_, _, _, strongest) => strongest
155-
.unwrap_or(TransformKind::Expression)
156-
.max(TransformKind::Expression),
198+
let kind: TransformKind = match (strongest, unknown) {
199+
(None, _) => TransformKind::Constant,
200+
(Some(kind), true) if !(sources.len() == 1 && all_direct) => {
201+
kind.max(TransformKind::Expression)
202+
}
203+
(Some(kind), _) => kind,
157204
};
158205
Lineage {
159206
sources,

‎crates/sqlquack-semantics/src/lineage/_helpers/tracing/queries.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ use sqlquack_syntax::expressions::queries::models::{Cte, OrderBy, Select, Union,
1010

1111
use crate::dialects::main::dialect_rules::dialect_rules;
1212
use crate::lineage::_helpers::tracing::expressions::{expression_lineage, is_aggregate};
13-
use crate::lineage::_helpers::tracing::lineages::{combined, set_merged, traced_if, unresolved};
13+
use crate::lineage::_helpers::tracing::lineages::{
14+
coerced, combined, set_merged, traced_if, unresolved,
15+
};
1416
use crate::lineage::_helpers::tracing::resolution::{key, plain_key};
1517
use crate::lineage::_helpers::tracing::reuse::{
1618
Reach, Reuse, holds_aggregate, keep_reach, kept_reach, level_traces, reused, reused_items,
@@ -203,11 +205,14 @@ fn left_typed_by_both(
203205
.iter_mut()
204206
.zip(right.columns.iter())
205207
{
206-
column.lineage.data_type = set_merged(
208+
let data_type: Option<Rc<str>> = set_merged(
207209
vec![column.lineage.clone(), other.lineage.clone()],
208210
context.profile,
209211
)
210212
.data_type;
213+
let left_branch: Lineage = column.lineage.clone();
214+
column.lineage.data_type = data_type;
215+
column.lineage = coerced(column.lineage.clone(), &[left_branch], context.profile);
211216
}
212217
left
213218
}

‎crates/sqlquack-semantics/src/lineage/_helpers/tracing/sources.rs‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ use sqlquack_syntax::expressions::queries::models::{
1313

1414
use crate::dialects::main::dialect_rules::dialect_rules;
1515
use crate::lineage::_helpers::tracing::expressions::expression_lineage;
16-
use crate::lineage::_helpers::tracing::lineages::{combined, constant, direct, merged, unresolved};
16+
use crate::lineage::_helpers::tracing::lineages::{
17+
coerced, combined, constant, direct, merged, unresolved,
18+
};
1719
use crate::lineage::_helpers::tracing::queries::{empty_scope, renamed, resolved_query};
1820
use crate::lineage::_helpers::tracing::resolution::{key, plain_key};
1921
use crate::lineage::_helpers::typing::rules::mapped_timestamp;
@@ -852,12 +854,14 @@ fn unpivot_source(
852854
_ => None,
853855
})
854856
.collect();
855-
let value = merged(
856-
unpivot
857-
.columns
858-
.iter()
859-
.map(|column| expression_lineage(column, &input, context))
860-
.collect(),
857+
let unpivoted_values: Vec<Lineage> = unpivot
858+
.columns
859+
.iter()
860+
.map(|column| expression_lineage(column, &input, context))
861+
.collect();
862+
let value: Lineage = coerced(
863+
merged(unpivoted_values.clone(), context.profile),
864+
&unpivoted_values,
861865
context.profile,
862866
);
863867
let passed: Vec<ScopedColumn> = passed_columns(&input.sources, &unpivoted, context);
@@ -906,7 +910,11 @@ fn values_column(
906910
read.push(expression_lineage(value, scope, context));
907911
}
908912
}
909-
merged(read, context.profile)
913+
coerced(
914+
merged(read.clone(), context.profile),
915+
&read,
916+
context.profile,
917+
)
910918
}
911919

912920
/// The columns of `sources` a PIVOT or UNPIVOT passes through: those it does not consume.

‎crates/sqlquack-semantics/src/lineage/models.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::lineage::types::{DialectRules, LineageSchema, SharedColumns};
1818
pub enum TransformKind {
1919
/// It reads no source column.
2020
Constant,
21-
/// It is one source column unchanged.
21+
/// It is a source column unchanged, or one of several that branches pass through unchanged.
2222
Direct,
2323
/// It is a cast of what it reads.
2424
Cast,

‎crates/sqlquack-semantics/src/lineage/types.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use std::rc::Rc;
55

66
use sqlquack_syntax::{DataType, Expression};
77

8+
use crate::dialects::types::DialectProfile;
89
use crate::lineage::_helpers::checks::window_only::named_window_only;
910
use crate::lineage::main::rendered_type::rendered_type;
1011
use crate::lineage::models::{Engine, Nullability};
@@ -197,6 +198,11 @@ pub(crate) trait DialectRules: Sync {
197198
None
198199
}
199200

201+
/// Whether merging a value of type `from` into a column of type `to` converts the value.
202+
fn merge_converts(&self, from: &str, to: &str, profile: &dyn DialectProfile) -> bool {
203+
!profile.same_type(from, to)
204+
}
205+
200206
/// A set operation's type, from its `merged` type, its typed `branches` and all its `parts`.
201207
fn set_type(
202208
&self,

‎crates/sqlquack-semantics/src/postgres/profile/_helpers/typing.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,20 @@ fn catalogue_name(spelling: &str) -> String {
224224
name.to_owned()
225225
}
226226

227+
/// Whether merging a value spelled `from` into a column spelled `to` converts the value.
228+
pub(crate) fn postgres_merge_converts(from: &str, to: &str) -> bool {
229+
catalogue_name(from) != catalogue_name(to)
230+
|| (!type_modifiers(to).is_empty() && type_modifiers(from) != type_modifiers(to))
231+
}
232+
233+
/// A type spelling's modifiers, everything after its opening parenthesis, without whitespace.
234+
fn type_modifiers(spelling: &str) -> String {
235+
let Some((_, rest)) = spelling.split_once('(') else {
236+
return String::new();
237+
};
238+
rest.chars().filter(|c| !c.is_whitespace()).collect()
239+
}
240+
227241
/// The category PostgreSQL files a value of `family` under; none when the family is unknown.
228242
fn family_category(family: Family) -> Option<char> {
229243
Some(match family {

‎crates/sqlquack-semantics/src/postgres/profile/models.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ use crate::lineage::types::DialectRules;
1414
use crate::lineage::types::ValueType;
1515
use crate::postgres::profile::_helpers::names::postgres_name;
1616
use crate::postgres::profile::_helpers::typing::{
17-
called, postgres_cast_spelling, postgres_literal_type, postgres_set_type, postgres_type,
18-
window_function,
17+
called, postgres_cast_spelling, postgres_literal_type, postgres_merge_converts,
18+
postgres_set_type, postgres_type, window_function,
1919
};
2020
use crate::postgres::profile::constants::POSTGRES_SYSTEM_COLUMNS;
2121

@@ -217,6 +217,10 @@ impl DialectRules for PostgresRules {
217217
)
218218
}
219219

220+
fn merge_converts(&self, from: &str, to: &str, _profile: &dyn DialectProfile) -> bool {
221+
postgres_merge_converts(from, to)
222+
}
223+
220224
fn set_type(
221225
&self,
222226
merged: Option<Rc<str>>,

0 commit comments

Comments
 (0)