Skip to content

Commit cb8dcb6

Browse files
committed
Fix: Always set the varchar size when creating a table in redshift (#1881)
* Fix: Always set the varchar size when creating a table in redshift * Cast NULL instead of the original projection
1 parent 49f7d11 commit cb8dcb6

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

sqlmesh/core/engine_adapter/redshift.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,13 +108,20 @@ def _create_table_exp(
108108
if target["name"] == "TARGETENTRY":
109109
resdom = target["resdom"]
110110
# https://github.com/postgres/postgres/blob/master/src/include/catalog/pg_type.dat
111-
if resdom["restype"] == "1043" and resdom["restypmod"] == "- 1":
111+
if resdom["restype"] == "1043":
112+
size = (
113+
int(resdom["restypmod"]) - 4
114+
if resdom["restypmod"] != "- 1"
115+
else "MAX"
116+
)
117+
# Cast NULL instead of the original projection to trick the planner into assigning a
118+
# correct type to the column.
112119
select.select(
113120
exp.cast(
114-
exp.to_identifier(resdom["resname"]),
115-
"VARCHAR(MAX)",
121+
exp.null(),
122+
f"VARCHAR({size})",
116123
dialect=self.dialect,
117-
),
124+
).as_(resdom["resname"]),
118125
copy=False,
119126
)
120127
else:

tests/core/engine_adapter/test_redshift.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,8 @@ def test_create_table_from_query_exists_no_if_not_exists(
8484

8585
assert to_sql_calls(adapter) == [
8686
'EXPLAIN VERBOSE CREATE TABLE "test_table" AS SELECT "a", "b", "x" + 1 AS "c", "d" AS "d" FROM "table"',
87-
'CREATE TABLE "test_table" AS SELECT CAST("a" AS VARCHAR(MAX)), "b", CAST("c" '
88-
'AS VARCHAR(MAX)), CAST("d" AS VARCHAR(MAX)) FROM (SELECT "a", "b", "x" + 1 '
87+
'CREATE TABLE "test_table" AS SELECT CAST(NULL AS VARCHAR(MAX)) AS "a", CAST(NULL AS VARCHAR(60)) AS "b", CAST(NULL '
88+
'AS VARCHAR(MAX)) AS "c", CAST(NULL AS VARCHAR(MAX)) AS "d" FROM (SELECT "a", "b", "x" + 1 '
8989
'AS "c", "d" AS "d" FROM "table") AS "_subquery"',
9090
]
9191

0 commit comments

Comments
 (0)