|
4 | 4 | import re |
5 | 5 | import uuid |
6 | 6 | import warnings |
| 7 | +from typing import Any |
7 | 8 | from urllib.parse import quote |
8 | 9 |
|
9 | 10 | import google.oauth2.credentials |
|
24 | 25 | get_project_auth_headers, |
25 | 26 | ) |
26 | 27 | from deepnote_toolkit.ipython_utils import output_sql_metadata |
| 28 | +from deepnote_toolkit.logging import LoggerManager |
27 | 29 | from deepnote_toolkit.ocelots.pandas.utils import deduplicate_columns |
28 | 30 | from deepnote_toolkit.sql.duckdb_sql import execute_duckdb_sql |
29 | 31 | from deepnote_toolkit.sql.jinjasql_utils import render_jinja_sql_template |
|
33 | 35 | from deepnote_toolkit.sql.sql_utils import is_single_select_query |
34 | 36 | from deepnote_toolkit.sql.url_utils import replace_user_pass_in_pg_url |
35 | 37 |
|
| 38 | +logger = LoggerManager().get_logger() |
| 39 | + |
| 40 | + |
| 41 | +# TODO(BLU-5171): Temporary hack to allow cancelling BigQuery jobs on KeyboardInterrupt (e.g. when user cancels cell execution) |
| 42 | +# Can be removed once |
| 43 | +# 1. https://github.com/googleapis/python-bigquery/pull/2331 is merged and released |
| 44 | +# 2. Dependicies updated for the toolkit. We don't depend on google-cloud-bigquery directly, but it's transitive |
| 45 | +# dependency through sqlalchemy-bigquery |
| 46 | +def _monkeypatch_bigquery_wait_or_cancel(): |
| 47 | + try: |
| 48 | + from typing import Optional, Union |
| 49 | + |
| 50 | + import google.cloud.bigquery._job_helpers as _job_helpers |
| 51 | + from google.cloud.bigquery import job, table |
| 52 | + |
| 53 | + def _wait_or_cancel( |
| 54 | + job_obj: job.QueryJob, |
| 55 | + api_timeout: Optional[float], |
| 56 | + wait_timeout: Optional[Union[object, float]], |
| 57 | + retry: Optional[Any], |
| 58 | + page_size: Optional[int], |
| 59 | + max_results: Optional[int], |
| 60 | + ) -> table.RowIterator: |
| 61 | + try: |
| 62 | + return job_obj.result( |
| 63 | + page_size=page_size, |
| 64 | + max_results=max_results, |
| 65 | + retry=retry, |
| 66 | + timeout=wait_timeout, |
| 67 | + ) |
| 68 | + except (KeyboardInterrupt, Exception): |
| 69 | + try: |
| 70 | + job_obj.cancel(retry=retry, timeout=api_timeout) |
| 71 | + except (KeyboardInterrupt, Exception): |
| 72 | + pass |
| 73 | + raise |
| 74 | + |
| 75 | + _job_helpers._wait_or_cancel = _wait_or_cancel |
| 76 | + logger.debug("Successfully monkeypatched google.cloud.bigquery._job_helpers._wait_or_cancel") |
| 77 | + except ImportError: |
| 78 | + logger.debug("Could not monkeypatch BigQuery _wait_or_cancel: google.cloud.bigquery not available") |
| 79 | + except Exception as e: |
| 80 | + logger.warning("Failed to monkeypatch BigQuery _wait_or_cancel: %s", repr(e)) |
| 81 | + |
| 82 | + |
| 83 | +_monkeypatch_bigquery_wait_or_cancel() |
| 84 | + |
36 | 85 |
|
37 | 86 | def compile_sql_query( |
38 | 87 | skip_jinja_template_render, |
|
0 commit comments