Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: add terse coalesce operator #1991

Merged
merged 4 commits into from
Aug 3, 2023
Merged

Conversation

z3z1ma
Copy link
Contributor

@z3z1ma z3z1ma commented Aug 3, 2023

One of the most common operations we perform in queries other than casting is coalescing. Offering a terse syntax available to all dialects just as you do with the :: casting is hugely beneficial. This feature is also immediately attractive within a SQLMesh project and is just generally a pretty neat showcase of the power of sqlglot.

SELECT x ?? y FROM z -> SELECT COALESCE(x, y) FROM z
"SELECT a, b ?? 'No Data' FROM z" -> SELECT a, COALESCE(b, 'No Data') FROM z

cc: @tobymao

@z3z1ma
Copy link
Contributor Author

z3z1ma commented Aug 3, 2023

While you could, probably detect ?? chained one after another and put them all into a single COALESCE(.., .., ..) function, its significantly simpler this way, probably more resilient, and just as correct as far as I can tell. And the code footprint to enable this is beautifully simple. 🤓

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.

LGTM, good idea Alex 👍

By the way, implementing the ?? operator in this way means that expressions like

a + b ?? c

will be parsed as a + COALESCE(b, c). Perhaps this is something obvious, but I wanted to point it out in case people don't feel this should be the operator's precedence. Of course, one can always wrap a + b in parentheses to produce COALESCE((a + b), c).

@tobymao
Copy link
Owner

tobymao commented Aug 3, 2023

@z3z1ma i'm not sure this is right, i would have thought this was closer to a bitwise operation like concat x || y. can we move it out of column ops?

sqlglot/parser.py Outdated Show resolved Hide resolved
sqlglot/parser.py Outdated Show resolved Hide resolved
sqlglot/parser.py Outdated Show resolved Hide resolved
@z3z1ma z3z1ma requested a review from tobymao August 3, 2023 22:51
@tobymao tobymao merged commit 12c2e9b into tobymao:main Aug 3, 2023
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.

3 participants