googleapis / googleapis/google-cloud-python

Support calling SAFE_CAST via sqlalchemy

Đang mở
#15,779 1 bình luận 0 reaction 1 người được giao Được @suzmue nhận Xem trên GitHub
api: bigquery
Ngôn ngữ chính
Python
Star
5.4k
Fork
1.8k
Merge trung bình
3 ngày 4 giờ
Pull request đã merge (30 ngày)
122

Mô tả

**Is your feature request related to a problem? Please describe.**
I could not find a way to use [SAFE_CAST](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#safe_casting) 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(...).

```python
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.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.