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

BigQuery parsing produces incorrect AST for DATE_TRUNC where unit is WEEK(WEEKDAY) #1563

Closed
pmsanford opened this issue May 6, 2023 · 1 comment
Assignees

Comments

@pmsanford
Copy link
Contributor

I've tested this on the latest released version as well as on main and it is the same both places

Fully reproducible code snippet

parse_one("DATE_TRUNC(tbl.col, WEEK(MONDAY))", read="bigquery").sql("bigquery")
# produces 'DATE_TRUNC(tbl.col, )'

Official Documentation
Here are the BigQuery docs for DATE_TRUNC showing WEEK(WEEKDAY) is a valid option: https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date_trunc

I believe this happens because at this point:

unit=exp.Literal.string(seq_get(args, 1).name), # type: ignore
the return value of seq_get(args, 1) for a WEEK (or QUARTER or other date part) is an exp.Column, but WEEK(MONDAY) is an exp.Week (which of course doesn't have a name property). I hacked together the following custom dialect, which fixes the issue, but I'm guessing isn't going to cut it as a real fix:

class NewBigquery(BigQuery):
    class Parser(BigQuery.Parser):
        FUNCTIONS = {
            **BigQuery.Parser.FUNCTIONS,
            "DATE_TRUNC": lambda args: exp.DateTrunc(
                unit=exp.Literal.string(seq_get(args, 1).sql()),  # type: ignore
                this=seq_get(args, 0),
                )
            }

I hacked around a little in bigquery.py to try and put together a PR but I wasn't able to quite figure out the right way to do it. I'm happy to contribute a PR if someone can point me in the right direction.

@tobymao tobymao self-assigned this May 6, 2023
@tobymao tobymao closed this as completed in 4f0b3ed May 6, 2023
@tobymao
Copy link
Owner

tobymao commented May 6, 2023

thanks for the detailed report. i look forward to your future prs!

adrianisk pushed a commit to adrianisk/sqlglot that referenced this issue Jun 21, 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

No branches or pull requests

2 participants