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

Support calling SAFE_CAST via sqlalchemy #1099

Open
suhas-dc opened this issue Jul 26, 2024 · 0 comments
Open

Support calling SAFE_CAST via sqlalchemy #1099

suhas-dc opened this issue Jul 26, 2024 · 0 comments
Assignees
Labels
api: bigquery Issues related to the googleapis/python-bigquery-sqlalchemy API.

Comments

@suhas-dc
Copy link

suhas-dc commented Jul 26, 2024

Is your feature request related to a problem? Please describe.
I could not find a way to use SAFE_CAST which returns NULL if the cast fails rather than failing the query.

Describe the solution you'd like
A custom safe_cast function provided by the library that compiles to SAFE_CAST.

Describe alternatives you've considered
I can implement a custom safe_cast function within my codebase. But, I would have to subclass sqlalchemy.sql.Cast (say SafeCast) and override the visit_cast function in the bigquery dialect to compile SafeCast into SAFE_CAST(...) instead of `CAST(...).

class SafeCast(Cast):
    pass

def safe_cast(col: ColumnElement, type_: TypeEngine)) -> SafeCast:
    return SafeCast(col, type_)

# Define custom Bigquery dialect and compiler with
def visit_cast(self, cast, **kwargs):
    if isinstance(cast, SafeCast):
      return "SAFE_CAST(%s AS %s)" % (
          cast.clause._compiler_dispatch(self, **kwargs),
          cast.typeclause._compiler_dispatch(self, **kwargs),
      )
    else:
      return super().visit_cast(cast, **kwargs)

Additional context
Add any other context or screenshots about the feature request here.

@product-auto-label product-auto-label bot added the api: bigquery Issues related to the googleapis/python-bigquery-sqlalchemy API. label Jul 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api: bigquery Issues related to the googleapis/python-bigquery-sqlalchemy API.
Projects
None yet
Development

No branches or pull requests

2 participants