Skip to content

Commit ce8316a

Browse files
Arthur031221ionnich
authored andcommitted
fix(scd2): preserve NULL values in historical rows
Select target values using an explicit row-existence flag carried into the SCD2 join. Choose a flag alias that does not overlap source or prefixed target columns, including case-insensitive names. Co-authored-by: Nicholas <71755971+ionnich@users.noreply.github.com> Signed-off-by: Arthur031221 <levi74108520963@gmail.com>
1 parent ca3f919 commit ce8316a

5 files changed

Lines changed: 504 additions & 49 deletions

File tree

‎sqlmesh/core/engine_adapter/base.py‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
from sqlglot import Dialect, exp
2020
from sqlglot.errors import ErrorLevel
21-
from sqlglot.helper import ensure_list, seq_get
21+
from sqlglot.helper import ensure_list, find_new_name, seq_get
2222
from sqlglot.optimizer.qualify_columns import quote_identifiers
2323

2424
from sqlmesh.core.dialect import (
@@ -2095,6 +2095,11 @@ def remove_managed_columns(
20952095
prefixed_col = exp.column(column).copy()
20962096
prefixed_col.this.set("this", f"t_{prefixed_col.name}")
20972097
prefixed_unmanaged_columns.append(prefixed_col)
2098+
target_exists_column = find_new_name(
2099+
{col.name.lower() for col in prefixed_columns_to_types}
2100+
| {col.lower() for col in unmanaged_columns_to_types},
2101+
"t__exists",
2102+
)
20982103
query = (
20992104
exp.Select() # type: ignore
21002105
.select(*table_columns)
@@ -2163,6 +2168,7 @@ def remove_managed_columns(
21632168
"joined",
21642169
exp.select(
21652170
exp.column("_exists", table="source").as_("_exists"),
2171+
exp.column("_exists", table="latest").as_(target_exists_column),
21662172
*(
21672173
exp.column(col, table="latest").as_(prefixed_columns_to_types[i].this)
21682174
for i, col in enumerate(target_columns_to_types)
@@ -2186,6 +2192,7 @@ def remove_managed_columns(
21862192
.union(
21872193
exp.select(
21882194
exp.column("_exists", table="source").as_("_exists"),
2195+
exp.column("_exists", table="latest").as_(target_exists_column),
21892196
*(
21902197
exp.column(col, table="latest").as_(
21912198
prefixed_columns_to_types[i].this
@@ -2217,11 +2224,15 @@ def remove_managed_columns(
22172224
"updated_rows",
22182225
exp.select(
22192226
*(
2220-
exp.func(
2221-
"COALESCE",
2227+
exp.Case()
2228+
.when(
2229+
exp.column(target_exists_column, table="joined")
2230+
.is_(exp.Null())
2231+
.not_(),
22222232
exp.column(prefixed_unmanaged_columns[i].this, table="joined"),
2223-
exp.column(col, table="joined"),
2224-
).as_(col)
2233+
)
2234+
.else_(exp.column(col, table="joined"))
2235+
.as_(col)
22252236
for i, col in enumerate(unmanaged_columns_to_types)
22262237
),
22272238
valid_from_case_stmt,

0 commit comments

Comments
 (0)