Skip to content

Conversation

@MikeWallis42
Copy link
Contributor

Fixes #4595

Further building upon #3940 there was a gap whereby the UPDATE part of a MERGE query needed to be fully qualified if it's used within a function.
The specific example we had was when we were concatenating arrays but I've substituted for a coalesce in the unit test.

@georgesittas
Copy link
Collaborator

Thanks for the PR @MikeWallis42, asked some questions to understand this better.

@MikeWallis42
Copy link
Contributor Author

@georgesittas, I've pushed up what I think is a better solution, I haven't checked Postgres specifically but the tests are still passing.
The documentation seems to suggest that it should be similar to Trino, I've focused on stripping relevant table aliases from where expression is not mentioned in the following documentation.

https://trino.io/docs/current/sql/merge.html#merge
https://www.postgresql.org/docs/current/sql-merge.html

Trino

WHEN MATCHED [ AND condition ]
    THEN UPDATE SET ( column = expression [, ...] )
WHEN NOT MATCHED [ AND condition ]
    THEN INSERT [ column_list ] VALUES (expression, ...)

Postgres

UPDATE SET { column_name = { expression | DEFAULT } |
             ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
             ( column_name [, ...] ) = ( sub-SELECT )
           } [, ...]
INSERT [( column_name [, ...] )]
[ OVERRIDING { SYSTEM | USER } VALUE ]
{ VALUES ( { expression | DEFAULT } [, ...] ) | DEFAULT VALUES }

My previous implementation wouldn't have been comprehensive enough as you suggested.

Copy link
Collaborator

@georgesittas georgesittas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These changes look reasonable. I was able to run this successfully in Postgres as a quick sanity check:

georgesittas=# MERGE INTO foo AS target USING (SELECT a, b FROM tbl) AS src ON src.a = target.a WHEN MATCHED THEN UPDATE SET b = COALESCE(src.b, target.b) WHEN NOT MATCHED THEN INSERT (a, b) VALUES (src.a, src.b);

MERGE 1

@georgesittas georgesittas merged commit b7ab3f1 into tobymao:main Jan 13, 2025
7 checks passed
@MikeWallis42 MikeWallis42 deleted the trino_merge_target branch January 14, 2025 08:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Trino - when matched ambiguous column when using a function

2 participants