diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac559949552b90fd0340722870ca9e8558702301 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef0980ddb8d37946f063a0f62ad4b63353477e81 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/base.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbaa540fe7eaf5fcc1b09ffc0a9f189be621fa0d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/aiplatform_v1/services/dataset_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c4c817d2a82947de3437b80dac72219e7e815dc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de9c513ffa87818f01b50eaac6c066baef2b3329 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_http.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dae36dcb1a555873cb9f2f5fe4fee182fa7d97b8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_http.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_job_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_job_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f0d5bd00cfb9ac9eab8f8093f9e6c1defa81f7a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_job_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_pandas_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_pandas_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b33c9a71d4ffe5957b26864e2efc410461822282 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_pandas_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_pyarrow_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_pyarrow_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d46781a1eb21104a1b82420e0d854a32031a7cb7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_pyarrow_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_tqdm_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_tqdm_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9487e7b8fe145965c1c9383472b52c87380090b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_tqdm_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_versions_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_versions_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0852f25683e455cd29c3e0fa0f8c81e538a6afb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/_versions_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/dataset.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97b0c90dbc3be58d86ae3ad168aa0cf1a98278a4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/dataset.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/encryption_configuration.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/encryption_configuration.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d780bdd37bfc0075d39548e42b8f1509aa740b1d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/encryption_configuration.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/enums.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/enums.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47d7e4f5290106406d02c0d4cd8f7996927a1b73 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/enums.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7aa783d9dea2fb8065a2cbb93abc93963ea4fc38 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/exceptions.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/external_config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/external_config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57a5a45cdfe658b32a922905f123d94e368b97d1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/external_config.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/format_options.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/format_options.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cd174a29a2294cdb8d022dd14b8f1c48028e04c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/format_options.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/iam.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/iam.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13ffb2880c105481eee1aa5730c15f9403aeed5f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/iam.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/model.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/model.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bffa67656bb664bb80c3ce080977a74444ade938 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/model.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/opentelemetry_tracing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/opentelemetry_tracing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fe2ab4f9ca0edfc0ee2c7924f801d60ee83bb5d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/opentelemetry_tracing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/query.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/query.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4f890945278aaa2010c32c394d5aca27f7326ba Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/query.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/retry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/retry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11bc26a9287b34c105c43ae4b03d73ac5298d83d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/retry.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/schema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1988f783b0d50cb4ee2ead92b51bd1fbd023eae Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/schema.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/standard_sql.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/standard_sql.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d0cd70e44c985bb1ee0cb650e59b384ef581c5b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/standard_sql.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce36ece1bd3e7125a470794fb63fcad6b87309b2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/__pycache__/version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d1a723949b104e355b0ba2cd334beef9a91793a0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__init__.py @@ -0,0 +1,87 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Google BigQuery implementation of the Database API Specification v2.0. + +This module implements the `Python Database API Specification v2.0 (DB-API)`_ +for Google BigQuery. + +.. _Python Database API Specification v2.0 (DB-API): + https://www.python.org/dev/peps/pep-0249/ +""" + +from google.cloud.bigquery.dbapi.connection import connect +from google.cloud.bigquery.dbapi.connection import Connection +from google.cloud.bigquery.dbapi.cursor import Cursor +from google.cloud.bigquery.dbapi.exceptions import Warning +from google.cloud.bigquery.dbapi.exceptions import Error +from google.cloud.bigquery.dbapi.exceptions import InterfaceError +from google.cloud.bigquery.dbapi.exceptions import DatabaseError +from google.cloud.bigquery.dbapi.exceptions import DataError +from google.cloud.bigquery.dbapi.exceptions import OperationalError +from google.cloud.bigquery.dbapi.exceptions import IntegrityError +from google.cloud.bigquery.dbapi.exceptions import InternalError +from google.cloud.bigquery.dbapi.exceptions import ProgrammingError +from google.cloud.bigquery.dbapi.exceptions import NotSupportedError +from google.cloud.bigquery.dbapi.types import Binary +from google.cloud.bigquery.dbapi.types import Date +from google.cloud.bigquery.dbapi.types import DateFromTicks +from google.cloud.bigquery.dbapi.types import Time +from google.cloud.bigquery.dbapi.types import TimeFromTicks +from google.cloud.bigquery.dbapi.types import Timestamp +from google.cloud.bigquery.dbapi.types import TimestampFromTicks +from google.cloud.bigquery.dbapi.types import BINARY +from google.cloud.bigquery.dbapi.types import DATETIME +from google.cloud.bigquery.dbapi.types import NUMBER +from google.cloud.bigquery.dbapi.types import ROWID +from google.cloud.bigquery.dbapi.types import STRING + + +apilevel = "2.0" + +# Threads may share the module and connections, but not cursors. +threadsafety = 2 + +paramstyle = "pyformat" + +__all__ = [ + "apilevel", + "threadsafety", + "paramstyle", + "connect", + "Connection", + "Cursor", + "Warning", + "Error", + "InterfaceError", + "DatabaseError", + "DataError", + "OperationalError", + "IntegrityError", + "InternalError", + "ProgrammingError", + "NotSupportedError", + "Binary", + "Date", + "DateFromTicks", + "Time", + "TimeFromTicks", + "Timestamp", + "TimestampFromTicks", + "BINARY", + "DATETIME", + "NUMBER", + "ROWID", + "STRING", +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e49941d495abcbee28d4aec76814947ca78355c6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22a0a9e788e70fce40c7ec2eb96fde66037eab6b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/connection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7b39fe52f449e232fa1280589ad4426d5816c97 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/connection.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/cursor.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/cursor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d6f0805376cb484bd90e589d3436bb31179a9f6 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/cursor.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ef7b4aa52f12a6a6826cd6a517f358ac0e7dfd8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/exceptions.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1ab81f63ce307d89d16851fbe3b62ff431216ea Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/__pycache__/types.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/_helpers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ab05ce82a397fa8f004a44b94378e0e624445d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/_helpers.py @@ -0,0 +1,522 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from collections import abc as collections_abc +import datetime +import decimal +import functools +import numbers +import re +import typing + +from google.cloud import bigquery +from google.cloud.bigquery import table, query +from google.cloud.bigquery.dbapi import exceptions + + +_NUMERIC_SERVER_MIN = decimal.Decimal("-9.9999999999999999999999999999999999999E+28") +_NUMERIC_SERVER_MAX = decimal.Decimal("9.9999999999999999999999999999999999999E+28") + +type_parameters_re = re.compile( + r""" + \( + \s*[0-9]+\s* + (, + \s*[0-9]+\s* + )* + \) + """, + re.VERBOSE, +) + + +def _parameter_type(name, value, query_parameter_type=None, value_doc=""): + if query_parameter_type: + # Strip type parameters + query_parameter_type = type_parameters_re.sub("", query_parameter_type) + try: + parameter_type = getattr( + query.SqlParameterScalarTypes, query_parameter_type.upper() + )._type + except AttributeError: + raise exceptions.ProgrammingError( + f"The given parameter type, {query_parameter_type}," + f" for {name} is not a valid BigQuery scalar type." + ) + else: + parameter_type = bigquery_scalar_type(value) + if parameter_type is None: + raise exceptions.ProgrammingError( + f"Encountered parameter {name} with " + f"{value_doc} value {value} of unexpected type." + ) + return parameter_type + + +def scalar_to_query_parameter(value, name=None, query_parameter_type=None): + """Convert a scalar value into a query parameter. + + Args: + value (Any): + A scalar value to convert into a query parameter. + + name (str): + (Optional) Name of the query parameter. + query_parameter_type (Optional[str]): Given type for the parameter. + + Returns: + google.cloud.bigquery.ScalarQueryParameter: + A query parameter corresponding with the type and value of the plain + Python object. + + Raises: + google.cloud.bigquery.dbapi.exceptions.ProgrammingError: + if the type cannot be determined. + """ + return bigquery.ScalarQueryParameter( + name, _parameter_type(name, value, query_parameter_type), value + ) + + +def array_to_query_parameter(value, name=None, query_parameter_type=None): + """Convert an array-like value into a query parameter. + + Args: + value (Sequence[Any]): The elements of the array (should not be a + string-like Sequence). + name (Optional[str]): Name of the query parameter. + query_parameter_type (Optional[str]): Given type for the parameter. + + Returns: + A query parameter corresponding with the type and value of the plain + Python object. + + Raises: + google.cloud.bigquery.dbapi.exceptions.ProgrammingError: + if the type of array elements cannot be determined. + """ + if not array_like(value): + raise exceptions.ProgrammingError( + "The value of parameter {} must be a sequence that is " + "not string-like.".format(name) + ) + + if query_parameter_type or value: + array_type = _parameter_type( + name, + value[0] if value else None, + query_parameter_type, + value_doc="array element ", + ) + else: + raise exceptions.ProgrammingError( + "Encountered an empty array-like value of parameter {}, cannot " + "determine array elements type.".format(name) + ) + + return bigquery.ArrayQueryParameter(name, array_type, value) + + +def _parse_struct_fields( + fields, + base, + parse_struct_field=re.compile( + r""" + (?:(\w+)\s+) # field name + ([A-Z0-9<> ,()]+) # Field type + $""", + re.VERBOSE | re.IGNORECASE, + ).match, +): + # Split a string of struct fields. They're defined by commas, but + # we have to avoid splitting on commas internal to fields. For + # example: + # name string, children array> + # + # only has 2 top-level fields. + fields = fields.split(",") + fields = list(reversed(fields)) # in the off chance that there are very many + while fields: + field = fields.pop() + while fields and field.count("<") != field.count(">"): + field += "," + fields.pop() + + m = parse_struct_field(field.strip()) + if not m: + raise exceptions.ProgrammingError( + f"Invalid struct field, {field}, in {base}" + ) + yield m.group(1, 2) + + +SCALAR, ARRAY, STRUCT = ("s", "a", "r") + + +def _parse_type( + type_, + name, + base, + complex_query_parameter_parse=re.compile( + r""" + \s* + (ARRAY|STRUCT|RECORD) # Type + \s* + <([A-Z0-9_<> ,()]+)> # Subtype(s) + \s*$ + """, + re.IGNORECASE | re.VERBOSE, + ).match, +): + if "<" not in type_: + # Scalar + + # Strip type parameters + type_ = type_parameters_re.sub("", type_).strip() + try: + type_ = getattr(query.SqlParameterScalarTypes, type_.upper()) + except AttributeError: + raise exceptions.ProgrammingError( + f"The given parameter type, {type_}," + f"{' for ' + name if name else ''}" + f" is not a valid BigQuery scalar type, in {base}." + ) + if name: + type_ = type_.with_name(name) + return SCALAR, type_ + + m = complex_query_parameter_parse(type_) + if not m: + raise exceptions.ProgrammingError(f"Invalid parameter type, {type_}") + tname, sub = m.group(1, 2) + if tname.upper() == "ARRAY": + sub_type = complex_query_parameter_type(None, sub, base) + if isinstance(sub_type, query.ArrayQueryParameterType): + raise exceptions.ProgrammingError(f"Array can't contain an array in {base}") + sub_type._complex__src = sub + return ARRAY, sub_type + else: + return STRUCT, _parse_struct_fields(sub, base) + + +def complex_query_parameter_type(name: typing.Optional[str], type_: str, base: str): + """Construct a parameter type (`StructQueryParameterType`) for a complex type + + or a non-complex type that's part of a complex type. + + Examples: + + array> + + struct>> + + This is used for computing array types. + """ + + type_type, sub_type = _parse_type(type_, name, base) + if type_type == SCALAR: + result_type = sub_type + elif type_type == ARRAY: + result_type = query.ArrayQueryParameterType(sub_type, name=name) + elif type_type == STRUCT: + fields = [ + complex_query_parameter_type(field_name, field_type, base) + for field_name, field_type in sub_type + ] + result_type = query.StructQueryParameterType(*fields, name=name) + else: # pragma: NO COVER + raise AssertionError("Bad type_type", type_type) # Can't happen :) + + return result_type + + +def complex_query_parameter( + name: typing.Optional[str], value, type_: str, base: typing.Optional[str] = None +): + """ + Construct a query parameter for a complex type (array or struct record) + + or for a subtype, which may not be complex + + Examples: + + array> + + struct>> + + """ + param: typing.Union[ + query.ScalarQueryParameter, + query.ArrayQueryParameter, + query.StructQueryParameter, + ] + + base = base or type_ + + type_type, sub_type = _parse_type(type_, name, base) + + if type_type == SCALAR: + param = query.ScalarQueryParameter(name, sub_type._type, value) + elif type_type == ARRAY: + if not array_like(value): + raise exceptions.ProgrammingError( + f"Array type with non-array-like value" + f" with type {type(value).__name__}" + ) + param = query.ArrayQueryParameter( + name, + sub_type, + ( + value + if isinstance(sub_type, query.ScalarQueryParameterType) + else [ + complex_query_parameter(None, v, sub_type._complex__src, base) + for v in value + ] + ), + ) + elif type_type == STRUCT: + if not isinstance(value, collections_abc.Mapping): + raise exceptions.ProgrammingError(f"Non-mapping value for type {type_}") + value_keys = set(value) + fields = [] + for field_name, field_type in sub_type: + if field_name not in value: + raise exceptions.ProgrammingError( + f"No field value for {field_name} in {type_}" + ) + value_keys.remove(field_name) + fields.append( + complex_query_parameter(field_name, value[field_name], field_type, base) + ) + if value_keys: + raise exceptions.ProgrammingError(f"Extra data keys for {type_}") + + param = query.StructQueryParameter(name, *fields) + else: # pragma: NO COVER + raise AssertionError("Bad type_type", type_type) # Can't happen :) + + return param + + +def _dispatch_parameter(type_, value, name=None): + if type_ is not None and "<" in type_: + param = complex_query_parameter(name, value, type_) + elif isinstance(value, collections_abc.Mapping): + raise NotImplementedError( + f"STRUCT-like parameter values are not supported" + f"{' (parameter ' + name + ')' if name else ''}," + f" unless an explicit type is give in the parameter placeholder" + f" (e.g. '%({name if name else ''}:struct<...>)s')." + ) + elif array_like(value): + param = array_to_query_parameter(value, name, type_) + else: + param = scalar_to_query_parameter(value, name, type_) + + return param + + +def to_query_parameters_list(parameters, parameter_types): + """Converts a sequence of parameter values into query parameters. + + Args: + parameters (Sequence[Any]): Sequence of query parameter values. + parameter_types: + A list of parameter types, one for each parameter. + Unknown types are provided as None. + + Returns: + List[google.cloud.bigquery.query._AbstractQueryParameter]: + A list of query parameters. + """ + return [ + _dispatch_parameter(type_, value) + for value, type_ in zip(parameters, parameter_types) + ] + + +def to_query_parameters_dict(parameters, query_parameter_types): + """Converts a dictionary of parameter values into query parameters. + + Args: + parameters (Mapping[str, Any]): Dictionary of query parameter values. + parameter_types: + A dictionary of parameter types. It needn't have a key for each + parameter. + + Returns: + List[google.cloud.bigquery.query._AbstractQueryParameter]: + A list of named query parameters. + """ + return [ + _dispatch_parameter(query_parameter_types.get(name), value, name) + for name, value in parameters.items() + ] + + +def to_query_parameters(parameters, parameter_types): + """Converts DB-API parameter values into query parameters. + + Args: + parameters (Union[Mapping[str, Any], Sequence[Any]]): + A dictionary or sequence of query parameter values. + parameter_types (Union[Mapping[str, str], Sequence[str]]): + A dictionary or list of parameter types. + + If parameters is a mapping, then this must be a dictionary + of parameter types. It needn't have a key for each + parameter. + + If parameters is a sequence, then this must be a list of + parameter types, one for each paramater. Unknown types + are provided as None. + + Returns: + List[google.cloud.bigquery.query._AbstractQueryParameter]: + A list of query parameters. + """ + if parameters is None: + return [] + + if isinstance(parameters, collections_abc.Mapping): + return to_query_parameters_dict(parameters, parameter_types) + else: + return to_query_parameters_list(parameters, parameter_types) + + +def bigquery_scalar_type(value): + """Return a BigQuery name of the scalar type that matches the given value. + + If the scalar type name could not be determined (e.g. for non-scalar + values), ``None`` is returned. + + Args: + value (Any) + + Returns: + Optional[str]: The BigQuery scalar type name. + """ + if isinstance(value, bool): + return "BOOL" + elif isinstance(value, numbers.Integral): + return "INT64" + elif isinstance(value, numbers.Real): + return "FLOAT64" + elif isinstance(value, decimal.Decimal): + vtuple = value.as_tuple() + # NUMERIC values have precision of 38 (number of digits) and scale of 9 (number + # of fractional digits), and their max absolute value must be strictly smaller + # than 1.0E+29. + # https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#decimal_types + if ( + len(vtuple.digits) <= 38 # max precision: 38 + and vtuple.exponent >= -9 # max scale: 9 + and _NUMERIC_SERVER_MIN <= value <= _NUMERIC_SERVER_MAX + ): + return "NUMERIC" + else: + return "BIGNUMERIC" + + elif isinstance(value, str): + return "STRING" + elif isinstance(value, bytes): + return "BYTES" + elif isinstance(value, datetime.datetime): + return "DATETIME" if value.tzinfo is None else "TIMESTAMP" + elif isinstance(value, datetime.date): + return "DATE" + elif isinstance(value, datetime.time): + return "TIME" + + return None + + +def array_like(value): + """Determine if the given value is array-like. + + Examples of array-like values (as interpreted by this function) are + sequences such as ``list`` and ``tuple``, but not strings and other + iterables such as sets. + + Args: + value (Any) + + Returns: + bool: ``True`` if the value is considered array-like, ``False`` otherwise. + """ + return isinstance(value, collections_abc.Sequence) and not isinstance( + value, (str, bytes, bytearray) + ) + + +def to_bq_table_rows(rows_iterable): + """Convert table rows to BigQuery table Row instances. + + Args: + rows_iterable (Iterable[Mapping]): + An iterable of row data items to convert to ``Row`` instances. + + Returns: + Iterable[google.cloud.bigquery.table.Row] + """ + + def to_table_row(row): + # NOTE: We fetch ARROW values, thus we need to convert them to Python + # objects with as_py(). + values = tuple(value.as_py() for value in row.values()) + keys_to_index = {key: i for i, key in enumerate(row.keys())} + return table.Row(values, keys_to_index) + + return (to_table_row(row_data) for row_data in rows_iterable) + + +def raise_on_closed( + exc_msg, exc_class=exceptions.ProgrammingError, closed_attr_name="_closed" +): + """Make public instance methods raise an error if the instance is closed.""" + + def _raise_on_closed(method): + """Make a non-static method raise an error if its containing instance is closed.""" + + def with_closed_check(self, *args, **kwargs): + if getattr(self, closed_attr_name): + raise exc_class(exc_msg) + return method(self, *args, **kwargs) + + functools.update_wrapper(with_closed_check, method) + return with_closed_check + + def decorate_public_methods(klass): + """Apply ``_raise_on_closed()`` decorator to public instance methods.""" + for name in dir(klass): + if name.startswith("_") and name != "__iter__": + continue + + member = getattr(klass, name) + if not callable(member): + continue + + # We need to check for class/static methods directly in the instance + # __dict__, not via the retrieved attribute (`member`), as the + # latter is already a callable *produced* by one of these descriptors. + if isinstance(klass.__dict__[name], (staticmethod, classmethod)): + continue + + member = _raise_on_closed(member) + setattr(klass, name, member) + + return klass + + return decorate_public_methods diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/connection.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a69b8fec90074afb01e459c19c3ce0a7ac9fdb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/connection.py @@ -0,0 +1,128 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Connection for the Google BigQuery DB-API.""" + +import weakref + +from google.cloud import bigquery +from google.cloud.bigquery.dbapi import cursor +from google.cloud.bigquery.dbapi import _helpers + + +@_helpers.raise_on_closed("Operating on a closed connection.") +class Connection(object): + """DB-API Connection to Google BigQuery. + + Args: + client (Optional[google.cloud.bigquery.Client]): + A REST API client used to connect to BigQuery. If not passed, a + client is created using default options inferred from the environment. + bqstorage_client(\ + Optional[google.cloud.bigquery_storage_v1.BigQueryReadClient] \ + ): + A client that uses the faster BigQuery Storage API to fetch rows from + BigQuery. If not passed, it is created using the same credentials + as ``client`` (provided that BigQuery Storage dependencies are installed). + prefer_bqstorage_client (Optional[bool]): + Prefer the BigQuery Storage client over the REST client. If Storage + client isn't available, fall back to the REST client. Defaults to + ``True``. + """ + + def __init__( + self, + client=None, + bqstorage_client=None, + prefer_bqstorage_client=True, + ): + if client is None: + client = bigquery.Client() + self._owns_client = True + else: + self._owns_client = False + + # A warning is already raised by the BQ Storage client factory factory if + # instantiation fails, or if the given BQ Storage client instance is outdated. + if not prefer_bqstorage_client: + bqstorage_client = None + self._owns_bqstorage_client = False + elif bqstorage_client is None: + bqstorage_client = client._ensure_bqstorage_client() + self._owns_bqstorage_client = bqstorage_client is not None + else: + self._owns_bqstorage_client = False + bqstorage_client = client._ensure_bqstorage_client(bqstorage_client) + + self._client = client + self._bqstorage_client = bqstorage_client + + self._closed = False + self._cursors_created = weakref.WeakSet() + + def close(self): + """Close the connection and any cursors created from it. + + Any BigQuery clients explicitly passed to the constructor are *not* + closed, only those created by the connection instance itself. + """ + self._closed = True + + if self._owns_client: + self._client.close() + + if self._owns_bqstorage_client: + # There is no close() on the BQ Storage client itself. + self._bqstorage_client._transport.grpc_channel.close() + + for cursor_ in self._cursors_created: + if not cursor_._closed: + cursor_.close() + + def commit(self): + """No-op, but for consistency raise an error if connection is closed.""" + + def cursor(self): + """Return a new cursor object. + + Returns: + google.cloud.bigquery.dbapi.Cursor: A DB-API cursor that uses this connection. + """ + new_cursor = cursor.Cursor(self) + self._cursors_created.add(new_cursor) + return new_cursor + + +def connect(client=None, bqstorage_client=None, prefer_bqstorage_client=True): + """Construct a DB-API connection to Google BigQuery. + + Args: + client (Optional[google.cloud.bigquery.Client]): + A REST API client used to connect to BigQuery. If not passed, a + client is created using default options inferred from the environment. + bqstorage_client(\ + Optional[google.cloud.bigquery_storage_v1.BigQueryReadClient] \ + ): + A client that uses the faster BigQuery Storage API to fetch rows from + BigQuery. If not passed, it is created using the same credentials + as ``client`` (provided that BigQuery Storage dependencies are installed). + prefer_bqstorage_client (Optional[bool]): + Prefer the BigQuery Storage client over the REST client. If Storage + client isn't available, fall back to the REST client. Defaults to + ``True``. + + Returns: + google.cloud.bigquery.dbapi.Connection: A new DB-API connection to BigQuery. + """ + return Connection(client, bqstorage_client, prefer_bqstorage_client) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/cursor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/cursor.py new file mode 100644 index 0000000000000000000000000000000000000000..4beec6929a05d3dcdb95dfc3a96719be7eeb54fd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/cursor.py @@ -0,0 +1,589 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cursor for the Google BigQuery DB-API.""" + +from __future__ import annotations + +import collections +from collections import abc as collections_abc +import re +from typing import Optional + +try: + from google.cloud.bigquery_storage import ArrowSerializationOptions +except ImportError: + _ARROW_COMPRESSION_SUPPORT = False +else: + # Having BQ Storage available implies that pyarrow >=1.0.0 is available, too. + _ARROW_COMPRESSION_SUPPORT = True + +from google.cloud.bigquery import job +from google.cloud.bigquery.dbapi import _helpers +from google.cloud.bigquery.dbapi import exceptions +import google.cloud.exceptions # type: ignore + + +# Per PEP 249: A 7-item sequence containing information describing one result +# column. The first two items (name and type_code) are mandatory, the other +# five are optional and are set to None if no meaningful values can be +# provided. +Column = collections.namedtuple( + "Column", + [ + "name", + "type_code", + "display_size", + "internal_size", + "precision", + "scale", + "null_ok", + ], +) + + +@_helpers.raise_on_closed("Operating on a closed cursor.") +class Cursor(object): + """DB-API Cursor to Google BigQuery. + + Args: + connection (google.cloud.bigquery.dbapi.Connection): + A DB-API connection to Google BigQuery. + """ + + def __init__(self, connection): + self.connection = connection + self.description = None + # Per PEP 249: The attribute is -1 in case no .execute*() has been + # performed on the cursor or the rowcount of the last operation + # cannot be determined by the interface. + self.rowcount = -1 + # Per PEP 249: The arraysize attribute defaults to 1, meaning to fetch + # a single row at a time. However, we deviate from that, and set the + # default to None, allowing the backend to automatically determine the + # most appropriate size. + self.arraysize = None + self._query_data = None + self._query_rows = None + self._closed = False + + @property + def query_job(self) -> Optional[job.QueryJob]: + """google.cloud.bigquery.job.query.QueryJob | None: The query job + created by the last ``execute*()`` call, if a query job was created. + + .. note:: + If the last ``execute*()`` call was ``executemany()``, this is the + last job created by ``executemany()``.""" + rows = self._query_rows + + if rows is None: + return None + + job_id = rows.job_id + project = rows.project + location = rows.location + client = self.connection._client + + if job_id is None: + return None + + return client.get_job(job_id, location=location, project=project) + + def close(self): + """Mark the cursor as closed, preventing its further use.""" + self._closed = True + + def _set_description(self, schema): + """Set description from schema. + + Args: + schema (Sequence[google.cloud.bigquery.schema.SchemaField]): + A description of fields in the schema. + """ + if schema is None: + self.description = None + return + + self.description = tuple( + Column( + name=field.name, + type_code=field.field_type, + display_size=None, + internal_size=None, + precision=None, + scale=None, + null_ok=field.is_nullable, + ) + for field in schema + ) + + def _set_rowcount(self, rows): + """Set the rowcount from a RowIterator. + + Normally, this sets rowcount to the number of rows returned by the + query, but if it was a DML statement, it sets rowcount to the number + of modified rows. + + Args: + query_results (google.cloud.bigquery.query._QueryResults): + Results of a query. + """ + total_rows = 0 + num_dml_affected_rows = rows.num_dml_affected_rows + + if rows.total_rows is not None and rows.total_rows > 0: + total_rows = rows.total_rows + if num_dml_affected_rows is not None and num_dml_affected_rows > 0: + total_rows = num_dml_affected_rows + self.rowcount = total_rows + + def execute(self, operation, parameters=None, job_id=None, job_config=None): + """Prepare and execute a database operation. + + .. note:: + When setting query parameters, values which are "text" + (``unicode`` in Python2, ``str`` in Python3) will use + the 'STRING' BigQuery type. Values which are "bytes" (``str`` in + Python2, ``bytes`` in Python3), will use using the 'BYTES' type. + + A `~datetime.datetime` parameter without timezone information uses + the 'DATETIME' BigQuery type (example: Global Pi Day Celebration + March 14, 2017 at 1:59pm). A `~datetime.datetime` parameter with + timezone information uses the 'TIMESTAMP' BigQuery type (example: + a wedding on April 29, 2011 at 11am, British Summer Time). + + For more information about BigQuery data types, see: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types + + ``STRUCT``/``RECORD`` and ``REPEATED`` query parameters are not + yet supported. See: + https://github.com/GoogleCloudPlatform/google-cloud-python/issues/3524 + + Args: + operation (str): A Google BigQuery query string. + + parameters (Union[Mapping[str, Any], Sequence[Any]]): + (Optional) dictionary or sequence of parameter values. + + job_id (str | None): + (Optional and discouraged) The job ID to use when creating + the query job. For best performance and reliability, manually + setting a job ID is discouraged. + + job_config (google.cloud.bigquery.job.QueryJobConfig): + (Optional) Extra configuration options for the query job. + """ + formatted_operation, parameter_types = _format_operation(operation, parameters) + self._execute( + formatted_operation, parameters, job_id, job_config, parameter_types + ) + + def _execute( + self, formatted_operation, parameters, job_id, job_config, parameter_types + ): + self._query_data = None + self._query_results = None + client = self.connection._client + + # The DB-API uses the pyformat formatting, since the way BigQuery does + # query parameters was not one of the standard options. Convert both + # the query and the parameters to the format expected by the client + # libraries. + query_parameters = _helpers.to_query_parameters(parameters, parameter_types) + + config = job_config or job.QueryJobConfig() + config.query_parameters = query_parameters + + # Start the query and wait for the query to finish. + try: + if job_id is not None: + rows = client.query( + formatted_operation, + job_config=job_config, + job_id=job_id, + job_retry=None, + ).result( + page_size=self.arraysize, + ) + else: + rows = client.query_and_wait( + formatted_operation, + job_config=config, + page_size=self.arraysize, + ) + except google.cloud.exceptions.GoogleCloudError as exc: + raise exceptions.DatabaseError(exc) + + self._query_rows = rows + self._set_description(rows.schema) + + if config.dry_run: + self.rowcount = 0 + else: + self._set_rowcount(rows) + + def executemany(self, operation, seq_of_parameters): + """Prepare and execute a database operation multiple times. + + Args: + operation (str): A Google BigQuery query string. + + seq_of_parameters (Union[Sequence[Mapping[str, Any], Sequence[Any]]]): + Sequence of many sets of parameter values. + """ + if seq_of_parameters: + rowcount = 0 + # There's no reason to format the line more than once, as + # the operation only barely depends on the parameters. So + # we just use the first set of parameters. If there are + # different numbers or types of parameters, we'll error + # anyway. + formatted_operation, parameter_types = _format_operation( + operation, seq_of_parameters[0] + ) + for parameters in seq_of_parameters: + self._execute( + formatted_operation, parameters, None, None, parameter_types + ) + rowcount += self.rowcount + + self.rowcount = rowcount + + def _try_fetch(self, size=None): + """Try to start fetching data, if not yet started. + + Mutates self to indicate that iteration has started. + """ + if self._query_data is not None: + # Already started fetching the data. + return + + rows = self._query_rows + if rows is None: + raise exceptions.InterfaceError( + "No query results: execute() must be called before fetch." + ) + + bqstorage_client = self.connection._bqstorage_client + if rows._should_use_bqstorage( + bqstorage_client, + create_bqstorage_client=False, + ): + rows_iterable = self._bqstorage_fetch(bqstorage_client) + self._query_data = _helpers.to_bq_table_rows(rows_iterable) + return + + self._query_data = iter(rows) + + def _bqstorage_fetch(self, bqstorage_client): + """Start fetching data with the BigQuery Storage API. + + The method assumes that the data about the relevant query job already + exists internally. + + Args: + bqstorage_client(\ + google.cloud.bigquery_storage_v1.BigQueryReadClient \ + ): + A client tha know how to talk to the BigQuery Storage API. + + Returns: + Iterable[Mapping]: + A sequence of rows, represented as dictionaries. + """ + # Hitting this code path with a BQ Storage client instance implies that + # bigquery_storage can indeed be imported here without errors. + from google.cloud import bigquery_storage + + table_reference = self._query_rows._table + + requested_session = bigquery_storage.types.ReadSession( + table=table_reference.to_bqstorage(), + data_format=bigquery_storage.types.DataFormat.ARROW, + ) + + if _ARROW_COMPRESSION_SUPPORT: + requested_session.read_options.arrow_serialization_options.buffer_compression = ( + ArrowSerializationOptions.CompressionCodec.LZ4_FRAME + ) + + read_session = bqstorage_client.create_read_session( + parent="projects/{}".format(table_reference.project), + read_session=requested_session, + # a single stream only, as DB API is not well-suited for multithreading + max_stream_count=1, + retry=None, + timeout=None, + ) + + if not read_session.streams: + return iter([]) # empty table, nothing to read + + stream_name = read_session.streams[0].name + read_rows_stream = bqstorage_client.read_rows(stream_name) + + rows_iterable = read_rows_stream.rows(read_session) + return rows_iterable + + def fetchone(self): + """Fetch a single row from the results of the last ``execute*()`` call. + + .. note:: + If a dry run query was executed, no rows are returned. + + Returns: + Tuple: + A tuple representing a row or ``None`` if no more data is + available. + + Raises: + google.cloud.bigquery.dbapi.InterfaceError: if called before ``execute()``. + """ + self._try_fetch() + try: + return next(self._query_data) + except StopIteration: + return None + + def fetchmany(self, size=None): + """Fetch multiple results from the last ``execute*()`` call. + + .. note:: + If a dry run query was executed, no rows are returned. + + .. note:: + The size parameter is not used for the request/response size. + Set the ``arraysize`` attribute before calling ``execute()`` to + set the batch size. + + Args: + size (int): + (Optional) Maximum number of rows to return. Defaults to the + ``arraysize`` property value. If ``arraysize`` is not set, it + defaults to ``1``. + + Returns: + List[Tuple]: A list of rows. + + Raises: + google.cloud.bigquery.dbapi.InterfaceError: if called before ``execute()``. + """ + if size is None: + # Since self.arraysize can be None (a deviation from PEP 249), + # use an actual PEP 249 default of 1 in such case (*some* number + # is needed here). + size = self.arraysize if self.arraysize else 1 + + self._try_fetch(size=size) + rows = [] + + for row in self._query_data: + rows.append(row) + if len(rows) >= size: + break + + return rows + + def fetchall(self): + """Fetch all remaining results from the last ``execute*()`` call. + + .. note:: + If a dry run query was executed, no rows are returned. + + Returns: + List[Tuple]: A list of all the rows in the results. + + Raises: + google.cloud.bigquery.dbapi.InterfaceError: if called before ``execute()``. + """ + self._try_fetch() + return list(self._query_data) + + def setinputsizes(self, sizes): + """No-op, but for consistency raise an error if cursor is closed.""" + + def setoutputsize(self, size, column=None): + """No-op, but for consistency raise an error if cursor is closed.""" + + def __iter__(self): + self._try_fetch() + return iter(self._query_data) + + +def _format_operation_list(operation, parameters): + """Formats parameters in operation in the way BigQuery expects. + + The input operation will be a query like ``SELECT %s`` and the output + will be a query like ``SELECT ?``. + + Args: + operation (str): A Google BigQuery query string. + + parameters (Sequence[Any]): Sequence of parameter values. + + Returns: + str: A formatted query string. + + Raises: + google.cloud.bigquery.dbapi.ProgrammingError: + if a parameter used in the operation is not found in the + ``parameters`` argument. + """ + formatted_params = ["?" for _ in parameters] + + try: + return operation % tuple(formatted_params) + except (TypeError, ValueError) as exc: + raise exceptions.ProgrammingError(exc) + + +def _format_operation_dict(operation, parameters): + """Formats parameters in operation in the way BigQuery expects. + + The input operation will be a query like ``SELECT %(namedparam)s`` and + the output will be a query like ``SELECT @namedparam``. + + Args: + operation (str): A Google BigQuery query string. + + parameters (Mapping[str, Any]): Dictionary of parameter values. + + Returns: + str: A formatted query string. + + Raises: + google.cloud.bigquery.dbapi.ProgrammingError: + if a parameter used in the operation is not found in the + ``parameters`` argument. + """ + formatted_params = {} + for name in parameters: + escaped_name = name.replace("`", r"\`") + formatted_params[name] = "@`{}`".format(escaped_name) + + try: + return operation % formatted_params + except (KeyError, ValueError, TypeError) as exc: + raise exceptions.ProgrammingError(exc) + + +def _format_operation(operation, parameters): + """Formats parameters in operation in way BigQuery expects. + + Args: + operation (str): A Google BigQuery query string. + + parameters (Union[Mapping[str, Any], Sequence[Any]]): + Optional parameter values. + + Returns: + str: A formatted query string. + + Raises: + google.cloud.bigquery.dbapi.ProgrammingError: + if a parameter used in the operation is not found in the + ``parameters`` argument. + """ + if parameters is None or len(parameters) == 0: + return operation.replace("%%", "%"), None # Still do percent de-escaping. + + operation, parameter_types = _extract_types(operation) + if parameter_types is None: + raise exceptions.ProgrammingError( + f"Parameters were provided, but {repr(operation)} has no placeholders." + ) + + if isinstance(parameters, collections_abc.Mapping): + return _format_operation_dict(operation, parameters), parameter_types + + return _format_operation_list(operation, parameters), parameter_types + + +def _extract_types( + operation, + extra_type_sub=re.compile( + r""" + (%*) # Extra %s. We'll deal with these in the replacement code + + % # Beginning of replacement, %s, %(...)s + + (?:\( # Begin of optional name and/or type + ([^:)]*) # name + (?:: # ':' introduces type + ( # start of type group + [a-zA-Z0-9_<>, ]+ # First part, no parens + + (?: # start sets of parens + non-paren text + \([0-9 ,]+\) # comma-separated groups of digits in parens + # (e.g. string(10)) + (?=[, >)]) # Must be followed by ,>) or space + [a-zA-Z0-9<>, ]* # Optional non-paren chars + )* # Can be zero or more of parens and following text + ) # end of type group + )? # close type clause ":type" + \))? # End of optional name and/or type + + s # End of replacement + """, + re.VERBOSE, + ).sub, +): + """Remove type information from parameter placeholders. + + For every parameter of the form %(name:type)s, replace with %(name)s and add the + item name->type to dict that's returned. + + Returns operation without type information and a dictionary of names and types. + """ + parameter_types = None + + def repl(m): + nonlocal parameter_types + prefix, name, type_ = m.groups() + if len(prefix) % 2: + # The prefix has an odd number of %s, the last of which + # escapes the % we're looking for, so we don't want to + # change anything. + return m.group(0) + + try: + if name: + if not parameter_types: + parameter_types = {} + if type_: + if name in parameter_types: + if type_ != parameter_types[name]: + raise exceptions.ProgrammingError( + f"Conflicting types for {name}: " + f"{parameter_types[name]} and {type_}." + ) + else: + parameter_types[name] = type_ + else: + if not isinstance(parameter_types, dict): + raise TypeError() + + return f"{prefix}%({name})s" + else: + if parameter_types is None: + parameter_types = [] + parameter_types.append(type_) + return f"{prefix}%s" + except (AttributeError, TypeError): + raise exceptions.ProgrammingError( + f"{repr(operation)} mixes named and unamed parameters." + ) + + return extra_type_sub(repl, operation), parameter_types diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/exceptions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..37f7129d06186c0fcfdc9d75ed55168fece90d2c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/exceptions.py @@ -0,0 +1,58 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Exceptions used in the Google BigQuery DB-API.""" + + +class Warning(Exception): + """Exception raised for important DB-API warnings.""" + + +class Error(Exception): + """Exception representing all non-warning DB-API errors.""" + + +class InterfaceError(Error): + """DB-API error related to the database interface.""" + + +class DatabaseError(Error): + """DB-API error related to the database.""" + + +class DataError(DatabaseError): + """DB-API error due to problems with the processed data.""" + + +class OperationalError(DatabaseError): + """DB-API error related to the database operation. + + These errors are not necessarily under the control of the programmer. + """ + + +class IntegrityError(DatabaseError): + """DB-API error when integrity of the database is affected.""" + + +class InternalError(DatabaseError): + """DB-API error when the database encounters an internal error.""" + + +class ProgrammingError(DatabaseError): + """DB-API exception raised for programming errors.""" + + +class NotSupportedError(DatabaseError): + """DB-API error for operations not supported by the database or API.""" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/types.py new file mode 100644 index 0000000000000000000000000000000000000000..717593ae1336d949cbec93ddfbc2abfc51d81011 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/dbapi/types.py @@ -0,0 +1,96 @@ +# Copyright 2017 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Types used in the Google BigQuery DB-API. + +See `PEP-249`_ for details. + +.. _PEP-249: + https://www.python.org/dev/peps/pep-0249/#type-objects-and-constructors +""" + +import datetime + + +Date = datetime.date +Time = datetime.time +Timestamp = datetime.datetime +DateFromTicks = datetime.date.fromtimestamp +TimestampFromTicks = datetime.datetime.fromtimestamp + + +def Binary(data): + """Contruct a DB-API binary value. + + Args: + data (bytes-like): An object containing binary data and that + can be converted to bytes with the `bytes` builtin. + + Returns: + bytes: The binary data as a bytes object. + """ + if isinstance(data, int): + # This is not the conversion we're looking for, because it + # will simply create a bytes object of the given size. + raise TypeError("cannot convert `int` object to binary") + + try: + return bytes(data) + except TypeError: + if isinstance(data, str): + return data.encode("utf-8") + else: + raise + + +def TimeFromTicks(ticks, tz=None): + """Construct a DB-API time value from the given ticks value. + + Args: + ticks (float): + a number of seconds since the epoch; see the documentation of the + standard Python time module for details. + + tz (datetime.tzinfo): (Optional) time zone to use for conversion + + Returns: + datetime.time: time represented by ticks. + """ + dt = datetime.datetime.fromtimestamp(ticks, tz=tz) + return dt.timetz() + + +class _DBAPITypeObject(object): + """DB-API type object which compares equal to many different strings. + + See `PEP-249`_ for details. + + .. _PEP-249: + https://www.python.org/dev/peps/pep-0249/#implementation-hints-for-module-authors + """ + + def __init__(self, *values): + self.values = values + + def __eq__(self, other): + return other in self.values + + +STRING = "STRING" +BINARY = _DBAPITypeObject("BYTES", "RECORD", "STRUCT") +NUMBER = _DBAPITypeObject( + "INTEGER", "INT64", "FLOAT", "FLOAT64", "NUMERIC", "BIGNUMERIC", "BOOLEAN", "BOOL" +) +DATETIME = _DBAPITypeObject("TIMESTAMP", "DATE", "TIME", "DATETIME") +ROWID = "ROWID" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4cda6596516ca5ca5b48bc80c30888dc972c7fe5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__init__.py @@ -0,0 +1,89 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Define API Jobs.""" + +from google.cloud.bigquery.job.base import _AsyncJob +from google.cloud.bigquery.job.base import _error_result_to_exception +from google.cloud.bigquery.job.base import _DONE_STATE +from google.cloud.bigquery.job.base import _JobConfig +from google.cloud.bigquery.job.base import _JobReference +from google.cloud.bigquery.job.base import ReservationUsage +from google.cloud.bigquery.job.base import ScriptStatistics +from google.cloud.bigquery.job.base import ScriptStackFrame +from google.cloud.bigquery.job.base import TransactionInfo +from google.cloud.bigquery.job.base import UnknownJob +from google.cloud.bigquery.job.copy_ import CopyJob +from google.cloud.bigquery.job.copy_ import CopyJobConfig +from google.cloud.bigquery.job.copy_ import OperationType +from google.cloud.bigquery.job.extract import ExtractJob +from google.cloud.bigquery.job.extract import ExtractJobConfig +from google.cloud.bigquery.job.load import LoadJob +from google.cloud.bigquery.job.load import LoadJobConfig +from google.cloud.bigquery.job.query import _contains_order_by +from google.cloud.bigquery.job.query import DmlStats +from google.cloud.bigquery.job.query import QueryJob +from google.cloud.bigquery.job.query import QueryJobConfig +from google.cloud.bigquery.job.query import QueryPlanEntry +from google.cloud.bigquery.job.query import QueryPlanEntryStep +from google.cloud.bigquery.job.query import ScriptOptions +from google.cloud.bigquery.job.query import TimelineEntry +from google.cloud.bigquery.job.query import IncrementalResultStats +from google.cloud.bigquery.enums import Compression +from google.cloud.bigquery.enums import CreateDisposition +from google.cloud.bigquery.enums import DestinationFormat +from google.cloud.bigquery.enums import Encoding +from google.cloud.bigquery.enums import QueryPriority +from google.cloud.bigquery.enums import SchemaUpdateOption +from google.cloud.bigquery.enums import SourceFormat +from google.cloud.bigquery.enums import WriteDisposition + + +# Include classes previously in job.py for backwards compatibility. +__all__ = [ + "_AsyncJob", + "_error_result_to_exception", + "_DONE_STATE", + "_JobConfig", + "_JobReference", + "ReservationUsage", + "ScriptStatistics", + "ScriptStackFrame", + "UnknownJob", + "CopyJob", + "CopyJobConfig", + "OperationType", + "ExtractJob", + "ExtractJobConfig", + "LoadJob", + "LoadJobConfig", + "_contains_order_by", + "DmlStats", + "QueryJob", + "QueryJobConfig", + "QueryPlanEntry", + "QueryPlanEntryStep", + "ScriptOptions", + "TimelineEntry", + "Compression", + "CreateDisposition", + "DestinationFormat", + "Encoding", + "QueryPriority", + "SchemaUpdateOption", + "SourceFormat", + "TransactionInfo", + "WriteDisposition", + "IncrementalResultStats", +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..112322812ab0a8e24b04ba7c0f0f22fb732a11a0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/base.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a23813720ae554fcdeea81de933bbbdf7b82e934 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/base.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/copy_.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/copy_.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa85f3f0b4104157b1e53306f1fe8e269413c4da Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/copy_.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/extract.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/extract.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c56b827865e2c7df5f4978bcf51f36eb66010eac Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/extract.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/load.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/load.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d7c438ea806efb2434b453314ce5174839c4ad Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/__pycache__/load.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/base.py new file mode 100644 index 0000000000000000000000000000000000000000..7576fc9aa64e6c5f775c38e99b142173641e3e53 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/base.py @@ -0,0 +1,1192 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Base classes and helpers for job classes.""" + +from collections import namedtuple +import copy +import http +import threading +import typing +from typing import ClassVar, Dict, Optional, Sequence + +from google.api_core import retry as retries +from google.api_core import exceptions +import google.api_core.future.polling + +from google.cloud.bigquery import _helpers +from google.cloud.bigquery._helpers import _int_or_none +from google.cloud.bigquery.retry import ( + DEFAULT_GET_JOB_TIMEOUT, + DEFAULT_RETRY, +) + + +_DONE_STATE = "DONE" +_STOPPED_REASON = "stopped" +_ERROR_REASON_TO_EXCEPTION = { + "accessDenied": http.client.FORBIDDEN, + "backendError": http.client.INTERNAL_SERVER_ERROR, + "billingNotEnabled": http.client.FORBIDDEN, + "billingTierLimitExceeded": http.client.BAD_REQUEST, + "blocked": http.client.FORBIDDEN, + "duplicate": http.client.CONFLICT, + "internalError": http.client.INTERNAL_SERVER_ERROR, + "invalid": http.client.BAD_REQUEST, + "invalidQuery": http.client.BAD_REQUEST, + "notFound": http.client.NOT_FOUND, + "notImplemented": http.client.NOT_IMPLEMENTED, + "policyViolation": http.client.FORBIDDEN, + "quotaExceeded": http.client.FORBIDDEN, + "rateLimitExceeded": http.client.TOO_MANY_REQUESTS, + "resourceInUse": http.client.BAD_REQUEST, + "resourcesExceeded": http.client.BAD_REQUEST, + "responseTooLarge": http.client.FORBIDDEN, + "stopped": http.client.OK, + "tableUnavailable": http.client.BAD_REQUEST, +} + + +def _error_result_to_exception(error_result, errors=None): + """Maps BigQuery error reasons to an exception. + + The reasons and their matching HTTP status codes are documented on + the `troubleshooting errors`_ page. + + .. _troubleshooting errors: https://cloud.google.com/bigquery\ + /troubleshooting-errors + + Args: + error_result (Mapping[str, str]): The error result from BigQuery. + errors (Union[Iterable[str], None]): The detailed error messages. + + Returns: + google.cloud.exceptions.GoogleAPICallError: The mapped exception. + """ + reason = error_result.get("reason") + status_code = _ERROR_REASON_TO_EXCEPTION.get( + reason, http.client.INTERNAL_SERVER_ERROR + ) + # Manually create error message to preserve both error_result and errors. + # Can be removed once b/310544564 and b/318889899 are resolved. + concatenated_errors = "" + if errors: + concatenated_errors = "; " + for err in errors: + concatenated_errors += ", ".join( + [f"{key}: {value}" for key, value in err.items()] + ) + concatenated_errors += "; " + + # strips off the last unneeded semicolon and space + concatenated_errors = concatenated_errors[:-2] + + error_message = error_result.get("message", "") + concatenated_errors + + return exceptions.from_http_status( + status_code, error_message, errors=[error_result] + ) + + +ReservationUsage = namedtuple("ReservationUsage", "name slot_ms") +ReservationUsage.__doc__ = "Job resource usage for a reservation." +ReservationUsage.name.__doc__ = ( + 'Reservation name or "unreserved" for on-demand resources usage.' +) +ReservationUsage.slot_ms.__doc__ = ( + "Total slot milliseconds used by the reservation for a particular job." +) + + +class TransactionInfo(typing.NamedTuple): + """[Alpha] Information of a multi-statement transaction. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#TransactionInfo + + .. versionadded:: 2.24.0 + """ + + transaction_id: str + """Output only. ID of the transaction.""" + + @classmethod + def from_api_repr(cls, transaction_info: Dict[str, str]) -> "TransactionInfo": + return cls(transaction_info["transactionId"]) + + +class _JobReference(object): + """A reference to a job. + + Args: + job_id (str): ID of the job to run. + project (str): ID of the project where the job runs. + location (str): Location of where the job runs. + """ + + def __init__(self, job_id, project, location): + self._properties = {"jobId": job_id, "projectId": project} + # The location field must not be populated if it is None. + if location: + self._properties["location"] = location + + @property + def job_id(self): + """str: ID of the job.""" + return self._properties.get("jobId") + + @property + def project(self): + """str: ID of the project where the job runs.""" + return self._properties.get("projectId") + + @property + def location(self): + """str: Location where the job runs.""" + return self._properties.get("location") + + def _to_api_repr(self): + """Returns the API resource representation of the job reference.""" + return copy.deepcopy(self._properties) + + @classmethod + def _from_api_repr(cls, resource): + """Returns a job reference for an API resource representation.""" + job_id = resource.get("jobId") + project = resource.get("projectId") + location = resource.get("location") + job_ref = cls(job_id, project, location) + return job_ref + + +class _JobConfig(object): + """Abstract base class for job configuration objects. + + Args: + job_type (str): The key to use for the job configuration. + """ + + def __init__(self, job_type, **kwargs): + self._job_type = job_type + self._properties = {job_type: {}} + for prop, val in kwargs.items(): + setattr(self, prop, val) + + def __setattr__(self, name, value): + """Override to be able to raise error if an unknown property is being set""" + if not name.startswith("_") and not hasattr(type(self), name): + raise AttributeError( + "Property {} is unknown for {}.".format(name, type(self)) + ) + super(_JobConfig, self).__setattr__(name, value) + + @property + def job_timeout_ms(self): + """Optional parameter. Job timeout in milliseconds. If this time limit is exceeded, BigQuery might attempt to stop the job. + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfiguration.FIELDS.job_timeout_ms + e.g. + + job_config = bigquery.QueryJobConfig( job_timeout_ms = 5000 ) + or + job_config.job_timeout_ms = 5000 + + Raises: + ValueError: If ``value`` type is invalid. + """ + + # None as this is an optional parameter. + if self._properties.get("jobTimeoutMs"): + return self._properties["jobTimeoutMs"] + return None + + @job_timeout_ms.setter + def job_timeout_ms(self, value): + try: + value = _int_or_none(value) + except ValueError as err: + raise ValueError("Pass an int for jobTimeoutMs, e.g. 5000").with_traceback( + err.__traceback__ + ) + + if value is not None: + # docs indicate a string is expected by the API + self._properties["jobTimeoutMs"] = str(value) + else: + self._properties.pop("jobTimeoutMs", None) + + @property + def max_slots(self) -> Optional[int]: + """The maximum rate of slot consumption to allow for this job. + + If set, the number of slots used to execute the job will be throttled + to try and keep its slot consumption below the requested rate. + This feature is not generally available. + """ + + max_slots = self._properties.get("maxSlots") + if max_slots is not None: + if isinstance(max_slots, str): + return int(max_slots) + if isinstance(max_slots, int): + return max_slots + return None + + @max_slots.setter + def max_slots(self, value): + try: + value = _int_or_none(value) + except ValueError as err: + raise ValueError("Pass an int for max slots, e.g. 100").with_traceback( + err.__traceback__ + ) + + if value is not None: + self._properties["maxSlots"] = str(value) + else: + self._properties.pop("maxSlots", None) + + @property + def reservation(self): + """str: Optional. The reservation that job would use. + + User can specify a reservation to execute the job. If reservation is + not set, reservation is determined based on the rules defined by the + reservation assignments. The expected format is + projects/{project}/locations/{location}/reservations/{reservation}. + + Raises: + ValueError: If ``value`` type is not None or of string type. + """ + return self._properties.setdefault("reservation", None) + + @reservation.setter + def reservation(self, value): + if value and not isinstance(value, str): + raise ValueError("Reservation must be None or a string.") + self._properties["reservation"] = value + + @property + def labels(self): + """Dict[str, str]: Labels for the job. + + This method always returns a dict. Once a job has been created on the + server, its labels cannot be modified anymore. + + Raises: + ValueError: If ``value`` type is invalid. + """ + return self._properties.setdefault("labels", {}) + + @labels.setter + def labels(self, value): + if not isinstance(value, dict): + raise ValueError("Pass a dict") + self._properties["labels"] = value + + def _get_sub_prop(self, key, default=None): + """Get a value in the ``self._properties[self._job_type]`` dictionary. + + Most job properties are inside the dictionary related to the job type + (e.g. 'copy', 'extract', 'load', 'query'). Use this method to access + those properties:: + + self._get_sub_prop('destinationTable') + + This is equivalent to using the ``_helpers._get_sub_prop`` function:: + + _helpers._get_sub_prop( + self._properties, ['query', 'destinationTable']) + + Args: + key (str): + Key for the value to get in the + ``self._properties[self._job_type]`` dictionary. + default (Optional[object]): + Default value to return if the key is not found. + Defaults to :data:`None`. + + Returns: + object: The value if present or the default. + """ + return _helpers._get_sub_prop( + self._properties, [self._job_type, key], default=default + ) + + def _set_sub_prop(self, key, value): + """Set a value in the ``self._properties[self._job_type]`` dictionary. + + Most job properties are inside the dictionary related to the job type + (e.g. 'copy', 'extract', 'load', 'query'). Use this method to set + those properties:: + + self._set_sub_prop('useLegacySql', False) + + This is equivalent to using the ``_helper._set_sub_prop`` function:: + + _helper._set_sub_prop( + self._properties, ['query', 'useLegacySql'], False) + + Args: + key (str): + Key to set in the ``self._properties[self._job_type]`` + dictionary. + value (object): Value to set. + """ + _helpers._set_sub_prop(self._properties, [self._job_type, key], value) + + def _del_sub_prop(self, key): + """Remove ``key`` from the ``self._properties[self._job_type]`` dict. + + Most job properties are inside the dictionary related to the job type + (e.g. 'copy', 'extract', 'load', 'query'). Use this method to clear + those properties:: + + self._del_sub_prop('useLegacySql') + + This is equivalent to using the ``_helper._del_sub_prop`` function:: + + _helper._del_sub_prop( + self._properties, ['query', 'useLegacySql']) + + Args: + key (str): + Key to remove in the ``self._properties[self._job_type]`` + dictionary. + """ + _helpers._del_sub_prop(self._properties, [self._job_type, key]) + + def to_api_repr(self) -> dict: + """Build an API representation of the job config. + + Returns: + Dict: A dictionary in the format used by the BigQuery API. + """ + return copy.deepcopy(self._properties) + + def _fill_from_default(self, default_job_config=None): + """Merge this job config with a default job config. + + The keys in this object take precedence over the keys in the default + config. The merge is done at the top-level as well as for keys one + level below the job type. + + Args: + default_job_config (google.cloud.bigquery.job._JobConfig): + The default job config that will be used to fill in self. + + Returns: + google.cloud.bigquery.job._JobConfig: A new (merged) job config. + """ + if not default_job_config: + new_job_config = copy.deepcopy(self) + return new_job_config + + if self._job_type != default_job_config._job_type: + raise TypeError( + "attempted to merge two incompatible job types: " + + repr(self._job_type) + + ", " + + repr(default_job_config._job_type) + ) + + # cls is one of the job config subclasses that provides the job_type argument to + # this base class on instantiation, thus missing-parameter warning is a false + # positive here. + new_job_config = self.__class__() # pytype: disable=missing-parameter + + default_job_properties = copy.deepcopy(default_job_config._properties) + for key in self._properties: + if key != self._job_type: + default_job_properties[key] = self._properties[key] + + default_job_properties[self._job_type].update(self._properties[self._job_type]) + new_job_config._properties = default_job_properties + + return new_job_config + + @classmethod + def from_api_repr(cls, resource: dict) -> "_JobConfig": + """Factory: construct a job configuration given its API representation + + Args: + resource (Dict): + A job configuration in the same representation as is returned + from the API. + + Returns: + google.cloud.bigquery.job._JobConfig: Configuration parsed from ``resource``. + """ + # cls is one of the job config subclasses that provides the job_type argument to + # this base class on instantiation, thus missing-parameter warning is a false + # positive here. + job_config = cls() # type: ignore # pytype: disable=missing-parameter + job_config._properties = resource + return job_config + + +class _AsyncJob(google.api_core.future.polling.PollingFuture): + """Base class for asynchronous jobs. + + Args: + job_id (Union[str, _JobReference]): + Job's ID in the project associated with the client or a + fully-qualified job reference. + client (google.cloud.bigquery.client.Client): + Client which holds credentials and project configuration. + """ + + _JOB_TYPE = "unknown" + _CONFIG_CLASS: ClassVar + + def __init__(self, job_id, client): + super(_AsyncJob, self).__init__() + + # The job reference can be either a plain job ID or the full resource. + # Populate the properties dictionary consistently depending on what has + # been passed in. + job_ref = job_id + if not isinstance(job_id, _JobReference): + job_ref = _JobReference(job_id, client.project, None) + self._properties = {"jobReference": job_ref._to_api_repr()} + + self._client = client + self._result_set = False + self._completion_lock = threading.Lock() + + @property + def configuration(self) -> _JobConfig: + """Job-type specific configurtion.""" + configuration: _JobConfig = self._CONFIG_CLASS() # pytype: disable=not-callable + configuration._properties = self._properties.setdefault("configuration", {}) + return configuration + + @property + def job_id(self): + """str: ID of the job.""" + return _helpers._get_sub_prop(self._properties, ["jobReference", "jobId"]) + + @property + def parent_job_id(self): + """Return the ID of the parent job. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics.FIELDS.parent_job_id + + Returns: + Optional[str]: parent job id. + """ + return _helpers._get_sub_prop(self._properties, ["statistics", "parentJobId"]) + + @property + def script_statistics(self) -> Optional["ScriptStatistics"]: + """Statistics for a child job of a script.""" + resource = _helpers._get_sub_prop( + self._properties, ["statistics", "scriptStatistics"] + ) + if resource is None: + return None + return ScriptStatistics(resource) + + @property + def session_info(self) -> Optional["SessionInfo"]: + """[Preview] Information of the session if this job is part of one. + + .. versionadded:: 2.29.0 + """ + resource = _helpers._get_sub_prop( + self._properties, ["statistics", "sessionInfo"] + ) + if resource is None: + return None + return SessionInfo(resource) + + @property + def num_child_jobs(self): + """The number of child jobs executed. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics.FIELDS.num_child_jobs + + Returns: + int + """ + count = _helpers._get_sub_prop(self._properties, ["statistics", "numChildJobs"]) + return int(count) if count is not None else 0 + + @property + def project(self): + """Project bound to the job. + + Returns: + str: the project (derived from the client). + """ + return _helpers._get_sub_prop(self._properties, ["jobReference", "projectId"]) + + @property + def location(self): + """str: Location where the job runs.""" + return _helpers._get_sub_prop(self._properties, ["jobReference", "location"]) + + @property + def reservation_id(self): + """str: Name of the primary reservation assigned to this job. + + Note that this could be different than reservations reported in + the reservation field if parent reservations were used to execute + this job. + """ + return _helpers._get_sub_prop( + self._properties, ["statistics", "reservation_id"] + ) + + def _require_client(self, client): + """Check client or verify over-ride. + + Args: + client (Optional[google.cloud.bigquery.client.Client]): + the client to use. If not passed, falls back to the + ``client`` stored on the current dataset. + + Returns: + google.cloud.bigquery.client.Client: + The client passed in or the currently bound client. + """ + if client is None: + client = self._client + return client + + @property + def job_type(self): + """Type of job. + + Returns: + str: one of 'load', 'copy', 'extract', 'query'. + """ + return self._JOB_TYPE + + @property + def path(self): + """URL path for the job's APIs. + + Returns: + str: the path based on project and job ID. + """ + return "/projects/%s/jobs/%s" % (self.project, self.job_id) + + @property + def labels(self): + """Dict[str, str]: Labels for the job.""" + return self._properties.setdefault("configuration", {}).setdefault("labels", {}) + + @property + def etag(self): + """ETag for the job resource. + + Returns: + Optional[str]: the ETag (None until set from the server). + """ + return self._properties.get("etag") + + @property + def self_link(self): + """URL for the job resource. + + Returns: + Optional[str]: the URL (None until set from the server). + """ + return self._properties.get("selfLink") + + @property + def user_email(self): + """E-mail address of user who submitted the job. + + Returns: + Optional[str]: the URL (None until set from the server). + """ + return self._properties.get("user_email") + + @property + def created(self): + """Datetime at which the job was created. + + Returns: + Optional[datetime.datetime]: + the creation time (None until set from the server). + """ + millis = _helpers._get_sub_prop( + self._properties, ["statistics", "creationTime"] + ) + if millis is not None: + return _helpers._datetime_from_microseconds(millis * 1000.0) + + @property + def started(self): + """Datetime at which the job was started. + + Returns: + Optional[datetime.datetime]: + the start time (None until set from the server). + """ + millis = _helpers._get_sub_prop(self._properties, ["statistics", "startTime"]) + if millis is not None: + return _helpers._datetime_from_microseconds(millis * 1000.0) + + @property + def ended(self): + """Datetime at which the job finished. + + Returns: + Optional[datetime.datetime]: + the end time (None until set from the server). + """ + millis = _helpers._get_sub_prop(self._properties, ["statistics", "endTime"]) + if millis is not None: + return _helpers._datetime_from_microseconds(millis * 1000.0) + + def _job_statistics(self): + """Helper for job-type specific statistics-based properties.""" + statistics = self._properties.get("statistics", {}) + return statistics.get(self._JOB_TYPE, {}) + + @property + def reservation_usage(self): + """Job resource usage breakdown by reservation. + + Returns: + List[google.cloud.bigquery.job.ReservationUsage]: + Reservation usage stats. Can be empty if not set from the server. + """ + usage_stats_raw = _helpers._get_sub_prop( + self._properties, ["statistics", "reservationUsage"], default=() + ) + return [ + ReservationUsage(name=usage["name"], slot_ms=int(usage["slotMs"])) + for usage in usage_stats_raw + ] + + @property + def transaction_info(self) -> Optional[TransactionInfo]: + """Information of the multi-statement transaction if this job is part of one. + + Since a scripting query job can execute multiple transactions, this + property is only expected on child jobs. Use the + :meth:`google.cloud.bigquery.client.Client.list_jobs` method with the + ``parent_job`` parameter to iterate over child jobs. + + .. versionadded:: 2.24.0 + """ + info = self._properties.get("statistics", {}).get("transactionInfo") + if info is None: + return None + else: + return TransactionInfo.from_api_repr(info) + + @property + def error_result(self): + """Output only. Final error result of the job. + + If present, indicates that the job has completed and was unsuccessful. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatus.FIELDS.error_result + + Returns: + Optional[Mapping]: the error information (None until set from the server). + """ + status = self._properties.get("status") + if status is not None: + return status.get("errorResult") + + @property + def errors(self): + """Output only. The first errors encountered during the running of the job. + + The final message includes the number of errors that caused the process to stop. + Errors here do not necessarily mean that the job has not completed or was unsuccessful. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatus.FIELDS.errors + + Returns: + Optional[List[Mapping]]: + the error information (None until set from the server). + """ + status = self._properties.get("status") + if status is not None: + return status.get("errors") + + @property + def state(self): + """Output only. Running state of the job. + + Valid states include 'PENDING', 'RUNNING', and 'DONE'. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatus.FIELDS.state + + Returns: + Optional[str]: + the state (None until set from the server). + """ + status = self._properties.get("status", {}) + return status.get("state") + + def _set_properties(self, api_response): + """Update properties from resource in body of ``api_response`` + + Args: + api_response (Dict): response returned from an API call. + """ + cleaned = api_response.copy() + statistics = cleaned.setdefault("statistics", {}) + if "creationTime" in statistics: + statistics["creationTime"] = float(statistics["creationTime"]) + if "startTime" in statistics: + statistics["startTime"] = float(statistics["startTime"]) + if "endTime" in statistics: + statistics["endTime"] = float(statistics["endTime"]) + + self._properties = cleaned + + # For Future interface + self._set_future_result() + + @classmethod + def _check_resource_config(cls, resource): + """Helper for :meth:`from_api_repr` + + Args: + resource (Dict): resource for the job. + + Raises: + KeyError: + If the resource has no identifier, or + is missing the appropriate configuration. + """ + if "jobReference" not in resource or "jobId" not in resource["jobReference"]: + raise KeyError( + "Resource lacks required identity information: " + '["jobReference"]["jobId"]' + ) + if ( + "configuration" not in resource + or cls._JOB_TYPE not in resource["configuration"] + ): + raise KeyError( + "Resource lacks required configuration: " + '["configuration"]["%s"]' % cls._JOB_TYPE + ) + + def to_api_repr(self): + """Generate a resource for the job.""" + return copy.deepcopy(self._properties) + + _build_resource = to_api_repr # backward-compatibility alias + + def _begin(self, client=None, retry=DEFAULT_RETRY, timeout=None): + """API call: begin the job via a POST request + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/insert + + Args: + client (Optional[google.cloud.bigquery.client.Client]): + The client to use. If not passed, falls back to the ``client`` + associated with the job object or``NoneType`` + retry (Optional[google.api_core.retry.Retry]): + How to retry the RPC. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. + + Raises: + ValueError: + If the job has already begun. + """ + if self.state is not None: + raise ValueError("Job already begun.") + + client = self._require_client(client) + path = "/projects/%s/jobs" % (self.project,) + + # jobs.insert is idempotent because we ensure that every new + # job has an ID. + span_attributes = {"path": path} + api_response = client._call_api( + retry, + span_name="BigQuery.job.begin", + span_attributes=span_attributes, + job_ref=self, + method="POST", + path=path, + data=self.to_api_repr(), + timeout=timeout, + ) + self._set_properties(api_response) + + def exists( + self, + client=None, + retry: "retries.Retry" = DEFAULT_RETRY, + timeout: Optional[float] = None, + ) -> bool: + """API call: test for the existence of the job via a GET request + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get + + Args: + client (Optional[google.cloud.bigquery.client.Client]): + the client to use. If not passed, falls back to the + ``client`` stored on the current dataset. + + retry (Optional[google.api_core.retry.Retry]): How to retry the RPC. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. + + Returns: + bool: Boolean indicating existence of the job. + """ + client = self._require_client(client) + + extra_params = {"fields": "id"} + if self.location: + extra_params["location"] = self.location + + try: + span_attributes = {"path": self.path} + + client._call_api( + retry, + span_name="BigQuery.job.exists", + span_attributes=span_attributes, + job_ref=self, + method="GET", + path=self.path, + query_params=extra_params, + timeout=timeout, + ) + except exceptions.NotFound: + return False + else: + return True + + def reload( + self, + client=None, + retry: "retries.Retry" = DEFAULT_RETRY, + timeout: Optional[float] = DEFAULT_GET_JOB_TIMEOUT, + ): + """API call: refresh job properties via a GET request. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get + + Args: + client (Optional[google.cloud.bigquery.client.Client]): + the client to use. If not passed, falls back to the + ``client`` stored on the current dataset. + + retry (Optional[google.api_core.retry.Retry]): How to retry the RPC. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. + """ + client = self._require_client(client) + + got_job = client.get_job( + self, + project=self.project, + location=self.location, + retry=retry, + timeout=timeout, + ) + self._set_properties(got_job._properties) + + def cancel( + self, + client=None, + retry: Optional[retries.Retry] = DEFAULT_RETRY, + timeout: Optional[float] = None, + ) -> bool: + """API call: cancel job via a POST request + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel + + Args: + client (Optional[google.cloud.bigquery.client.Client]): + the client to use. If not passed, falls back to the + ``client`` stored on the current dataset. + retry (Optional[google.api_core.retry.Retry]): How to retry the RPC. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry`` + + Returns: + bool: Boolean indicating that the cancel request was sent. + """ + client = self._require_client(client) + + extra_params = {} + if self.location: + extra_params["location"] = self.location + + path = "{}/cancel".format(self.path) + span_attributes = {"path": path} + + api_response = client._call_api( + retry, + span_name="BigQuery.job.cancel", + span_attributes=span_attributes, + job_ref=self, + method="POST", + path=path, + query_params=extra_params, + timeout=timeout, + ) + self._set_properties(api_response["job"]) + # The Future interface requires that we return True if the *attempt* + # to cancel was successful. + return True + + # The following methods implement the PollingFuture interface. Note that + # the methods above are from the pre-Future interface and are left for + # compatibility. The only "overloaded" method is :meth:`cancel`, which + # satisfies both interfaces. + + def _set_future_result(self): + """Set the result or exception from the job if it is complete.""" + # This must be done in a lock to prevent the polling thread + # and main thread from both executing the completion logic + # at the same time. + with self._completion_lock: + # If the operation isn't complete or if the result has already been + # set, do not call set_result/set_exception again. + # Note: self._result_set is set to True in set_result and + # set_exception, in case those methods are invoked directly. + if not self.done(reload=False) or self._result_set: + return + + if self.error_result is not None: + exception = _error_result_to_exception( + self.error_result, self.errors or () + ) + self.set_exception(exception) + else: + self.set_result(self) + + def done( + self, + retry: "retries.Retry" = DEFAULT_RETRY, + timeout: Optional[float] = DEFAULT_GET_JOB_TIMEOUT, + reload: bool = True, + ) -> bool: + """Checks if the job is complete. + + Args: + retry (Optional[google.api_core.retry.Retry]): + How to retry the RPC. If the job state is ``DONE``, retrying is aborted + early, as the job will not change anymore. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. + reload (Optional[bool]): + If ``True``, make an API call to refresh the job state of + unfinished jobs before checking. Default ``True``. + + Returns: + bool: True if the job is complete, False otherwise. + """ + # Do not refresh is the state is already done, as the job will not + # change once complete. + if self.state != _DONE_STATE and reload: + self.reload(retry=retry, timeout=timeout) + return self.state == _DONE_STATE + + def result( # type: ignore # (incompatible with supertype) + self, + retry: Optional[retries.Retry] = DEFAULT_RETRY, + timeout: Optional[float] = None, + ) -> "_AsyncJob": + """Start the job and wait for it to complete and get the result. + + Args: + retry (Optional[google.api_core.retry.Retry]): + How to retry the RPC. If the job state is ``DONE``, retrying is aborted + early, as the job will not change anymore. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. + If multiple requests are made under the hood, ``timeout`` + applies to each individual request. + + Returns: + _AsyncJob: This instance. + + Raises: + google.cloud.exceptions.GoogleAPICallError: + if the job failed. + concurrent.futures.TimeoutError: + if the job did not complete in the given timeout. + """ + if self.state is None: + self._begin(retry=retry, timeout=timeout) + + return super(_AsyncJob, self).result(timeout=timeout, retry=retry) + + def cancelled(self): + """Check if the job has been cancelled. + + This always returns False. It's not possible to check if a job was + cancelled in the API. This method is here to satisfy the interface + for :class:`google.api_core.future.Future`. + + Returns: + bool: False + """ + return ( + self.error_result is not None + and self.error_result.get("reason") == _STOPPED_REASON + ) + + def __repr__(self): + result = ( + f"{self.__class__.__name__}<" + f"project={self.project}, location={self.location}, id={self.job_id}" + ">" + ) + return result + + +class ScriptStackFrame(object): + """Stack frame showing the line/column/procedure name where the current + evaluation happened. + + Args: + resource (Map[str, Any]): JSON representation of object. + """ + + def __init__(self, resource): + self._properties = resource + + @property + def procedure_id(self): + """Optional[str]: Name of the active procedure. + + Omitted if in a top-level script. + """ + return self._properties.get("procedureId") + + @property + def text(self): + """str: Text of the current statement/expression.""" + return self._properties.get("text") + + @property + def start_line(self): + """int: One-based start line.""" + return _helpers._int_or_none(self._properties.get("startLine")) + + @property + def start_column(self): + """int: One-based start column.""" + return _helpers._int_or_none(self._properties.get("startColumn")) + + @property + def end_line(self): + """int: One-based end line.""" + return _helpers._int_or_none(self._properties.get("endLine")) + + @property + def end_column(self): + """int: One-based end column.""" + return _helpers._int_or_none(self._properties.get("endColumn")) + + +class ScriptStatistics(object): + """Statistics for a child job of a script. + + Args: + resource (Map[str, Any]): JSON representation of object. + """ + + def __init__(self, resource): + self._properties = resource + + @property + def stack_frames(self) -> Sequence[ScriptStackFrame]: + """Stack trace where the current evaluation happened. + + Shows line/column/procedure name of each frame on the stack at the + point where the current evaluation happened. + + The leaf frame is first, the primary script is last. + """ + return [ + ScriptStackFrame(frame) for frame in self._properties.get("stackFrames", []) + ] + + @property + def evaluation_kind(self) -> Optional[str]: + """str: Indicates the type of child job. + + Possible values include ``STATEMENT`` and ``EXPRESSION``. + """ + return self._properties.get("evaluationKind") + + +class SessionInfo: + """[Preview] Information of the session if this job is part of one. + + .. versionadded:: 2.29.0 + + Args: + resource (Map[str, Any]): JSON representation of object. + """ + + def __init__(self, resource): + self._properties = resource + + @property + def session_id(self) -> Optional[str]: + """The ID of the session.""" + return self._properties.get("sessionId") + + +class UnknownJob(_AsyncJob): + """A job whose type cannot be determined.""" + + @classmethod + def from_api_repr(cls, resource: dict, client) -> "UnknownJob": + """Construct an UnknownJob from the JSON representation. + + Args: + resource (Dict): JSON representation of a job. + client (google.cloud.bigquery.client.Client): + Client connected to BigQuery API. + + Returns: + UnknownJob: Job corresponding to the resource. + """ + job_ref_properties = resource.get( + "jobReference", {"projectId": client.project, "jobId": None} + ) + job_ref = _JobReference._from_api_repr(job_ref_properties) + job = cls(job_ref, client) + # Populate the job reference with the project, even if it has been + # redacted, because we know it should equal that of the request. + resource["jobReference"] = job_ref_properties + job._properties = resource + return job diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/copy_.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/copy_.py new file mode 100644 index 0000000000000000000000000000000000000000..5c52aeed64707225702e459dd6cf555bba3aeae4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/copy_.py @@ -0,0 +1,282 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes for copy jobs.""" + +import typing +from typing import Optional + +from google.cloud.bigquery.encryption_configuration import EncryptionConfiguration +from google.cloud.bigquery import _helpers +from google.cloud.bigquery.table import TableReference + +from google.cloud.bigquery.job.base import _AsyncJob +from google.cloud.bigquery.job.base import _JobConfig +from google.cloud.bigquery.job.base import _JobReference + + +class OperationType: + """Different operation types supported in table copy job. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#operationtype + """ + + OPERATION_TYPE_UNSPECIFIED = "OPERATION_TYPE_UNSPECIFIED" + """Unspecified operation type.""" + + COPY = "COPY" + """The source and destination table have the same table type.""" + + SNAPSHOT = "SNAPSHOT" + """The source table type is TABLE and the destination table type is SNAPSHOT.""" + + CLONE = "CLONE" + """The source table type is TABLE and the destination table type is CLONE.""" + + RESTORE = "RESTORE" + """The source table type is SNAPSHOT and the destination table type is TABLE.""" + + +class CopyJobConfig(_JobConfig): + """Configuration options for copy jobs. + + All properties in this class are optional. Values which are :data:`None` -> + server defaults. Set properties on the constructed configuration by using + the property name as the name of a keyword argument. + """ + + def __init__(self, **kwargs) -> None: + super(CopyJobConfig, self).__init__("copy", **kwargs) + + @property + def create_disposition(self): + """google.cloud.bigquery.job.CreateDisposition: Specifies behavior + for creating tables. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationTableCopy.FIELDS.create_disposition + """ + return self._get_sub_prop("createDisposition") + + @create_disposition.setter + def create_disposition(self, value): + self._set_sub_prop("createDisposition", value) + + @property + def write_disposition(self): + """google.cloud.bigquery.job.WriteDisposition: Action that occurs if + the destination table already exists. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationTableCopy.FIELDS.write_disposition + """ + return self._get_sub_prop("writeDisposition") + + @write_disposition.setter + def write_disposition(self, value): + self._set_sub_prop("writeDisposition", value) + + @property + def destination_encryption_configuration(self): + """google.cloud.bigquery.encryption_configuration.EncryptionConfiguration: Custom + encryption configuration for the destination table. + + Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None` + if using default encryption. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationTableCopy.FIELDS.destination_encryption_configuration + """ + prop = self._get_sub_prop("destinationEncryptionConfiguration") + if prop is not None: + prop = EncryptionConfiguration.from_api_repr(prop) + return prop + + @destination_encryption_configuration.setter + def destination_encryption_configuration(self, value): + api_repr = value + if value is not None: + api_repr = value.to_api_repr() + self._set_sub_prop("destinationEncryptionConfiguration", api_repr) + + @property + def operation_type(self) -> str: + """The operation to perform with this copy job. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationTableCopy.FIELDS.operation_type + """ + return self._get_sub_prop( + "operationType", OperationType.OPERATION_TYPE_UNSPECIFIED + ) + + @operation_type.setter + def operation_type(self, value: Optional[str]): + if value is None: + value = OperationType.OPERATION_TYPE_UNSPECIFIED + self._set_sub_prop("operationType", value) + + @property + def destination_expiration_time(self) -> str: + """google.cloud.bigquery.job.DestinationExpirationTime: The time when the + destination table expires. Expired tables will be deleted and their storage reclaimed. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationTableCopy.FIELDS.destination_expiration_time + """ + return self._get_sub_prop("destinationExpirationTime") + + @destination_expiration_time.setter + def destination_expiration_time(self, value: str): + self._set_sub_prop("destinationExpirationTime", value) + + +class CopyJob(_AsyncJob): + """Asynchronous job: copy data into a table from other tables. + + Args: + job_id (str): the job's ID, within the project belonging to ``client``. + + sources (List[google.cloud.bigquery.table.TableReference]): Table from which data is to be loaded. + + destination (google.cloud.bigquery.table.TableReference): Table into which data is to be loaded. + + client (google.cloud.bigquery.client.Client): + A client which holds credentials and project configuration + for the dataset (which requires a project). + + job_config (Optional[google.cloud.bigquery.job.CopyJobConfig]): + Extra configuration options for the copy job. + """ + + _JOB_TYPE = "copy" + _CONFIG_CLASS = CopyJobConfig + + def __init__(self, job_id, sources, destination, client, job_config=None): + super(CopyJob, self).__init__(job_id, client) + + if job_config is not None: + self._properties["configuration"] = job_config._properties + + if destination: + _helpers._set_sub_prop( + self._properties, + ["configuration", "copy", "destinationTable"], + destination.to_api_repr(), + ) + + if sources: + source_resources = [source.to_api_repr() for source in sources] + _helpers._set_sub_prop( + self._properties, + ["configuration", "copy", "sourceTables"], + source_resources, + ) + + @property + def configuration(self) -> CopyJobConfig: + """The configuration for this copy job.""" + return typing.cast(CopyJobConfig, super().configuration) + + @property + def destination(self): + """google.cloud.bigquery.table.TableReference: Table into which data + is to be loaded. + """ + return TableReference.from_api_repr( + _helpers._get_sub_prop( + self._properties, ["configuration", "copy", "destinationTable"] + ) + ) + + @property + def sources(self): + """List[google.cloud.bigquery.table.TableReference]): Table(s) from + which data is to be loaded. + """ + source_configs = _helpers._get_sub_prop( + self._properties, ["configuration", "copy", "sourceTables"] + ) + if source_configs is None: + single = _helpers._get_sub_prop( + self._properties, ["configuration", "copy", "sourceTable"] + ) + if single is None: + raise KeyError("Resource missing 'sourceTables' / 'sourceTable'") + source_configs = [single] + + sources = [] + for source_config in source_configs: + table_ref = TableReference.from_api_repr(source_config) + sources.append(table_ref) + return sources + + @property + def create_disposition(self): + """See + :attr:`google.cloud.bigquery.job.CopyJobConfig.create_disposition`. + """ + return self.configuration.create_disposition + + @property + def write_disposition(self): + """See + :attr:`google.cloud.bigquery.job.CopyJobConfig.write_disposition`. + """ + return self.configuration.write_disposition + + @property + def destination_encryption_configuration(self): + """google.cloud.bigquery.encryption_configuration.EncryptionConfiguration: Custom + encryption configuration for the destination table. + + Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None` + if using default encryption. + + See + :attr:`google.cloud.bigquery.job.CopyJobConfig.destination_encryption_configuration`. + """ + return self.configuration.destination_encryption_configuration + + def to_api_repr(self): + """Generate a resource for :meth:`_begin`.""" + # Exclude statistics, if set. + return { + "jobReference": self._properties["jobReference"], + "configuration": self._properties["configuration"], + } + + @classmethod + def from_api_repr(cls, resource, client): + """Factory: construct a job given its API representation + + .. note:: + + This method assumes that the project found in the resource matches + the client's project. + + Args: + resource (Dict): dataset job representation returned from the API + client (google.cloud.bigquery.client.Client): + Client which holds credentials and project + configuration for the dataset. + + Returns: + google.cloud.bigquery.job.CopyJob: Job parsed from ``resource``. + """ + cls._check_resource_config(resource) + job_ref = _JobReference._from_api_repr(resource["jobReference"]) + job = cls(job_ref, None, None, client=client) + job._set_properties(resource) + return job diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/extract.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/extract.py new file mode 100644 index 0000000000000000000000000000000000000000..64ec39b7603cef0f9b850397f94ebf2d85ebe50e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/extract.py @@ -0,0 +1,271 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes for extract (export) jobs.""" + +import typing + +from google.cloud.bigquery import _helpers +from google.cloud.bigquery.model import ModelReference +from google.cloud.bigquery.table import Table +from google.cloud.bigquery.table import TableListItem +from google.cloud.bigquery.table import TableReference +from google.cloud.bigquery.job.base import _AsyncJob +from google.cloud.bigquery.job.base import _JobConfig +from google.cloud.bigquery.job.base import _JobReference + + +class ExtractJobConfig(_JobConfig): + """Configuration options for extract jobs. + + All properties in this class are optional. Values which are :data:`None` -> + server defaults. Set properties on the constructed configuration by using + the property name as the name of a keyword argument. + """ + + def __init__(self, **kwargs): + super(ExtractJobConfig, self).__init__("extract", **kwargs) + + @property + def compression(self): + """google.cloud.bigquery.job.Compression: Compression type to use for + exported files. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationExtract.FIELDS.compression + """ + return self._get_sub_prop("compression") + + @compression.setter + def compression(self, value): + self._set_sub_prop("compression", value) + + @property + def destination_format(self): + """google.cloud.bigquery.job.DestinationFormat: Exported file format. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationExtract.FIELDS.destination_format + """ + return self._get_sub_prop("destinationFormat") + + @destination_format.setter + def destination_format(self, value): + self._set_sub_prop("destinationFormat", value) + + @property + def field_delimiter(self): + """str: Delimiter to use between fields in the exported data. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationExtract.FIELDS.field_delimiter + """ + return self._get_sub_prop("fieldDelimiter") + + @field_delimiter.setter + def field_delimiter(self, value): + self._set_sub_prop("fieldDelimiter", value) + + @property + def print_header(self): + """bool: Print a header row in the exported data. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationExtract.FIELDS.print_header + """ + return self._get_sub_prop("printHeader") + + @print_header.setter + def print_header(self, value): + self._set_sub_prop("printHeader", value) + + @property + def use_avro_logical_types(self): + """bool: For loads of Avro data, governs whether Avro logical types are + converted to their corresponding BigQuery types (e.g. TIMESTAMP) rather than + raw types (e.g. INTEGER). + """ + return self._get_sub_prop("useAvroLogicalTypes") + + @use_avro_logical_types.setter + def use_avro_logical_types(self, value): + self._set_sub_prop("useAvroLogicalTypes", bool(value)) + + +class ExtractJob(_AsyncJob): + """Asynchronous job: extract data from a table into Cloud Storage. + + Args: + job_id (str): the job's ID. + + source (Union[ \ + google.cloud.bigquery.table.TableReference, \ + google.cloud.bigquery.model.ModelReference \ + ]): + Table or Model from which data is to be loaded or extracted. + + destination_uris (List[str]): + URIs describing where the extracted data will be written in Cloud + Storage, using the format ``gs:///``. + + client (google.cloud.bigquery.client.Client): + A client which holds credentials and project configuration. + + job_config (Optional[google.cloud.bigquery.job.ExtractJobConfig]): + Extra configuration options for the extract job. + """ + + _JOB_TYPE = "extract" + _CONFIG_CLASS = ExtractJobConfig + + def __init__(self, job_id, source, destination_uris, client, job_config=None): + super(ExtractJob, self).__init__(job_id, client) + + if job_config is not None: + self._properties["configuration"] = job_config._properties + + if source: + source_ref = {"projectId": source.project, "datasetId": source.dataset_id} + + if isinstance(source, (Table, TableListItem, TableReference)): + source_ref["tableId"] = source.table_id + source_key = "sourceTable" + else: + source_ref["modelId"] = source.model_id + source_key = "sourceModel" + + _helpers._set_sub_prop( + self._properties, ["configuration", "extract", source_key], source_ref + ) + + if destination_uris: + _helpers._set_sub_prop( + self._properties, + ["configuration", "extract", "destinationUris"], + destination_uris, + ) + + @property + def configuration(self) -> ExtractJobConfig: + """The configuration for this extract job.""" + return typing.cast(ExtractJobConfig, super().configuration) + + @property + def source(self): + """Union[ \ + google.cloud.bigquery.table.TableReference, \ + google.cloud.bigquery.model.ModelReference \ + ]: Table or Model from which data is to be loaded or extracted. + """ + source_config = _helpers._get_sub_prop( + self._properties, ["configuration", "extract", "sourceTable"] + ) + if source_config: + return TableReference.from_api_repr(source_config) + else: + source_config = _helpers._get_sub_prop( + self._properties, ["configuration", "extract", "sourceModel"] + ) + return ModelReference.from_api_repr(source_config) + + @property + def destination_uris(self): + """List[str]: URIs describing where the extracted data will be + written in Cloud Storage, using the format + ``gs:///``. + """ + return _helpers._get_sub_prop( + self._properties, ["configuration", "extract", "destinationUris"] + ) + + @property + def compression(self): + """See + :attr:`google.cloud.bigquery.job.ExtractJobConfig.compression`. + """ + return self.configuration.compression + + @property + def destination_format(self): + """See + :attr:`google.cloud.bigquery.job.ExtractJobConfig.destination_format`. + """ + return self.configuration.destination_format + + @property + def field_delimiter(self): + """See + :attr:`google.cloud.bigquery.job.ExtractJobConfig.field_delimiter`. + """ + return self.configuration.field_delimiter + + @property + def print_header(self): + """See + :attr:`google.cloud.bigquery.job.ExtractJobConfig.print_header`. + """ + return self.configuration.print_header + + @property + def destination_uri_file_counts(self): + """Return file counts from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics4.FIELDS.destination_uri_file_counts + + Returns: + List[int]: + A list of integer counts, each representing the number of files + per destination URI or URI pattern specified in the extract + configuration. These values will be in the same order as the URIs + specified in the 'destinationUris' field. Returns None if job is + not yet complete. + """ + counts = self._job_statistics().get("destinationUriFileCounts") + if counts is not None: + return [int(count) for count in counts] + return None + + def to_api_repr(self): + """Generate a resource for :meth:`_begin`.""" + # Exclude statistics, if set. + return { + "jobReference": self._properties["jobReference"], + "configuration": self._properties["configuration"], + } + + @classmethod + def from_api_repr(cls, resource: dict, client) -> "ExtractJob": + """Factory: construct a job given its API representation + + .. note:: + + This method assumes that the project found in the resource matches + the client's project. + + Args: + resource (Dict): dataset job representation returned from the API + + client (google.cloud.bigquery.client.Client): + Client which holds credentials and project + configuration for the dataset. + + Returns: + google.cloud.bigquery.job.ExtractJob: Job parsed from ``resource``. + """ + cls._check_resource_config(resource) + job_ref = _JobReference._from_api_repr(resource["jobReference"]) + job = cls(job_ref, None, None, client=client) + job._set_properties(resource) + return job diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/load.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/load.py new file mode 100644 index 0000000000000000000000000000000000000000..9c74f71243938956c459f8ba7b37b13e2dbc96ac --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/load.py @@ -0,0 +1,1185 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes for load jobs.""" + +import typing +from typing import FrozenSet, List, Iterable, Optional, Union + +from google.cloud.bigquery.encryption_configuration import EncryptionConfiguration +from google.cloud.bigquery.enums import SourceColumnMatch +from google.cloud.bigquery.external_config import HivePartitioningOptions +from google.cloud.bigquery.format_options import ParquetOptions +from google.cloud.bigquery import _helpers +from google.cloud.bigquery.schema import SchemaField +from google.cloud.bigquery.schema import _to_schema_fields +from google.cloud.bigquery.table import RangePartitioning +from google.cloud.bigquery.table import TableReference +from google.cloud.bigquery.table import TimePartitioning +from google.cloud.bigquery.job.base import _AsyncJob +from google.cloud.bigquery.job.base import _JobConfig +from google.cloud.bigquery.job.base import _JobReference +from google.cloud.bigquery.query import ConnectionProperty + + +class ColumnNameCharacterMap: + """Indicates the character map used for column names. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#columnnamecharactermap + """ + + COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED = "COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED" + """Unspecified column name character map.""" + + STRICT = "STRICT" + """Support flexible column name and reject invalid column names.""" + + V1 = "V1" + """ Support alphanumeric + underscore characters and names must start with + a letter or underscore. Invalid column names will be normalized.""" + + V2 = "V2" + """Support flexible column name. Invalid column names will be normalized.""" + + +class LoadJobConfig(_JobConfig): + """Configuration options for load jobs. + + Set properties on the constructed configuration by using the property name + as the name of a keyword argument. Values which are unset or :data:`None` + use the BigQuery REST API default values. See the `BigQuery REST API + reference documentation + `_ + for a list of default values. + + Required options differ based on the + :attr:`~google.cloud.bigquery.job.LoadJobConfig.source_format` value. + For example, the BigQuery API's default value for + :attr:`~google.cloud.bigquery.job.LoadJobConfig.source_format` is ``"CSV"``. + When loading a CSV file, either + :attr:`~google.cloud.bigquery.job.LoadJobConfig.schema` must be set or + :attr:`~google.cloud.bigquery.job.LoadJobConfig.autodetect` must be set to + :data:`True`. + """ + + def __init__(self, **kwargs) -> None: + super(LoadJobConfig, self).__init__("load", **kwargs) + + @property + def allow_jagged_rows(self): + """Optional[bool]: Allow missing trailing optional columns (CSV only). + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.allow_jagged_rows + """ + return self._get_sub_prop("allowJaggedRows") + + @allow_jagged_rows.setter + def allow_jagged_rows(self, value): + self._set_sub_prop("allowJaggedRows", value) + + @property + def allow_quoted_newlines(self): + """Optional[bool]: Allow quoted data containing newline characters (CSV only). + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.allow_quoted_newlines + """ + return self._get_sub_prop("allowQuotedNewlines") + + @allow_quoted_newlines.setter + def allow_quoted_newlines(self, value): + self._set_sub_prop("allowQuotedNewlines", value) + + @property + def autodetect(self): + """Optional[bool]: Automatically infer the schema from a sample of the data. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.autodetect + """ + return self._get_sub_prop("autodetect") + + @autodetect.setter + def autodetect(self, value): + self._set_sub_prop("autodetect", value) + + @property + def clustering_fields(self): + """Optional[List[str]]: Fields defining clustering for the table + + (Defaults to :data:`None`). + + Clustering fields are immutable after table creation. + + .. note:: + + BigQuery supports clustering for both partitioned and + non-partitioned tables. + """ + prop = self._get_sub_prop("clustering") + if prop is not None: + return list(prop.get("fields", ())) + + @clustering_fields.setter + def clustering_fields(self, value): + """Optional[List[str]]: Fields defining clustering for the table + + (Defaults to :data:`None`). + """ + if value is not None: + self._set_sub_prop("clustering", {"fields": value}) + else: + self._del_sub_prop("clustering") + + @property + def connection_properties(self) -> List[ConnectionProperty]: + """Connection properties. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.connection_properties + + .. versionadded:: 3.7.0 + """ + resource = self._get_sub_prop("connectionProperties", []) + return [ConnectionProperty.from_api_repr(prop) for prop in resource] + + @connection_properties.setter + def connection_properties(self, value: Iterable[ConnectionProperty]): + self._set_sub_prop( + "connectionProperties", + [prop.to_api_repr() for prop in value], + ) + + @property + def create_disposition(self): + """Optional[google.cloud.bigquery.job.CreateDisposition]: Specifies behavior + for creating tables. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.create_disposition + """ + return self._get_sub_prop("createDisposition") + + @create_disposition.setter + def create_disposition(self, value): + self._set_sub_prop("createDisposition", value) + + @property + def create_session(self) -> Optional[bool]: + """[Preview] If :data:`True`, creates a new session, where + :attr:`~google.cloud.bigquery.job.LoadJob.session_info` will contain a + random server generated session id. + + If :data:`False`, runs load job with an existing ``session_id`` passed in + :attr:`~google.cloud.bigquery.job.LoadJobConfig.connection_properties`, + otherwise runs load job in non-session mode. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.create_session + + .. versionadded:: 3.7.0 + """ + return self._get_sub_prop("createSession") + + @create_session.setter + def create_session(self, value: Optional[bool]): + self._set_sub_prop("createSession", value) + + @property + def decimal_target_types(self) -> Optional[FrozenSet[str]]: + """Possible SQL data types to which the source decimal values are converted. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.decimal_target_types + + .. versionadded:: 2.21.0 + """ + prop = self._get_sub_prop("decimalTargetTypes") + if prop is not None: + prop = frozenset(prop) + return prop + + @decimal_target_types.setter + def decimal_target_types(self, value: Optional[Iterable[str]]): + if value is not None: + self._set_sub_prop("decimalTargetTypes", list(value)) + else: + self._del_sub_prop("decimalTargetTypes") + + @property + def destination_encryption_configuration(self): + """Optional[google.cloud.bigquery.encryption_configuration.EncryptionConfiguration]: Custom + encryption configuration for the destination table. + + Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None` + if using default encryption. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.destination_encryption_configuration + """ + prop = self._get_sub_prop("destinationEncryptionConfiguration") + if prop is not None: + prop = EncryptionConfiguration.from_api_repr(prop) + return prop + + @destination_encryption_configuration.setter + def destination_encryption_configuration(self, value): + api_repr = value + if value is not None: + api_repr = value.to_api_repr() + self._set_sub_prop("destinationEncryptionConfiguration", api_repr) + else: + self._del_sub_prop("destinationEncryptionConfiguration") + + @property + def destination_table_description(self): + """Optional[str]: Description of the destination table. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#DestinationTableProperties.FIELDS.description + """ + prop = self._get_sub_prop("destinationTableProperties") + if prop is not None: + return prop["description"] + + @destination_table_description.setter + def destination_table_description(self, value): + keys = [self._job_type, "destinationTableProperties", "description"] + if value is not None: + _helpers._set_sub_prop(self._properties, keys, value) + else: + _helpers._del_sub_prop(self._properties, keys) + + @property + def destination_table_friendly_name(self): + """Optional[str]: Name given to destination table. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#DestinationTableProperties.FIELDS.friendly_name + """ + prop = self._get_sub_prop("destinationTableProperties") + if prop is not None: + return prop["friendlyName"] + + @destination_table_friendly_name.setter + def destination_table_friendly_name(self, value): + keys = [self._job_type, "destinationTableProperties", "friendlyName"] + if value is not None: + _helpers._set_sub_prop(self._properties, keys, value) + else: + _helpers._del_sub_prop(self._properties, keys) + + @property + def encoding(self): + """Optional[google.cloud.bigquery.job.Encoding]: The character encoding of the + data. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.encoding + """ + return self._get_sub_prop("encoding") + + @encoding.setter + def encoding(self, value): + self._set_sub_prop("encoding", value) + + @property + def field_delimiter(self): + """Optional[str]: The separator for fields in a CSV file. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.field_delimiter + """ + return self._get_sub_prop("fieldDelimiter") + + @field_delimiter.setter + def field_delimiter(self, value): + self._set_sub_prop("fieldDelimiter", value) + + @property + def hive_partitioning(self): + """Optional[:class:`~.external_config.HivePartitioningOptions`]: [Beta] When set, \ + it configures hive partitioning support. + + .. note:: + **Experimental**. This feature is experimental and might change or + have limited support. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.hive_partitioning_options + """ + prop = self._get_sub_prop("hivePartitioningOptions") + if prop is None: + return None + return HivePartitioningOptions.from_api_repr(prop) + + @hive_partitioning.setter + def hive_partitioning(self, value): + if value is not None: + if isinstance(value, HivePartitioningOptions): + value = value.to_api_repr() + else: + raise TypeError("Expected a HivePartitioningOptions instance or None.") + + self._set_sub_prop("hivePartitioningOptions", value) + + @property + def ignore_unknown_values(self): + """Optional[bool]: Ignore extra values not represented in the table schema. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.ignore_unknown_values + """ + return self._get_sub_prop("ignoreUnknownValues") + + @ignore_unknown_values.setter + def ignore_unknown_values(self, value): + self._set_sub_prop("ignoreUnknownValues", value) + + @property + def json_extension(self): + """Optional[str]: The extension to use for writing JSON data to BigQuery. Only supports GeoJSON currently. + + See: https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.json_extension + + """ + return self._get_sub_prop("jsonExtension") + + @json_extension.setter + def json_extension(self, value): + self._set_sub_prop("jsonExtension", value) + + @property + def max_bad_records(self): + """Optional[int]: Number of invalid rows to ignore. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.max_bad_records + """ + return _helpers._int_or_none(self._get_sub_prop("maxBadRecords")) + + @max_bad_records.setter + def max_bad_records(self, value): + self._set_sub_prop("maxBadRecords", value) + + @property + def null_marker(self): + """Optional[str]: Represents a null value (CSV only). + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.null_marker + """ + return self._get_sub_prop("nullMarker") + + @null_marker.setter + def null_marker(self, value): + self._set_sub_prop("nullMarker", value) + + @property + def null_markers(self) -> Optional[List[str]]: + """Optional[List[str]]: A list of strings represented as SQL NULL values in a CSV file. + + .. note:: + null_marker and null_markers can't be set at the same time. + If null_marker is set, null_markers has to be not set. + If null_markers is set, null_marker has to be not set. + If both null_marker and null_markers are set at the same time, a user error would be thrown. + Any strings listed in null_markers, including empty string would be interpreted as SQL NULL. + This applies to all column types. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.null_markers + """ + return self._get_sub_prop("nullMarkers") + + @null_markers.setter + def null_markers(self, value: Optional[List[str]]): + self._set_sub_prop("nullMarkers", value) + + @property + def preserve_ascii_control_characters(self): + """Optional[bool]: Preserves the embedded ASCII control characters when sourceFormat is set to CSV. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.preserve_ascii_control_characters + """ + return self._get_sub_prop("preserveAsciiControlCharacters") + + @preserve_ascii_control_characters.setter + def preserve_ascii_control_characters(self, value): + self._set_sub_prop("preserveAsciiControlCharacters", bool(value)) + + @property + def projection_fields(self) -> Optional[List[str]]: + """Optional[List[str]]: If + :attr:`google.cloud.bigquery.job.LoadJobConfig.source_format` is set to + "DATASTORE_BACKUP", indicates which entity properties to load into + BigQuery from a Cloud Datastore backup. + + Property names are case sensitive and must be top-level properties. If + no properties are specified, BigQuery loads all properties. If any + named property isn't found in the Cloud Datastore backup, an invalid + error is returned in the job result. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.projection_fields + """ + return self._get_sub_prop("projectionFields") + + @projection_fields.setter + def projection_fields(self, value: Optional[List[str]]): + self._set_sub_prop("projectionFields", value) + + @property + def quote_character(self): + """Optional[str]: Character used to quote data sections (CSV only). + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.quote + """ + return self._get_sub_prop("quote") + + @quote_character.setter + def quote_character(self, value): + self._set_sub_prop("quote", value) + + @property + def range_partitioning(self): + """Optional[google.cloud.bigquery.table.RangePartitioning]: + Configures range-based partitioning for destination table. + + .. note:: + **Beta**. The integer range partitioning feature is in a + pre-release state and might change or have limited support. + + Only specify at most one of + :attr:`~google.cloud.bigquery.job.LoadJobConfig.time_partitioning` or + :attr:`~google.cloud.bigquery.job.LoadJobConfig.range_partitioning`. + + Raises: + ValueError: + If the value is not + :class:`~google.cloud.bigquery.table.RangePartitioning` or + :data:`None`. + """ + resource = self._get_sub_prop("rangePartitioning") + if resource is not None: + return RangePartitioning(_properties=resource) + + @range_partitioning.setter + def range_partitioning(self, value): + resource = value + if isinstance(value, RangePartitioning): + resource = value._properties + elif value is not None: + raise ValueError( + "Expected value to be RangePartitioning or None, got {}.".format(value) + ) + self._set_sub_prop("rangePartitioning", resource) + + @property + def reference_file_schema_uri(self): + """Optional[str]: + When creating an external table, the user can provide a reference file with the + table schema. This is enabled for the following formats: + + AVRO, PARQUET, ORC + """ + return self._get_sub_prop("referenceFileSchemaUri") + + @reference_file_schema_uri.setter + def reference_file_schema_uri(self, value): + return self._set_sub_prop("referenceFileSchemaUri", value) + + @property + def schema(self): + """Optional[Sequence[Union[ \ + :class:`~google.cloud.bigquery.schema.SchemaField`, \ + Mapping[str, Any] \ + ]]]: Schema of the destination table. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.schema + """ + schema = _helpers._get_sub_prop(self._properties, ["load", "schema", "fields"]) + if schema is None: + return + return [SchemaField.from_api_repr(field) for field in schema] + + @schema.setter + def schema(self, value): + if value is None: + self._del_sub_prop("schema") + return + + value = _to_schema_fields(value) + + _helpers._set_sub_prop( + self._properties, + ["load", "schema", "fields"], + [field.to_api_repr() for field in value], + ) + + @property + def schema_update_options(self): + """Optional[List[google.cloud.bigquery.job.SchemaUpdateOption]]: Specifies + updates to the destination table schema to allow as a side effect of + the load job. + """ + return self._get_sub_prop("schemaUpdateOptions") + + @schema_update_options.setter + def schema_update_options(self, values): + self._set_sub_prop("schemaUpdateOptions", values) + + @property + def skip_leading_rows(self): + """Optional[int]: Number of rows to skip when reading data (CSV only). + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.skip_leading_rows + """ + return _helpers._int_or_none(self._get_sub_prop("skipLeadingRows")) + + @skip_leading_rows.setter + def skip_leading_rows(self, value): + self._set_sub_prop("skipLeadingRows", str(value)) + + @property + def source_format(self): + """Optional[google.cloud.bigquery.job.SourceFormat]: File format of the data. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.source_format + """ + return self._get_sub_prop("sourceFormat") + + @source_format.setter + def source_format(self, value): + self._set_sub_prop("sourceFormat", value) + + @property + def source_column_match(self) -> Optional[SourceColumnMatch]: + """Optional[google.cloud.bigquery.enums.SourceColumnMatch]: Controls the + strategy used to match loaded columns to the schema. If not set, a sensible + default is chosen based on how the schema is provided. If autodetect is + used, then columns are matched by name. Otherwise, columns are matched by + position. This is done to keep the behavior backward-compatible. + + Acceptable values are: + + SOURCE_COLUMN_MATCH_UNSPECIFIED: Unspecified column name match option. + POSITION: matches by position. This assumes that the columns are ordered + the same way as the schema. + NAME: matches by name. This reads the header row as column names and + reorders columns to match the field names in the schema. + + See: + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.source_column_match + """ + value = self._get_sub_prop("sourceColumnMatch") + return SourceColumnMatch(value) if value is not None else None + + @source_column_match.setter + def source_column_match(self, value: Union[SourceColumnMatch, str, None]): + if value is not None and not isinstance(value, (SourceColumnMatch, str)): + raise TypeError( + "value must be a google.cloud.bigquery.enums.SourceColumnMatch, str, or None" + ) + if isinstance(value, SourceColumnMatch): + value = value.value + self._set_sub_prop("sourceColumnMatch", value if value else None) + + @property + def date_format(self) -> Optional[str]: + """Optional[str]: Date format used for parsing DATE values. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.date_format + """ + return self._get_sub_prop("dateFormat") + + @date_format.setter + def date_format(self, value: Optional[str]): + self._set_sub_prop("dateFormat", value) + + @property + def datetime_format(self) -> Optional[str]: + """Optional[str]: Date format used for parsing DATETIME values. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.datetime_format + """ + return self._get_sub_prop("datetimeFormat") + + @datetime_format.setter + def datetime_format(self, value: Optional[str]): + self._set_sub_prop("datetimeFormat", value) + + @property + def time_zone(self) -> Optional[str]: + """Optional[str]: Default time zone that will apply when parsing timestamp + values that have no specific time zone. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.time_zone + """ + return self._get_sub_prop("timeZone") + + @time_zone.setter + def time_zone(self, value: Optional[str]): + self._set_sub_prop("timeZone", value) + + @property + def time_format(self) -> Optional[str]: + """Optional[str]: Date format used for parsing TIME values. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.time_format + """ + return self._get_sub_prop("timeFormat") + + @time_format.setter + def time_format(self, value: Optional[str]): + self._set_sub_prop("timeFormat", value) + + @property + def timestamp_format(self) -> Optional[str]: + """Optional[str]: Date format used for parsing TIMESTAMP values. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.timestamp_format + """ + return self._get_sub_prop("timestampFormat") + + @timestamp_format.setter + def timestamp_format(self, value: Optional[str]): + self._set_sub_prop("timestampFormat", value) + + @property + def time_partitioning(self): + """Optional[google.cloud.bigquery.table.TimePartitioning]: Specifies time-based + partitioning for the destination table. + + Only specify at most one of + :attr:`~google.cloud.bigquery.job.LoadJobConfig.time_partitioning` or + :attr:`~google.cloud.bigquery.job.LoadJobConfig.range_partitioning`. + """ + prop = self._get_sub_prop("timePartitioning") + if prop is not None: + prop = TimePartitioning.from_api_repr(prop) + return prop + + @time_partitioning.setter + def time_partitioning(self, value): + api_repr = value + if value is not None: + api_repr = value.to_api_repr() + self._set_sub_prop("timePartitioning", api_repr) + else: + self._del_sub_prop("timePartitioning") + + @property + def use_avro_logical_types(self): + """Optional[bool]: For loads of Avro data, governs whether Avro logical types are + converted to their corresponding BigQuery types (e.g. TIMESTAMP) rather than + raw types (e.g. INTEGER). + """ + return self._get_sub_prop("useAvroLogicalTypes") + + @use_avro_logical_types.setter + def use_avro_logical_types(self, value): + self._set_sub_prop("useAvroLogicalTypes", bool(value)) + + @property + def write_disposition(self): + """Optional[google.cloud.bigquery.job.WriteDisposition]: Action that occurs if + the destination table already exists. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.write_disposition + """ + return self._get_sub_prop("writeDisposition") + + @write_disposition.setter + def write_disposition(self, value): + self._set_sub_prop("writeDisposition", value) + + @property + def parquet_options(self): + """Optional[google.cloud.bigquery.format_options.ParquetOptions]: Additional + properties to set if ``sourceFormat`` is set to PARQUET. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.parquet_options + """ + prop = self._get_sub_prop("parquetOptions") + if prop is not None: + prop = ParquetOptions.from_api_repr(prop) + return prop + + @parquet_options.setter + def parquet_options(self, value): + if value is not None: + self._set_sub_prop("parquetOptions", value.to_api_repr()) + else: + self._del_sub_prop("parquetOptions") + + @property + def column_name_character_map(self) -> str: + """Optional[google.cloud.bigquery.job.ColumnNameCharacterMap]: + Character map supported for column names in CSV/Parquet loads. Defaults + to STRICT and can be overridden by Project Config Service. Using this + option with unsupported load formats will result in an error. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.column_name_character_map + """ + return self._get_sub_prop( + "columnNameCharacterMap", + ColumnNameCharacterMap.COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED, + ) + + @column_name_character_map.setter + def column_name_character_map(self, value: Optional[str]): + if value is None: + value = ColumnNameCharacterMap.COLUMN_NAME_CHARACTER_MAP_UNSPECIFIED + self._set_sub_prop("columnNameCharacterMap", value) + + @property + def timestamp_target_precision(self) -> Optional[List[int]]: + """Optional[list[int]]: [Private Preview] Precisions (maximum number of + total digits in base 10) for seconds of TIMESTAMP types that are + allowed to the destination table for autodetection mode. + + Available for the formats: CSV. + + For the CSV Format, Possible values include: + None, [], or [6]: timestamp(6) for all auto detected TIMESTAMP + columns. + [6, 12]: timestamp(6) for all auto detected TIMESTAMP columns that + have less than 6 digits of subseconds. timestamp(12) for all auto + detected TIMESTAMP columns that have more than 6 digits of + subseconds. + [12]: timestamp(12) for all auto detected TIMESTAMP columns. + + The order of the elements in this array is ignored. Inputs that have + higher precision than the highest target precision in this array will + be truncated. + """ + return self._get_sub_prop("timestampTargetPrecision") + + @timestamp_target_precision.setter + def timestamp_target_precision(self, value: Optional[List[int]]): + if value is not None: + self._set_sub_prop("timestampTargetPrecision", value) + else: + self._del_sub_prop("timestampTargetPrecision") + + +class LoadJob(_AsyncJob): + """Asynchronous job for loading data into a table. + + Can load from Google Cloud Storage URIs or from a file. + + Args: + job_id (str): the job's ID + + source_uris (Optional[Sequence[str]]): + URIs of one or more data files to be loaded. See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.source_uris + for supported URI formats. Pass None for jobs that load from a file. + + destination (google.cloud.bigquery.table.TableReference): reference to table into which data is to be loaded. + + client (google.cloud.bigquery.client.Client): + A client which holds credentials and project configuration + for the dataset (which requires a project). + """ + + _JOB_TYPE = "load" + _CONFIG_CLASS = LoadJobConfig + + def __init__(self, job_id, source_uris, destination, client, job_config=None): + super(LoadJob, self).__init__(job_id, client) + + if job_config is not None: + self._properties["configuration"] = job_config._properties + + if source_uris is not None: + _helpers._set_sub_prop( + self._properties, ["configuration", "load", "sourceUris"], source_uris + ) + + if destination is not None: + _helpers._set_sub_prop( + self._properties, + ["configuration", "load", "destinationTable"], + destination.to_api_repr(), + ) + + @property + def configuration(self) -> LoadJobConfig: + """The configuration for this load job.""" + return typing.cast(LoadJobConfig, super().configuration) + + @property + def destination(self): + """google.cloud.bigquery.table.TableReference: table where loaded rows are written + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.destination_table + """ + dest_config = _helpers._get_sub_prop( + self._properties, ["configuration", "load", "destinationTable"] + ) + return TableReference.from_api_repr(dest_config) + + @property + def source_uris(self): + """Optional[Sequence[str]]: URIs of data files to be loaded. See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationLoad.FIELDS.source_uris + for supported URI formats. None for jobs that load from a file. + """ + return _helpers._get_sub_prop( + self._properties, ["configuration", "load", "sourceUris"] + ) + + @property + def allow_jagged_rows(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.allow_jagged_rows`. + """ + return self.configuration.allow_jagged_rows + + @property + def allow_quoted_newlines(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.allow_quoted_newlines`. + """ + return self.configuration.allow_quoted_newlines + + @property + def autodetect(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.autodetect`. + """ + return self.configuration.autodetect + + @property + def connection_properties(self) -> List[ConnectionProperty]: + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.connection_properties`. + + .. versionadded:: 3.7.0 + """ + return self.configuration.connection_properties + + @property + def create_disposition(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.create_disposition`. + """ + return self.configuration.create_disposition + + @property + def create_session(self) -> Optional[bool]: + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.create_session`. + + .. versionadded:: 3.7.0 + """ + return self.configuration.create_session + + @property + def encoding(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.encoding`. + """ + return self.configuration.encoding + + @property + def field_delimiter(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.field_delimiter`. + """ + return self.configuration.field_delimiter + + @property + def ignore_unknown_values(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.ignore_unknown_values`. + """ + return self.configuration.ignore_unknown_values + + @property + def max_bad_records(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.max_bad_records`. + """ + return self.configuration.max_bad_records + + @property + def null_marker(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.null_marker`. + """ + return self.configuration.null_marker + + @property + def null_markers(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.null_markers`. + """ + return self.configuration.null_markers + + @property + def quote_character(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.quote_character`. + """ + return self.configuration.quote_character + + @property + def reference_file_schema_uri(self): + """See: + attr:`google.cloud.bigquery.job.LoadJobConfig.reference_file_schema_uri`. + """ + return self.configuration.reference_file_schema_uri + + @property + def skip_leading_rows(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.skip_leading_rows`. + """ + return self.configuration.skip_leading_rows + + @property + def source_format(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.source_format`. + """ + return self.configuration.source_format + + @property + def write_disposition(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.write_disposition`. + """ + return self.configuration.write_disposition + + @property + def schema(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.schema`. + """ + return self.configuration.schema + + @property + def destination_encryption_configuration(self): + """google.cloud.bigquery.encryption_configuration.EncryptionConfiguration: Custom + encryption configuration for the destination table. + + Custom encryption configuration (e.g., Cloud KMS keys) + or :data:`None` if using default encryption. + + See + :attr:`google.cloud.bigquery.job.LoadJobConfig.destination_encryption_configuration`. + """ + return self.configuration.destination_encryption_configuration + + @property + def destination_table_description(self): + """Optional[str] name given to destination table. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#DestinationTableProperties.FIELDS.description + """ + return self.configuration.destination_table_description + + @property + def destination_table_friendly_name(self): + """Optional[str] name given to destination table. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#DestinationTableProperties.FIELDS.friendly_name + """ + return self.configuration.destination_table_friendly_name + + @property + def range_partitioning(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.range_partitioning`. + """ + return self.configuration.range_partitioning + + @property + def time_partitioning(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.time_partitioning`. + """ + return self.configuration.time_partitioning + + @property + def use_avro_logical_types(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.use_avro_logical_types`. + """ + return self.configuration.use_avro_logical_types + + @property + def clustering_fields(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.clustering_fields`. + """ + return self.configuration.clustering_fields + + @property + def source_column_match(self) -> Optional[SourceColumnMatch]: + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.source_column_match`. + """ + return self.configuration.source_column_match + + @property + def date_format(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.date_format`. + """ + return self.configuration.date_format + + @property + def datetime_format(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.datetime_format`. + """ + return self.configuration.datetime_format + + @property + def time_zone(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.time_zone`. + """ + return self.configuration.time_zone + + @property + def time_format(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.time_format`. + """ + return self.configuration.time_format + + @property + def timestamp_format(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.timestamp_format`. + """ + return self.configuration.timestamp_format + + @property + def schema_update_options(self): + """See + :attr:`google.cloud.bigquery.job.LoadJobConfig.schema_update_options`. + """ + return self.configuration.schema_update_options + + @property + def input_file_bytes(self): + """Count of bytes loaded from source files. + + Returns: + Optional[int]: the count (None until set from the server). + + Raises: + ValueError: for invalid value types. + """ + return _helpers._int_or_none( + _helpers._get_sub_prop( + self._properties, ["statistics", "load", "inputFileBytes"] + ) + ) + + @property + def input_files(self): + """Count of source files. + + Returns: + Optional[int]: the count (None until set from the server). + """ + return _helpers._int_or_none( + _helpers._get_sub_prop( + self._properties, ["statistics", "load", "inputFiles"] + ) + ) + + @property + def output_bytes(self): + """Count of bytes saved to destination table. + + Returns: + Optional[int]: the count (None until set from the server). + """ + return _helpers._int_or_none( + _helpers._get_sub_prop( + self._properties, ["statistics", "load", "outputBytes"] + ) + ) + + @property + def output_rows(self): + """Count of rows saved to destination table. + + Returns: + Optional[int]: the count (None until set from the server). + """ + return _helpers._int_or_none( + _helpers._get_sub_prop( + self._properties, ["statistics", "load", "outputRows"] + ) + ) + + def to_api_repr(self): + """Generate a resource for :meth:`_begin`.""" + # Exclude statistics, if set. + return { + "jobReference": self._properties["jobReference"], + "configuration": self._properties["configuration"], + } + + @classmethod + def from_api_repr(cls, resource: dict, client) -> "LoadJob": + """Factory: construct a job given its API representation + + .. note:: + + This method assumes that the project found in the resource matches + the client's project. + + Args: + resource (Dict): dataset job representation returned from the API + + client (google.cloud.bigquery.client.Client): + Client which holds credentials and project + configuration for the dataset. + + Returns: + google.cloud.bigquery.job.LoadJob: Job parsed from ``resource``. + """ + cls._check_resource_config(resource) + job_ref = _JobReference._from_api_repr(resource["jobReference"]) + job = cls(job_ref, None, None, client) + job._set_properties(resource) + return job diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/query.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/query.py new file mode 100644 index 0000000000000000000000000000000000000000..e85e43f6a16465b55c8fcc66eeb7a6b715d50031 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/job/query.py @@ -0,0 +1,2675 @@ +# Copyright 2015 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes for query jobs.""" + +import concurrent.futures +import copy +import re +import time +import typing +from typing import Any, Dict, Iterable, List, Optional, Union + +from google.api_core import exceptions +from google.api_core import retry as retries +import requests + +from google.cloud.bigquery.dataset import Dataset +from google.cloud.bigquery.dataset import DatasetListItem +from google.cloud.bigquery.dataset import DatasetReference +from google.cloud.bigquery.encryption_configuration import EncryptionConfiguration +from google.cloud.bigquery.enums import KeyResultStatementKind, DefaultPandasDTypes +from google.cloud.bigquery.external_config import ExternalConfig +from google.cloud.bigquery import _helpers +from google.cloud.bigquery.query import ( + _query_param_from_api_repr, + ArrayQueryParameter, + ConnectionProperty, + ScalarQueryParameter, + StructQueryParameter, + UDFResource, +) +from google.cloud.bigquery.retry import ( + DEFAULT_RETRY, + DEFAULT_JOB_RETRY, + POLLING_DEFAULT_VALUE, +) +from google.cloud.bigquery.routine import RoutineReference +from google.cloud.bigquery.schema import SchemaField +from google.cloud.bigquery.table import _EmptyRowIterator +from google.cloud.bigquery.table import RangePartitioning +from google.cloud.bigquery.table import _table_arg_to_table_ref +from google.cloud.bigquery.table import TableReference, PropertyGraphReference +from google.cloud.bigquery.table import TimePartitioning +from google.cloud.bigquery._tqdm_helpers import wait_for_query + +from google.cloud.bigquery.job.base import _AsyncJob +from google.cloud.bigquery.job.base import _JobConfig +from google.cloud.bigquery.job.base import _JobReference + +try: + import pandas # type: ignore +except ImportError: + pandas = None + +if typing.TYPE_CHECKING: # pragma: NO COVER + # Assumption: type checks are only used by library developers and CI environments + # that have all optional dependencies installed, thus no conditional imports. + import pandas # type: ignore + import geopandas # type: ignore + import pyarrow # type: ignore + from google.cloud import bigquery_storage + from google.cloud.bigquery.client import Client + from google.cloud.bigquery.table import RowIterator + + +_CONTAINS_ORDER_BY = re.compile(r"ORDER\s+BY", re.IGNORECASE) +_EXCEPTION_FOOTER_TEMPLATE = "{message}\n\nLocation: {location}\nJob ID: {job_id}\n" +_TIMEOUT_BUFFER_SECS = 0.1 + + +def _contains_order_by(query): + """Do we need to preserve the order of the query results? + + This function has known false positives, such as with ordered window + functions: + + .. code-block:: sql + + SELECT SUM(x) OVER ( + window_name + PARTITION BY... + ORDER BY... + window_frame_clause) + FROM ... + + This false positive failure case means the behavior will be correct, but + downloading results with the BigQuery Storage API may be slower than it + otherwise would. This is preferable to the false negative case, where + results are expected to be in order but are not (due to parallel reads). + """ + return query and _CONTAINS_ORDER_BY.search(query) + + +def _from_api_repr_query_parameters(resource): + return [_query_param_from_api_repr(mapping) for mapping in resource] + + +def _to_api_repr_query_parameters(value): + return [query_parameter.to_api_repr() for query_parameter in value] + + +def _from_api_repr_udf_resources(resource): + udf_resources = [] + for udf_mapping in resource: + for udf_type, udf_value in udf_mapping.items(): + udf_resources.append(UDFResource(udf_type, udf_value)) + return udf_resources + + +def _to_api_repr_udf_resources(value): + return [{udf_resource.udf_type: udf_resource.value} for udf_resource in value] + + +def _from_api_repr_table_defs(resource): + return {k: ExternalConfig.from_api_repr(v) for k, v in resource.items()} + + +def _to_api_repr_table_defs(value): + return {k: ExternalConfig.to_api_repr(v) for k, v in value.items()} + + +class BiEngineReason(typing.NamedTuple): + """Reason for BI Engine acceleration failure + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#bienginereason + """ + + code: str = "CODE_UNSPECIFIED" + + reason: str = "" + + @classmethod + def from_api_repr(cls, reason: Dict[str, str]) -> "BiEngineReason": + return cls(reason.get("code", "CODE_UNSPECIFIED"), reason.get("message", "")) + + +class BiEngineStats(typing.NamedTuple): + """Statistics for a BI Engine query + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#bienginestatistics + """ + + mode: str = "ACCELERATION_MODE_UNSPECIFIED" + """ Specifies which mode of BI Engine acceleration was performed (if any) + """ + + reasons: List[BiEngineReason] = [] + """ Contains explanatory messages in case of DISABLED / PARTIAL acceleration + """ + + @classmethod + def from_api_repr(cls, stats: Dict[str, Any]) -> "BiEngineStats": + mode = stats.get("biEngineMode", "ACCELERATION_MODE_UNSPECIFIED") + reasons = [ + BiEngineReason.from_api_repr(r) for r in stats.get("biEngineReasons", []) + ] + return cls(mode, reasons) + + +class DmlStats(typing.NamedTuple): + """Detailed statistics for DML statements. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/DmlStats + """ + + inserted_row_count: int = 0 + """Number of inserted rows. Populated by DML INSERT and MERGE statements.""" + + deleted_row_count: int = 0 + """Number of deleted rows. populated by DML DELETE, MERGE and TRUNCATE statements. + """ + + updated_row_count: int = 0 + """Number of updated rows. Populated by DML UPDATE and MERGE statements.""" + + @classmethod + def from_api_repr(cls, stats: Dict[str, str]) -> "DmlStats": + # NOTE: The field order here must match the order of fields set at the + # class level. + api_fields = ("insertedRowCount", "deletedRowCount", "updatedRowCount") + + args = ( + int(stats.get(api_field, default_val)) + for api_field, default_val in zip(api_fields, cls.__new__.__defaults__) # type: ignore + ) + return cls(*args) + + +class IncrementalResultStats: + """IncrementalResultStats provides information about incremental query execution.""" + + def __init__(self): + self._properties = {} + + @classmethod + def from_api_repr(cls, resource) -> "IncrementalResultStats": + """Factory: construct instance from the JSON repr. + + Args: + resource(Dict[str: object]): + IncrementalResultStats representation returned from API. + + Returns: + google.cloud.bigquery.job.IncrementalResultStats: + stats parsed from ``resource``. + """ + entry = cls() + entry._properties = resource + return entry + + @property + def disabled_reason(self): + """Optional[string]: Reason why incremental results were not + written by the query. + """ + return _helpers._str_or_none(self._properties.get("disabledReason")) + + @property + def result_set_last_replace_time(self): + """Optional[datetime]: The time at which the result table's contents + were completely replaced. May be absent if no results have been written + or the query has completed.""" + from google.cloud._helpers import _rfc3339_nanos_to_datetime + + value = self._properties.get("resultSetLastReplaceTime") + if value: + try: + return _rfc3339_nanos_to_datetime(value) + except ValueError: + pass + return None + + @property + def result_set_last_modify_time(self): + """Optional[datetime]: The time at which the result table's contents + were modified. May be absent if no results have been written or the + query has completed.""" + from google.cloud._helpers import _rfc3339_nanos_to_datetime + + value = self._properties.get("resultSetLastModifyTime") + if value: + try: + return _rfc3339_nanos_to_datetime(value) + except ValueError: + pass + return None + + +class IndexUnusedReason(typing.NamedTuple): + """Reason about why no search index was used in the search query (or sub-query). + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#indexunusedreason + """ + + code: Optional[str] = None + """Specifies the high-level reason for the scenario when no search index was used. + """ + + message: Optional[str] = None + """Free form human-readable reason for the scenario when no search index was used. + """ + + baseTable: Optional[TableReference] = None + """Specifies the base table involved in the reason that no search index was used. + """ + + indexName: Optional[str] = None + """Specifies the name of the unused search index, if available.""" + + @classmethod + def from_api_repr(cls, reason): + code = reason.get("code") + message = reason.get("message") + baseTable = reason.get("baseTable") + indexName = reason.get("indexName") + + return cls(code, message, baseTable, indexName) + + +class SearchStats(typing.NamedTuple): + """Statistics related to Search Queries. Populated as part of JobStatistics2. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#searchstatistics + """ + + mode: Optional[str] = None + """Indicates the type of search index usage in the entire search query.""" + + reason: List[IndexUnusedReason] = [] + """Reason about why no search index was used in the search query (or sub-query)""" + + @classmethod + def from_api_repr(cls, stats: Dict[str, Any]): + mode = stats.get("indexUsageMode", None) + reason = [ + IndexUnusedReason.from_api_repr(r) + for r in stats.get("indexUnusedReasons", []) + ] + return cls(mode, reason) + + +class ScriptOptions: + """Options controlling the execution of scripts. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#ScriptOptions + """ + + def __init__( + self, + statement_timeout_ms: Optional[int] = None, + statement_byte_budget: Optional[int] = None, + key_result_statement: Optional[KeyResultStatementKind] = None, + ): + self._properties: Dict[str, Any] = {} + self.statement_timeout_ms = statement_timeout_ms + self.statement_byte_budget = statement_byte_budget + self.key_result_statement = key_result_statement + + @classmethod + def from_api_repr(cls, resource: Dict[str, Any]) -> "ScriptOptions": + """Factory: construct instance from the JSON repr. + + Args: + resource(Dict[str: Any]): + ScriptOptions representation returned from API. + + Returns: + google.cloud.bigquery.ScriptOptions: + ScriptOptions sample parsed from ``resource``. + """ + entry = cls() + entry._properties = copy.deepcopy(resource) + return entry + + def to_api_repr(self) -> Dict[str, Any]: + """Construct the API resource representation.""" + return copy.deepcopy(self._properties) + + @property + def statement_timeout_ms(self) -> Union[int, None]: + """Timeout period for each statement in a script.""" + return _helpers._int_or_none(self._properties.get("statementTimeoutMs")) + + @statement_timeout_ms.setter + def statement_timeout_ms(self, value: Union[int, None]): + new_value = None if value is None else str(value) + self._properties["statementTimeoutMs"] = new_value + + @property + def statement_byte_budget(self) -> Union[int, None]: + """Limit on the number of bytes billed per statement. + + Exceeding this budget results in an error. + """ + return _helpers._int_or_none(self._properties.get("statementByteBudget")) + + @statement_byte_budget.setter + def statement_byte_budget(self, value: Union[int, None]): + new_value = None if value is None else str(value) + self._properties["statementByteBudget"] = new_value + + @property + def key_result_statement(self) -> Union[KeyResultStatementKind, None]: + """Determines which statement in the script represents the "key result". + + This is used to populate the schema and query results of the script job. + Default is ``KeyResultStatementKind.LAST``. + """ + return self._properties.get("keyResultStatement") + + @key_result_statement.setter + def key_result_statement(self, value: Union[KeyResultStatementKind, None]): + self._properties["keyResultStatement"] = value + + +class QueryJobConfig(_JobConfig): + """Configuration options for query jobs. + + All properties in this class are optional. Values which are :data:`None` -> + server defaults. Set properties on the constructed configuration by using + the property name as the name of a keyword argument. + """ + + def __init__(self, **kwargs) -> None: + super(QueryJobConfig, self).__init__("query", **kwargs) + + @property + def destination_encryption_configuration(self): + """google.cloud.bigquery.encryption_configuration.EncryptionConfiguration: Custom + encryption configuration for the destination table. + + Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None` + if using default encryption. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.destination_encryption_configuration + """ + prop = self._get_sub_prop("destinationEncryptionConfiguration") + if prop is not None: + prop = EncryptionConfiguration.from_api_repr(prop) + return prop + + @destination_encryption_configuration.setter + def destination_encryption_configuration(self, value): + api_repr = value + if value is not None: + api_repr = value.to_api_repr() + self._set_sub_prop("destinationEncryptionConfiguration", api_repr) + + @property + def allow_large_results(self): + """bool: Allow large query results tables (legacy SQL, only) + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.allow_large_results + """ + return self._get_sub_prop("allowLargeResults") + + @allow_large_results.setter + def allow_large_results(self, value): + self._set_sub_prop("allowLargeResults", value) + + @property + def connection_properties(self) -> List[ConnectionProperty]: + """Connection properties. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.connection_properties + + .. versionadded:: 2.29.0 + """ + resource = self._get_sub_prop("connectionProperties", []) + return [ConnectionProperty.from_api_repr(prop) for prop in resource] + + @connection_properties.setter + def connection_properties(self, value: Iterable[ConnectionProperty]): + self._set_sub_prop( + "connectionProperties", + [prop.to_api_repr() for prop in value], + ) + + @property + def create_disposition(self): + """google.cloud.bigquery.job.CreateDisposition: Specifies behavior + for creating tables. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.create_disposition + """ + return self._get_sub_prop("createDisposition") + + @create_disposition.setter + def create_disposition(self, value): + self._set_sub_prop("createDisposition", value) + + @property + def create_session(self) -> Optional[bool]: + """[Preview] If :data:`True`, creates a new session, where + :attr:`~google.cloud.bigquery.job.QueryJob.session_info` will contain a + random server generated session id. + + If :data:`False`, runs query with an existing ``session_id`` passed in + :attr:`~google.cloud.bigquery.job.QueryJobConfig.connection_properties`, + otherwise runs query in non-session mode. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.create_session + + .. versionadded:: 2.29.0 + """ + return self._get_sub_prop("createSession") + + @create_session.setter + def create_session(self, value: Optional[bool]): + self._set_sub_prop("createSession", value) + + @property + def default_dataset(self): + """google.cloud.bigquery.dataset.DatasetReference: the default dataset + to use for unqualified table names in the query or :data:`None` if not + set. + + The ``default_dataset`` setter accepts: + + - a :class:`~google.cloud.bigquery.dataset.Dataset`, or + - a :class:`~google.cloud.bigquery.dataset.DatasetReference`, or + - a :class:`str` of the fully-qualified dataset ID in standard SQL + format. The value must included a project ID and dataset ID + separated by ``.``. For example: ``your-project.your_dataset``. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.default_dataset + """ + prop = self._get_sub_prop("defaultDataset") + if prop is not None: + prop = DatasetReference.from_api_repr(prop) + return prop + + @default_dataset.setter + def default_dataset(self, value): + if value is None: + self._set_sub_prop("defaultDataset", None) + return + + if isinstance(value, str): + value = DatasetReference.from_string(value) + + if isinstance(value, (Dataset, DatasetListItem)): + value = value.reference + + resource = value.to_api_repr() + self._set_sub_prop("defaultDataset", resource) + + @property + def destination(self): + """google.cloud.bigquery.table.TableReference: table where results are + written or :data:`None` if not set. + + The ``destination`` setter accepts: + + - a :class:`~google.cloud.bigquery.table.Table`, or + - a :class:`~google.cloud.bigquery.table.TableReference`, or + - a :class:`str` of the fully-qualified table ID in standard SQL + format. The value must included a project ID, dataset ID, and table + ID, each separated by ``.``. For example: + ``your-project.your_dataset.your_table``. + + .. note:: + + Only table ID is passed to the backend, so any configuration + in `~google.cloud.bigquery.table.Table` is discarded. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.destination_table + """ + prop = self._get_sub_prop("destinationTable") + if prop is not None: + prop = TableReference.from_api_repr(prop) + return prop + + @destination.setter + def destination(self, value): + if value is None: + self._set_sub_prop("destinationTable", None) + return + + value = _table_arg_to_table_ref(value) + resource = value.to_api_repr() + self._set_sub_prop("destinationTable", resource) + + @property + def dry_run(self): + """bool: :data:`True` if this query should be a dry run to estimate + costs. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfiguration.FIELDS.dry_run + """ + return self._properties.get("dryRun") + + @dry_run.setter + def dry_run(self, value): + self._properties["dryRun"] = value + + @property + def flatten_results(self): + """bool: Flatten nested/repeated fields in results. (Legacy SQL only) + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.flatten_results + """ + return self._get_sub_prop("flattenResults") + + @flatten_results.setter + def flatten_results(self, value): + self._set_sub_prop("flattenResults", value) + + @property + def maximum_billing_tier(self): + """int: Deprecated. Changes the billing tier to allow high-compute + queries. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.maximum_billing_tier + """ + return self._get_sub_prop("maximumBillingTier") + + @maximum_billing_tier.setter + def maximum_billing_tier(self, value): + self._set_sub_prop("maximumBillingTier", value) + + @property + def maximum_bytes_billed(self): + """int: Maximum bytes to be billed for this job or :data:`None` if not set. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.maximum_bytes_billed + """ + return _helpers._int_or_none(self._get_sub_prop("maximumBytesBilled")) + + @maximum_bytes_billed.setter + def maximum_bytes_billed(self, value): + self._set_sub_prop("maximumBytesBilled", str(value)) + + @property + def priority(self): + """google.cloud.bigquery.job.QueryPriority: Priority of the query. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.priority + """ + return self._get_sub_prop("priority") + + @priority.setter + def priority(self, value): + self._set_sub_prop("priority", value) + + @property + def query_parameters(self): + """List[Union[google.cloud.bigquery.query.ArrayQueryParameter, \ + google.cloud.bigquery.query.ScalarQueryParameter, \ + google.cloud.bigquery.query.StructQueryParameter]]: list of parameters + for parameterized query (empty by default) + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.query_parameters + """ + prop = self._get_sub_prop("queryParameters", default=[]) + return _from_api_repr_query_parameters(prop) + + @query_parameters.setter + def query_parameters(self, values): + self._set_sub_prop("queryParameters", _to_api_repr_query_parameters(values)) + + @property + def range_partitioning(self): + """Optional[google.cloud.bigquery.table.RangePartitioning]: + Configures range-based partitioning for destination table. + + .. note:: + **Beta**. The integer range partitioning feature is in a + pre-release state and might change or have limited support. + + Only specify at most one of + :attr:`~google.cloud.bigquery.job.LoadJobConfig.time_partitioning` or + :attr:`~google.cloud.bigquery.job.LoadJobConfig.range_partitioning`. + + Raises: + ValueError: + If the value is not + :class:`~google.cloud.bigquery.table.RangePartitioning` or + :data:`None`. + """ + resource = self._get_sub_prop("rangePartitioning") + if resource is not None: + return RangePartitioning(_properties=resource) + + @range_partitioning.setter + def range_partitioning(self, value): + resource = value + if isinstance(value, RangePartitioning): + resource = value._properties + elif value is not None: + raise ValueError( + "Expected value to be RangePartitioning or None, got {}.".format(value) + ) + self._set_sub_prop("rangePartitioning", resource) + + @property + def udf_resources(self): + """List[google.cloud.bigquery.query.UDFResource]: user + defined function resources (empty by default) + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.user_defined_function_resources + """ + prop = self._get_sub_prop("userDefinedFunctionResources", default=[]) + return _from_api_repr_udf_resources(prop) + + @udf_resources.setter + def udf_resources(self, values): + self._set_sub_prop( + "userDefinedFunctionResources", _to_api_repr_udf_resources(values) + ) + + @property + def use_legacy_sql(self): + """bool: Use legacy SQL syntax. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.use_legacy_sql + """ + return self._get_sub_prop("useLegacySql") + + @use_legacy_sql.setter + def use_legacy_sql(self, value): + self._set_sub_prop("useLegacySql", value) + + @property + def use_query_cache(self): + """bool: Look for the query result in the cache. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.use_query_cache + """ + return self._get_sub_prop("useQueryCache") + + @use_query_cache.setter + def use_query_cache(self, value): + self._set_sub_prop("useQueryCache", value) + + @property + def write_disposition(self): + """google.cloud.bigquery.job.WriteDisposition: Action that occurs if + the destination table already exists. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.write_disposition + """ + return self._get_sub_prop("writeDisposition") + + @write_disposition.setter + def write_disposition(self, value): + self._set_sub_prop("writeDisposition", value) + + @property + def write_incremental_results(self) -> Optional[bool]: + """This is only supported for a SELECT query using a temporary table. + + If set, the query is allowed to write results incrementally to the temporary result + table. This may incur a performance penalty. This option cannot be used with Legacy SQL. + + This feature is not generally available. + """ + return self._get_sub_prop("writeIncrementalResults") + + @write_incremental_results.setter + def write_incremental_results(self, value): + self._set_sub_prop("writeIncrementalResults", value) + + @property + def table_definitions(self): + """Dict[str, google.cloud.bigquery.external_config.ExternalConfig]: + Definitions for external tables or :data:`None` if not set. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.external_table_definitions + """ + prop = self._get_sub_prop("tableDefinitions") + if prop is not None: + prop = _from_api_repr_table_defs(prop) + return prop + + @table_definitions.setter + def table_definitions(self, values): + self._set_sub_prop("tableDefinitions", _to_api_repr_table_defs(values)) + + @property + def time_partitioning(self): + """Optional[google.cloud.bigquery.table.TimePartitioning]: Specifies + time-based partitioning for the destination table. + + Only specify at most one of + :attr:`~google.cloud.bigquery.job.LoadJobConfig.time_partitioning` or + :attr:`~google.cloud.bigquery.job.LoadJobConfig.range_partitioning`. + + Raises: + ValueError: + If the value is not + :class:`~google.cloud.bigquery.table.TimePartitioning` or + :data:`None`. + """ + prop = self._get_sub_prop("timePartitioning") + if prop is not None: + prop = TimePartitioning.from_api_repr(prop) + return prop + + @time_partitioning.setter + def time_partitioning(self, value): + api_repr = value + if value is not None: + api_repr = value.to_api_repr() + self._set_sub_prop("timePartitioning", api_repr) + + @property + def clustering_fields(self): + """Optional[List[str]]: Fields defining clustering for the table + + (Defaults to :data:`None`). + + Clustering fields are immutable after table creation. + + .. note:: + + BigQuery supports clustering for both partitioned and + non-partitioned tables. + """ + prop = self._get_sub_prop("clustering") + if prop is not None: + return list(prop.get("fields", ())) + + @clustering_fields.setter + def clustering_fields(self, value): + """Optional[List[str]]: Fields defining clustering for the table + + (Defaults to :data:`None`). + """ + if value is not None: + self._set_sub_prop("clustering", {"fields": value}) + else: + self._del_sub_prop("clustering") + + @property + def schema_update_options(self): + """List[google.cloud.bigquery.job.SchemaUpdateOption]: Specifies + updates to the destination table schema to allow as a side effect of + the query job. + """ + return self._get_sub_prop("schemaUpdateOptions") + + @schema_update_options.setter + def schema_update_options(self, values): + self._set_sub_prop("schemaUpdateOptions", values) + + @property + def script_options(self) -> ScriptOptions: + """Options controlling the execution of scripts. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#scriptoptions + """ + prop = self._get_sub_prop("scriptOptions") + if prop is not None: + prop = ScriptOptions.from_api_repr(prop) + return prop + + @script_options.setter + def script_options(self, value: Union[ScriptOptions, None]): + new_value = None if value is None else value.to_api_repr() + self._set_sub_prop("scriptOptions", new_value) + + def to_api_repr(self) -> dict: + """Build an API representation of the query job config. + + Returns: + Dict: A dictionary in the format used by the BigQuery API. + """ + resource = copy.deepcopy(self._properties) + # Query parameters have an addition property associated with them + # to indicate if the query is using named or positional parameters. + query_parameters = resource.get("query", {}).get("queryParameters") + if query_parameters: + if query_parameters[0].get("name") is None: + resource["query"]["parameterMode"] = "POSITIONAL" + else: + resource["query"]["parameterMode"] = "NAMED" + + return resource + + +class QueryJob(_AsyncJob): + """Asynchronous job: query tables. + + Args: + job_id (str): the job's ID, within the project belonging to ``client``. + + query (str): SQL query string. + + client (google.cloud.bigquery.client.Client): + A client which holds credentials and project configuration + for the dataset (which requires a project). + + job_config (Optional[google.cloud.bigquery.job.QueryJobConfig]): + Extra configuration options for the query job. + """ + + _JOB_TYPE = "query" + _UDF_KEY = "userDefinedFunctionResources" + _CONFIG_CLASS = QueryJobConfig + + def __init__(self, job_id, query, client, job_config=None): + super(QueryJob, self).__init__(job_id, client) + + if job_config is not None: + self._properties["configuration"] = job_config._properties + if self.configuration.use_legacy_sql is None: + self.configuration.use_legacy_sql = False + + if query: + _helpers._set_sub_prop( + self._properties, ["configuration", "query", "query"], query + ) + self._query_results = None + self._done_timeout = None + self._transport_timeout = None + + @property + def allow_large_results(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.allow_large_results`. + """ + return self.configuration.allow_large_results + + @property + def configuration(self) -> QueryJobConfig: + """The configuration for this query job.""" + return typing.cast(QueryJobConfig, super().configuration) + + @property + def connection_properties(self) -> List[ConnectionProperty]: + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.connection_properties`. + + .. versionadded:: 2.29.0 + """ + return self.configuration.connection_properties + + @property + def create_disposition(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.create_disposition`. + """ + return self.configuration.create_disposition + + @property + def create_session(self) -> Optional[bool]: + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.create_session`. + + .. versionadded:: 2.29.0 + """ + return self.configuration.create_session + + @property + def default_dataset(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.default_dataset`. + """ + return self.configuration.default_dataset + + @property + def destination(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.destination`. + """ + return self.configuration.destination + + @property + def destination_encryption_configuration(self): + """google.cloud.bigquery.encryption_configuration.EncryptionConfiguration: Custom + encryption configuration for the destination table. + + Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None` + if using default encryption. + + See + :attr:`google.cloud.bigquery.job.QueryJobConfig.destination_encryption_configuration`. + """ + return self.configuration.destination_encryption_configuration + + @property + def dry_run(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.dry_run`. + """ + return self.configuration.dry_run + + @property + def flatten_results(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.flatten_results`. + """ + return self.configuration.flatten_results + + @property + def priority(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.priority`. + """ + return self.configuration.priority + + @property + def search_stats(self) -> Optional[SearchStats]: + """Returns a SearchStats object.""" + + stats = self._job_statistics().get("searchStatistics") + if stats is not None: + return SearchStats.from_api_repr(stats) + return None + + @property + def query(self): + """str: The query text used in this query job. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfigurationQuery.FIELDS.query + """ + return _helpers._get_sub_prop( + self._properties, ["configuration", "query", "query"] + ) + + @property + def query_id(self) -> Optional[str]: + """[Preview] ID of a completed query. + + This ID is auto-generated and not guaranteed to be populated. + """ + query_results = self._query_results + return query_results.query_id if query_results is not None else None + + @property + def query_parameters(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.query_parameters`. + """ + return self.configuration.query_parameters + + @property + def udf_resources(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.udf_resources`. + """ + return self.configuration.udf_resources + + @property + def use_legacy_sql(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.use_legacy_sql`. + """ + return self.configuration.use_legacy_sql + + @property + def use_query_cache(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.use_query_cache`. + """ + return self.configuration.use_query_cache + + @property + def write_disposition(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.write_disposition`. + """ + return self.configuration.write_disposition + + @property + def maximum_billing_tier(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.maximum_billing_tier`. + """ + return self.configuration.maximum_billing_tier + + @property + def maximum_bytes_billed(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.maximum_bytes_billed`. + """ + return self.configuration.maximum_bytes_billed + + @property + def range_partitioning(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.range_partitioning`. + """ + return self.configuration.range_partitioning + + @property + def table_definitions(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.table_definitions`. + """ + return self.configuration.table_definitions + + @property + def time_partitioning(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.time_partitioning`. + """ + return self.configuration.time_partitioning + + @property + def clustering_fields(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.clustering_fields`. + """ + return self.configuration.clustering_fields + + @property + def schema_update_options(self): + """See + :attr:`google.cloud.bigquery.job.QueryJobConfig.schema_update_options`. + """ + return self.configuration.schema_update_options + + def to_api_repr(self): + """Generate a resource for :meth:`_begin`.""" + # Use to_api_repr to allow for some configuration properties to be set + # automatically. + configuration = self.configuration.to_api_repr() + return { + "jobReference": self._properties["jobReference"], + "configuration": configuration, + } + + @classmethod + def from_api_repr(cls, resource: dict, client: "Client") -> "QueryJob": + """Factory: construct a job given its API representation + + Args: + resource (Dict): dataset job representation returned from the API + + client (google.cloud.bigquery.client.Client): + Client which holds credentials and project + configuration for the dataset. + + Returns: + google.cloud.bigquery.job.QueryJob: Job parsed from ``resource``. + """ + job_ref_properties = resource.setdefault( + "jobReference", {"projectId": client.project, "jobId": None} + ) + job_ref = _JobReference._from_api_repr(job_ref_properties) + job = cls(job_ref, None, client=client) + job._set_properties(resource) + return job + + @property + def query_plan(self): + """Return query plan from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.query_plan + + Returns: + List[google.cloud.bigquery.job.QueryPlanEntry]: + mappings describing the query plan, or an empty list + if the query has not yet completed. + """ + plan_entries = self._job_statistics().get("queryPlan", ()) + return [QueryPlanEntry.from_api_repr(entry) for entry in plan_entries] + + @property + def schema(self) -> Optional[List[SchemaField]]: + """The schema of the results. + + Present only for successful dry run of non-legacy SQL queries. + """ + resource = self._job_statistics().get("schema") + if resource is None: + return None + fields = resource.get("fields", []) + return [SchemaField.from_api_repr(field) for field in fields] + + @property + def timeline(self): + """List(TimelineEntry): Return the query execution timeline + from job statistics. + """ + raw = self._job_statistics().get("timeline", ()) + return [TimelineEntry.from_api_repr(entry) for entry in raw] + + @property + def total_bytes_processed(self): + """Return total bytes processed from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.total_bytes_processed + + Returns: + Optional[int]: + Total bytes processed by the job, or None if job is not + yet complete. + """ + result = self._job_statistics().get("totalBytesProcessed") + if result is not None: + result = int(result) + return result + + @property + def total_bytes_billed(self): + """Return total bytes billed from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.total_bytes_billed + + Returns: + Optional[int]: + Total bytes processed by the job, or None if job is not + yet complete. + """ + result = self._job_statistics().get("totalBytesBilled") + if result is not None: + result = int(result) + return result + + @property + def billing_tier(self): + """Return billing tier from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.billing_tier + + Returns: + Optional[int]: + Billing tier used by the job, or None if job is not + yet complete. + """ + return self._job_statistics().get("billingTier") + + @property + def cache_hit(self): + """Return whether or not query results were served from cache. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.cache_hit + + Returns: + Optional[bool]: + whether the query results were returned from cache, or None + if job is not yet complete. + """ + return self._job_statistics().get("cacheHit") + + @property + def ddl_operation_performed(self): + """Optional[str]: Return the DDL operation performed. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.ddl_operation_performed + + """ + return self._job_statistics().get("ddlOperationPerformed") + + @property + def ddl_target_routine(self): + """Optional[google.cloud.bigquery.routine.RoutineReference]: Return the DDL target routine, present + for CREATE/DROP FUNCTION/PROCEDURE queries. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.ddl_target_routine + """ + prop = self._job_statistics().get("ddlTargetRoutine") + if prop is not None: + prop = RoutineReference.from_api_repr(prop) + return prop + + @property + def ddl_target_table(self): + """Optional[google.cloud.bigquery.table.TableReference]: Return the DDL target table, present + for CREATE/DROP TABLE/VIEW queries. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.ddl_target_table + """ + prop = self._job_statistics().get("ddlTargetTable") + if prop is not None: + prop = TableReference.from_api_repr(prop) + return prop + + @property + def num_dml_affected_rows(self) -> Optional[int]: + """Return the number of DML rows affected by the job. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.num_dml_affected_rows + + Returns: + Optional[int]: + number of DML rows affected by the job, or None if job is not + yet complete. + """ + result = self._job_statistics().get("numDmlAffectedRows") + if result is not None: + result = int(result) + return result + + @property + def slot_millis(self): + """Union[int, None]: Slot-milliseconds used by this query job.""" + return _helpers._int_or_none(self._job_statistics().get("totalSlotMs")) + + @property + def statement_type(self): + """Return statement type from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.statement_type + + Returns: + Optional[str]: + type of statement used by the job, or None if job is not + yet complete. + """ + return self._job_statistics().get("statementType") + + @property + def referenced_tables(self): + """Return referenced tables from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.referenced_tables + + Returns: + List[Dict]: + mappings describing the query plan, or an empty list + if the query has not yet completed. + """ + tables = [] + datasets_by_project_name = {} + + for table in self._job_statistics().get("referencedTables", ()): + t_project = table["projectId"] + + ds_id = table["datasetId"] + t_dataset = datasets_by_project_name.get((t_project, ds_id)) + if t_dataset is None: + t_dataset = DatasetReference(t_project, ds_id) + datasets_by_project_name[(t_project, ds_id)] = t_dataset + + t_name = table["tableId"] + tables.append(t_dataset.table(t_name)) + + return tables + + @property + def referenced_property_graphs(self): + """Return referenced property graphs from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.referenced_property_graphs + + Returns: + List[google.cloud.bigquery.table.PropertyGraphReference]: + mappings describing the property graphs, or an empty list + if the query has not yet completed. + """ + property_graphs = [] + + for pg in self._job_statistics().get("referencedPropertyGraphs", ()): + property_graphs.append( + PropertyGraphReference( + DatasetReference(pg["projectId"], pg["datasetId"]), + pg["propertyGraphId"], + ) + ) + + return property_graphs + + @property + def undeclared_query_parameters(self): + """Return undeclared query parameters from job statistics, if present. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.undeclared_query_parameters + + Returns: + List[Union[ \ + google.cloud.bigquery.query.ArrayQueryParameter, \ + google.cloud.bigquery.query.ScalarQueryParameter, \ + google.cloud.bigquery.query.StructQueryParameter \ + ]]: + Undeclared parameters, or an empty list if the query has + not yet completed. + """ + parameters = [] + undeclared = self._job_statistics().get("undeclaredQueryParameters", ()) + + for parameter in undeclared: + p_type = parameter["parameterType"] + + if "arrayType" in p_type: + klass = ArrayQueryParameter + elif "structTypes" in p_type: + klass = StructQueryParameter + else: + klass = ScalarQueryParameter + + parameters.append(klass.from_api_repr(parameter)) + + return parameters + + @property + def estimated_bytes_processed(self): + """Return the estimated number of bytes processed by the query. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatistics2.FIELDS.estimated_bytes_processed + + Returns: + Optional[int]: + number of DML rows affected by the job, or None if job is not + yet complete. + """ + result = self._job_statistics().get("estimatedBytesProcessed") + if result is not None: + result = int(result) + return result + + @property + def dml_stats(self) -> Optional[DmlStats]: + stats = self._job_statistics().get("dmlStats") + if stats is None: + return None + else: + return DmlStats.from_api_repr(stats) + + @property + def bi_engine_stats(self) -> Optional[BiEngineStats]: + stats = self._job_statistics().get("biEngineStatistics") + + if stats is None: + return None + else: + return BiEngineStats.from_api_repr(stats) + + @property + def incremental_result_stats(self) -> Optional[IncrementalResultStats]: + stats = self._job_statistics().get("incrementalResultStats") + if stats is None: + return None + return IncrementalResultStats.from_api_repr(stats) + + def _blocking_poll(self, timeout=None, **kwargs): + self._done_timeout = timeout + self._transport_timeout = timeout + super(QueryJob, self)._blocking_poll(timeout=timeout, **kwargs) + + @staticmethod + def _format_for_exception(message: str, query: str): + """Format a query for the output in exception message. + + Args: + message (str): The original exception message. + query (str): The SQL query to format. + + Returns: + str: A formatted query text. + """ + template = "{message}\n\n{header}\n\n{ruler}\n{body}\n{ruler}" + + lines = query.splitlines() if query is not None else [""] + max_line_len = max(len(line) for line in lines) + + header = "-----Query Job SQL Follows-----" + header = "{:^{total_width}}".format(header, total_width=max_line_len + 5) + + # Print out a "ruler" above and below the SQL so we can judge columns. + # Left pad for the line numbers (4 digits plus ":"). + ruler = " |" + " . |" * (max_line_len // 10) + + # Put line numbers next to the SQL. + body = "\n".join( + "{:4}:{}".format(n, line) for n, line in enumerate(lines, start=1) + ) + + return template.format(message=message, header=header, ruler=ruler, body=body) + + def _begin(self, client=None, retry=DEFAULT_RETRY, timeout=None): + """API call: begin the job via a POST request + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/insert + + Args: + client (Optional[google.cloud.bigquery.client.Client]): + The client to use. If not passed, falls back to the ``client`` + associated with the job object or``NoneType``. + retry (Optional[google.api_core.retry.Retry]): + How to retry the RPC. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. + + Raises: + ValueError: If the job has already begun. + """ + + try: + super(QueryJob, self)._begin(client=client, retry=retry, timeout=timeout) + except exceptions.GoogleAPICallError as exc: + exc.message = _EXCEPTION_FOOTER_TEMPLATE.format( + message=exc.message, location=self.location, job_id=self.job_id + ) + exc.debug_message = self._format_for_exception(exc.message, self.query) + exc.query_job = self + raise + + def _reload_query_results( + self, + retry: "retries.Retry" = DEFAULT_RETRY, + timeout: Optional[float] = None, + page_size: int = 0, + start_index: Optional[int] = None, + ): + """Refresh the cached query results unless already cached and complete. + + Args: + retry (Optional[google.api_core.retry.Retry]): + How to retry the call that retrieves query results. + timeout (Optional[float]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. + page_size (int): + Maximum number of rows in a single response. See maxResults in + the jobs.getQueryResults REST API. + start_index (Optional[int]): + Zero-based index of the starting row. See startIndex in the + jobs.getQueryResults REST API. + """ + # Optimization: avoid a call to jobs.getQueryResults if it's already + # been fetched, e.g. from jobs.query first page of results. + if self._query_results and self._query_results.complete: + return + + # Since the API to getQueryResults can hang up to the timeout value + # (default of 10 seconds), set the timeout parameter to ensure that + # the timeout from the futures API is respected. See: + # https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4135 + timeout_ms = None + + # Python_API_core, as part of a major rewrite of the deadline, timeout, + # retry process sets the timeout value as a Python object(). + # Our system does not natively handle that and instead expects + # either None or a numeric value. If passed a Python object, convert to + # None. + if type(self._done_timeout) is object: # pragma: NO COVER + self._done_timeout = None + + if self._done_timeout is not None: # pragma: NO COVER + # Subtract a buffer for context switching, network latency, etc. + api_timeout = self._done_timeout - _TIMEOUT_BUFFER_SECS + api_timeout = max(min(api_timeout, 10), 0) + self._done_timeout -= api_timeout + self._done_timeout = max(0, self._done_timeout) + timeout_ms = int(api_timeout * 1000) + + # If an explicit timeout is not given, fall back to the transport timeout + # stored in _blocking_poll() in the process of polling for job completion. + if timeout is not None: + transport_timeout = timeout + else: + transport_timeout = self._transport_timeout + + # Handle PollingJob._DEFAULT_VALUE. + if not isinstance(transport_timeout, (float, int)): + transport_timeout = None + + self._query_results = self._client._get_query_results( + self.job_id, + retry, + project=self.project, + timeout_ms=timeout_ms, + location=self.location, + timeout=transport_timeout, + page_size=page_size, + start_index=start_index, + ) + + def result( # type: ignore # (incompatible with supertype) + self, + page_size: Optional[int] = None, + max_results: Optional[int] = None, + retry: Optional[retries.Retry] = DEFAULT_RETRY, + timeout: Optional[Union[float, object]] = POLLING_DEFAULT_VALUE, + start_index: Optional[int] = None, + job_retry: Optional[retries.Retry] = DEFAULT_JOB_RETRY, + ) -> Union["RowIterator", _EmptyRowIterator]: + """Start the job and wait for it to complete and get the result. + + Args: + page_size (Optional[int]): + The maximum number of rows in each page of results from this + request. Non-positive values are ignored. + max_results (Optional[int]): + The maximum total number of rows from this request. + retry (Optional[google.api_core.retry.Retry]): + How to retry the call that retrieves rows. This only + applies to making RPC calls. It isn't used to retry + failed jobs. This has a reasonable default that + should only be overridden with care. If the job state + is ``DONE``, retrying is aborted early even if the + results are not available, as this will not change + anymore. + timeout (Optional[Union[float, \ + google.api_core.future.polling.PollingFuture._DEFAULT_VALUE, \ + ]]): + The number of seconds to wait for the underlying HTTP transport + before using ``retry``. If ``None``, wait indefinitely + unless an error is returned. If unset, only the + underlying API calls have their default timeouts, but we still + wait indefinitely for the job to finish. + start_index (Optional[int]): + The zero-based index of the starting row to read. + job_retry (Optional[google.api_core.retry.Retry]): + How to retry failed jobs. The default retries + rate-limit-exceeded errors. Passing ``None`` disables + job retry. + + Not all jobs can be retried. If ``job_id`` was + provided to the query that created this job, then the + job returned by the query will not be retryable, and + an exception will be raised if non-``None`` + non-default ``job_retry`` is also provided. + + Returns: + google.cloud.bigquery.table.RowIterator: + Iterator of row data + :class:`~google.cloud.bigquery.table.Row`-s. During each + page, the iterator will have the ``total_rows`` attribute + set, which counts the total number of rows **in the result + set** (this is distinct from the total number of rows in the + current page: ``iterator.page.num_items``). + + If the query is a special query that produces no results, e.g. + a DDL query, an ``_EmptyRowIterator`` instance is returned. + + Raises: + google.api_core.exceptions.GoogleAPICallError: + If the job failed and retries aren't successful. + concurrent.futures.TimeoutError: + If the job did not complete in the given timeout. + TypeError: + If Non-``None`` and non-default ``job_retry`` is + provided and the job is not retryable. + """ + # Note: Since waiting for a query job to finish is more complex than + # refreshing the job state in a loop, we avoid calling the superclass + # in this method. + + if self.dry_run: + return _EmptyRowIterator( + project=self.project, + location=self.location, + schema=self.schema, + total_bytes_processed=self.total_bytes_processed, + # Intentionally omit job_id and query_id since this doesn't + # actually correspond to a finished query job. + ) + + # Setting max_results should be equivalent to setting page_size with + # regards to allowing the user to tune how many results to download + # while we wait for the query to finish. See internal issue: + # 344008814. But if start_index is set, user is trying to access a + # specific page, so we don't need to set page_size. See issue #1950. + if page_size is None and max_results is not None and start_index is None: + page_size = max_results + + # When timeout has default sentinel value ``object()``, do not pass + # anything to invoke default timeouts in subsequent calls. + done_kwargs: Dict[str, Union[_helpers.TimeoutType, object]] = {} + reload_query_results_kwargs: Dict[str, Union[_helpers.TimeoutType, object]] = {} + list_rows_kwargs: Dict[str, Union[_helpers.TimeoutType, object]] = {} + if type(timeout) is not object: + done_kwargs["timeout"] = timeout + list_rows_kwargs["timeout"] = timeout + reload_query_results_kwargs["timeout"] = timeout + + if page_size is not None: + reload_query_results_kwargs["page_size"] = page_size + + if start_index is not None: + reload_query_results_kwargs["start_index"] = start_index + + try: + retry_do_query = getattr(self, "_retry_do_query", None) + if retry_do_query is not None: + if job_retry is DEFAULT_JOB_RETRY: + job_retry = self._job_retry # type: ignore + else: + if job_retry is not None and job_retry is not DEFAULT_JOB_RETRY: + raise TypeError( + "`job_retry` was provided, but this job is" + " not retryable, because a custom `job_id` was" + " provided to the query that created this job." + ) + + restart_query_job = False + + def is_job_done(): + nonlocal restart_query_job + + if restart_query_job: + restart_query_job = False + + # The original job has failed. Create a new one. + # + # Note that we won't get here if retry_do_query is + # None, because we won't use a retry. + job = retry_do_query() + + # Become the new job: + self.__dict__.clear() + self.__dict__.update(job.__dict__) + + # It's possible the job fails again and we'll have to + # retry that too. + self._retry_do_query = retry_do_query + self._job_retry = job_retry + + # If the job hasn't been created, create it now. Related: + # https://github.com/googleapis/python-bigquery/issues/1940 + if self.state is None: + self._begin(retry=retry, **done_kwargs) + + # Refresh the job status with jobs.get because some of the + # exceptions thrown by jobs.getQueryResults like timeout and + # rateLimitExceeded errors are ambiguous. We want to know if + # the query job failed and not just the call to + # jobs.getQueryResults. + if self.done(retry=retry, **done_kwargs): + # If it's already failed, we might as well stop. + job_failed_exception = self.exception() + if job_failed_exception is not None: + # Only try to restart the query job if the job failed for + # a retriable reason. For example, don't restart the query + # if the call to reload the job metadata within self.done() + # timed out. + # + # The `restart_query_job` must only be called after a + # successful call to the `jobs.get` REST API and we + # determine that the job has failed. + # + # The `jobs.get` REST API + # (https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get) + # is called via `self.done()` which calls + # `self.reload()`. + # + # To determine if the job failed, the `self.exception()` + # is set from `self.reload()` via + # `self._set_properties()`, which translates the + # `Job.status.errorResult` field + # (https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobStatus.FIELDS.error_result) + # into an exception that can be processed by the + # `job_retry` predicate. + restart_query_job = True + raise job_failed_exception + else: + # Make sure that the _query_results are cached so we + # can return a complete RowIterator. + # + # Note: As an optimization, _reload_query_results + # doesn't make any API calls if the query results are + # already cached and have jobComplete=True in the + # response from the REST API. This ensures we aren't + # making any extra API calls if the previous loop + # iteration fetched the finished job. + self._reload_query_results( + retry=retry, **reload_query_results_kwargs + ) + return True + + # Call jobs.getQueryResults with max results set to 0 just to + # wait for the query to finish. Unlike most methods, + # jobs.getQueryResults hangs as long as it can to ensure we + # know when the query has finished as soon as possible. + self._reload_query_results(retry=retry, **reload_query_results_kwargs) + + # Even if the query is finished now according to + # jobs.getQueryResults, we'll want to reload the job status if + # it's not already DONE. + return False + + if retry_do_query is not None and job_retry is not None: + is_job_done = job_retry(is_job_done) + + # timeout can be a number of seconds, `None`, or a + # `google.api_core.future.polling.PollingFuture._DEFAULT_VALUE` + # sentinel object indicating a default timeout if we choose to add + # one some day. This value can come from our PollingFuture + # superclass and was introduced in + # https://github.com/googleapis/python-api-core/pull/462. + if isinstance(timeout, (float, int)): + remaining_timeout = timeout + else: + # Note: we may need to handle _DEFAULT_VALUE as a separate + # case someday, but even then the best we can do for queries + # is 72+ hours for hyperparameter tuning jobs: + # https://cloud.google.com/bigquery/quotas#query_jobs + # + # The timeout for a multi-statement query is 24+ hours. See: + # https://cloud.google.com/bigquery/quotas#multi_statement_query_limits + remaining_timeout = None + + if remaining_timeout is None: + # Since is_job_done() calls jobs.getQueryResults, which is a + # long-running API, don't delay the next request at all. + while not is_job_done(): + pass + else: + # Use a monotonic clock since we don't actually care about + # daylight savings or similar, just the elapsed time. + previous_time = time.monotonic() + + while not is_job_done(): + current_time = time.monotonic() + elapsed_time = current_time - previous_time + remaining_timeout = remaining_timeout - elapsed_time + previous_time = current_time + + if remaining_timeout < 0: + raise concurrent.futures.TimeoutError() + + except exceptions.GoogleAPICallError as exc: + exc.message = _EXCEPTION_FOOTER_TEMPLATE.format( + message=exc.message, location=self.location, job_id=self.job_id + ) + exc.debug_message = self._format_for_exception(exc.message, self.query) # type: ignore + exc.query_job = self # type: ignore + raise + except requests.exceptions.Timeout as exc: + raise concurrent.futures.TimeoutError from exc + + # If the query job is complete but there are no query results, this was + # special job, such as a DDL query. Return an empty result set to + # indicate success and avoid calling tabledata.list on a table which + # can't be read (such as a view table). + if self._query_results.total_rows is None: + return _EmptyRowIterator( + location=self.location, + project=self.project, + job_id=self.job_id, + query_id=self.query_id, + schema=self.schema, + num_dml_affected_rows=self._query_results.num_dml_affected_rows, + query=self.query, + total_bytes_processed=self.total_bytes_processed, + slot_millis=self.slot_millis, + ) + + # We know that there's at least 1 row, so only treat the response from + # jobs.getQueryResults / jobs.query as the first page of the + # RowIterator response if there are any rows in it. This prevents us + # from stopping the iteration early in the cases where we set + # maxResults=0. In that case, we're missing rows and there's no next + # page token. + first_page_response = self._query_results._properties + if "rows" not in first_page_response: + first_page_response = None + + rows = self._client._list_rows_from_query_results( + self.job_id, + self.location, + self.project, + self._query_results.schema, + total_rows=self._query_results.total_rows, + destination=self.destination, + page_size=page_size, + max_results=max_results, + start_index=start_index, + retry=retry, + query_id=self.query_id, + first_page_response=first_page_response, + num_dml_affected_rows=self._query_results.num_dml_affected_rows, + query=self.query, + total_bytes_processed=self.total_bytes_processed, + slot_millis=self.slot_millis, + created=self.created, + started=self.started, + ended=self.ended, + **list_rows_kwargs, + ) + rows._preserve_order = _contains_order_by(self.query) + return rows + + # If changing the signature of this method, make sure to apply the same + # changes to table.RowIterator.to_arrow(), except for the max_results parameter + # that should only exist here in the QueryJob method. + def to_arrow( + self, + progress_bar_type: Optional[str] = None, + bqstorage_client: Optional["bigquery_storage.BigQueryReadClient"] = None, + create_bqstorage_client: bool = True, + max_results: Optional[int] = None, + timeout: Optional[float] = None, + ) -> "pyarrow.Table": + """[Beta] Create a class:`pyarrow.Table` by loading all pages of a + table or query. + + Args: + progress_bar_type (Optional[str]): + If set, use the `tqdm `_ library to + display a progress bar while the data downloads. Install the + ``tqdm`` package to use this feature. + + Possible values of ``progress_bar_type`` include: + + ``None`` + No progress bar. + ``'tqdm'`` + Use the :func:`tqdm.tqdm` function to print a progress bar + to :data:`sys.stdout`. + ``'tqdm_notebook'`` + Use the :func:`tqdm.notebook.tqdm` function to display a + progress bar as a Jupyter notebook widget. + ``'tqdm_gui'`` + Use the :func:`tqdm.tqdm_gui` function to display a + progress bar as a graphical dialog box. + bqstorage_client (Optional[google.cloud.bigquery_storage_v1.BigQueryReadClient]): + A BigQuery Storage API client. If supplied, use the faster + BigQuery Storage API to fetch rows from BigQuery. This API + is a billable API. + + This method requires ``google-cloud-bigquery-storage`` library. + + Reading from a specific partition or snapshot is not + currently supported by this method. + create_bqstorage_client (Optional[bool]): + If ``True`` (default), create a BigQuery Storage API client + using the default API settings. The BigQuery Storage API + is a faster way to fetch rows from BigQuery. See the + ``bqstorage_client`` parameter for more information. + + This argument does nothing if ``bqstorage_client`` is supplied. + + .. versionadded:: 1.24.0 + + max_results (Optional[int]): + Maximum number of rows to include in the result. No limit by default. + + .. versionadded:: 2.21.0 + + timeout (Optional[float]): + The number of seconds to wait for the underlying download to complete. + If ``None``, wait indefinitely. + + Returns: + pyarrow.Table + A :class:`pyarrow.Table` populated with row data and column + headers from the query results. The column headers are derived + from the destination table's schema. + + Raises: + ValueError: + If the :mod:`pyarrow` library cannot be imported. + + .. versionadded:: 1.17.0 + """ + query_result = wait_for_query(self, progress_bar_type, max_results=max_results) + return query_result.to_arrow( + progress_bar_type=progress_bar_type, + bqstorage_client=bqstorage_client, + create_bqstorage_client=create_bqstorage_client, + timeout=timeout, + ) + + # If changing the signature of this method, make sure to apply the same + # changes to table.RowIterator.to_dataframe(), except for the max_results parameter + # that should only exist here in the QueryJob method. + def to_dataframe( + self, + bqstorage_client: Optional["bigquery_storage.BigQueryReadClient"] = None, + dtypes: Optional[Dict[str, Any]] = None, + progress_bar_type: Optional[str] = None, + create_bqstorage_client: bool = True, + max_results: Optional[int] = None, + geography_as_object: bool = False, + bool_dtype: Union[Any, None] = DefaultPandasDTypes.BOOL_DTYPE, + int_dtype: Union[Any, None] = DefaultPandasDTypes.INT_DTYPE, + float_dtype: Union[Any, None] = None, + string_dtype: Union[Any, None] = None, + date_dtype: Union[Any, None] = DefaultPandasDTypes.DATE_DTYPE, + datetime_dtype: Union[Any, None] = None, + time_dtype: Union[Any, None] = DefaultPandasDTypes.TIME_DTYPE, + timestamp_dtype: Union[Any, None] = None, + range_date_dtype: Union[Any, None] = DefaultPandasDTypes.RANGE_DATE_DTYPE, + range_datetime_dtype: Union[ + Any, None + ] = DefaultPandasDTypes.RANGE_DATETIME_DTYPE, + range_timestamp_dtype: Union[ + Any, None + ] = DefaultPandasDTypes.RANGE_TIMESTAMP_DTYPE, + timeout: Optional[float] = None, + ) -> "pandas.DataFrame": + """Return a pandas DataFrame from a QueryJob + + Args: + bqstorage_client (Optional[google.cloud.bigquery_storage_v1.BigQueryReadClient]): + A BigQuery Storage API client. If supplied, use the faster + BigQuery Storage API to fetch rows from BigQuery. This + API is a billable API. + + This method requires the ``fastavro`` and + ``google-cloud-bigquery-storage`` libraries. + + Reading from a specific partition or snapshot is not + currently supported by this method. + + dtypes (Optional[Map[str, Union[str, pandas.Series.dtype]]]): + A dictionary of column names pandas ``dtype``s. The provided + ``dtype`` is used when constructing the series for the column + specified. Otherwise, the default pandas behavior is used. + + progress_bar_type (Optional[str]): + If set, use the `tqdm `_ library to + display a progress bar while the data downloads. Install the + ``tqdm`` package to use this feature. + + See + :func:`~google.cloud.bigquery.table.RowIterator.to_dataframe` + for details. + + .. versionadded:: 1.11.0 + create_bqstorage_client (Optional[bool]): + If ``True`` (default), create a BigQuery Storage API client + using the default API settings. The BigQuery Storage API + is a faster way to fetch rows from BigQuery. See the + ``bqstorage_client`` parameter for more information. + + This argument does nothing if ``bqstorage_client`` is supplied. + + .. versionadded:: 1.24.0 + + max_results (Optional[int]): + Maximum number of rows to include in the result. No limit by default. + + .. versionadded:: 2.21.0 + + geography_as_object (Optional[bool]): + If ``True``, convert GEOGRAPHY data to :mod:`shapely` + geometry objects. If ``False`` (default), don't cast + geography data to :mod:`shapely` geometry objects. + + .. versionadded:: 2.24.0 + + bool_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.BooleanDtype()``) + to convert BigQuery Boolean type, instead of relying on the default + ``pandas.BooleanDtype()``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("bool")``. BigQuery Boolean + type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#boolean_type + + .. versionadded:: 3.8.0 + + int_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.Int64Dtype()``) + to convert BigQuery Integer types, instead of relying on the default + ``pandas.Int64Dtype()``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("int64")``. A list of BigQuery + Integer types can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#integer_types + + .. versionadded:: 3.8.0 + + float_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.Float32Dtype()``) + to convert BigQuery Float type, instead of relying on the default + ``numpy.dtype("float64")``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("float64")``. BigQuery Float + type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#floating_point_types + + .. versionadded:: 3.8.0 + + string_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.StringDtype()``) to + convert BigQuery String type, instead of relying on the default + ``numpy.dtype("object")``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("object")``. BigQuery String + type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#string_type + + .. versionadded:: 3.8.0 + + date_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. + ``pandas.ArrowDtype(pyarrow.date32())``) to convert BigQuery Date + type, instead of relying on the default ``db_dtypes.DateDtype()``. + If you explicitly set the value to ``None``, then the data type will be + ``numpy.dtype("datetime64[ns]")`` or ``object`` if out of bound. BigQuery + Date type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#date_type + + .. versionadded:: 3.10.0 + + datetime_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. + ``pandas.ArrowDtype(pyarrow.timestamp("us"))``) to convert BigQuery Datetime + type, instead of relying on the default ``numpy.dtype("datetime64[ns]``. + If you explicitly set the value to ``None``, then the data type will be + ``numpy.dtype("datetime64[ns]")`` or ``object`` if out of bound. BigQuery + Datetime type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#datetime_type + + .. versionadded:: 3.10.0 + + time_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. + ``pandas.ArrowDtype(pyarrow.time64("us"))``) to convert BigQuery Time + type, instead of relying on the default ``db_dtypes.TimeDtype()``. + If you explicitly set the value to ``None``, then the data type will be + ``numpy.dtype("object")``. BigQuery Time type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#time_type + + .. versionadded:: 3.10.0 + + timestamp_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. + ``pandas.ArrowDtype(pyarrow.timestamp("us", tz="UTC"))``) to convert BigQuery Timestamp + type, instead of relying on the default ``numpy.dtype("datetime64[ns, UTC]")``. + If you explicitly set the value to ``None``, then the data type will be + ``numpy.dtype("datetime64[ns, UTC]")`` or ``object`` if out of bound. BigQuery + Datetime type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#timestamp_type + + .. versionadded:: 3.10.0 + + range_date_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype, such as: + + .. code-block:: python + + pandas.ArrowDtype(pyarrow.struct( + [("start", pyarrow.date32()), ("end", pyarrow.date32())] + )) + + to convert BigQuery RANGE type, instead of relying on + the default ``object``. If you explicitly set the value to + ``None``, the data type will be ``object``. BigQuery Range type + can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#range_type + + .. versionadded:: 3.21.0 + + range_datetime_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype, such as: + + .. code-block:: python + + pandas.ArrowDtype(pyarrow.struct( + [ + ("start", pyarrow.timestamp("us")), + ("end", pyarrow.timestamp("us")), + ] + )) + + to convert BigQuery RANGE type, instead of relying on + the default ``object``. If you explicitly set the value to + ``None``, the data type will be ``object``. BigQuery Range type + can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#range_type + + .. versionadded:: 3.21.0 + + range_timestamp_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype, such as: + + .. code-block:: python + + pandas.ArrowDtype(pyarrow.struct( + [ + ("start", pyarrow.timestamp("us", tz="UTC")), + ("end", pyarrow.timestamp("us", tz="UTC")), + ] + )) + + to convert BigQuery RANGE type, instead of relying + on the default ``object``. If you explicitly set the value to + ``None``, the data type will be ``object``. BigQuery Range type + can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#range_type + + .. versionadded:: 3.21.0 + + timeout (Optional[float]): + The number of seconds to wait for the underlying download to complete. + If ``None``, wait indefinitely. + + Returns: + pandas.DataFrame: + A :class:`~pandas.DataFrame` populated with row data + and column headers from the query results. The column + headers are derived from the destination table's + schema. + + Raises: + ValueError: + If the :mod:`pandas` library cannot be imported, or + the :mod:`google.cloud.bigquery_storage_v1` module is + required but cannot be imported. Also if + `geography_as_object` is `True`, but the + :mod:`shapely` library cannot be imported. + """ + query_result = wait_for_query(self, progress_bar_type, max_results=max_results) + return query_result.to_dataframe( + bqstorage_client=bqstorage_client, + dtypes=dtypes, + progress_bar_type=progress_bar_type, + create_bqstorage_client=create_bqstorage_client, + geography_as_object=geography_as_object, + bool_dtype=bool_dtype, + int_dtype=int_dtype, + float_dtype=float_dtype, + string_dtype=string_dtype, + date_dtype=date_dtype, + datetime_dtype=datetime_dtype, + time_dtype=time_dtype, + timestamp_dtype=timestamp_dtype, + range_date_dtype=range_date_dtype, + range_datetime_dtype=range_datetime_dtype, + range_timestamp_dtype=range_timestamp_dtype, + timeout=timeout, + ) + + # If changing the signature of this method, make sure to apply the same + # changes to table.RowIterator.to_dataframe(), except for the max_results parameter + # that should only exist here in the QueryJob method. + def to_geodataframe( + self, + bqstorage_client: Optional["bigquery_storage.BigQueryReadClient"] = None, + dtypes: Optional[Dict[str, Any]] = None, + progress_bar_type: Optional[str] = None, + create_bqstorage_client: bool = True, + max_results: Optional[int] = None, + geography_column: Optional[str] = None, + bool_dtype: Union[Any, None] = DefaultPandasDTypes.BOOL_DTYPE, + int_dtype: Union[Any, None] = DefaultPandasDTypes.INT_DTYPE, + float_dtype: Union[Any, None] = None, + string_dtype: Union[Any, None] = None, + timeout: Optional[float] = None, + ) -> "geopandas.GeoDataFrame": + """Return a GeoPandas GeoDataFrame from a QueryJob + + Args: + bqstorage_client (Optional[google.cloud.bigquery_storage_v1.BigQueryReadClient]): + A BigQuery Storage API client. If supplied, use the faster + BigQuery Storage API to fetch rows from BigQuery. This + API is a billable API. + + This method requires the ``fastavro`` and + ``google-cloud-bigquery-storage`` libraries. + + Reading from a specific partition or snapshot is not + currently supported by this method. + + dtypes (Optional[Map[str, Union[str, pandas.Series.dtype]]]): + A dictionary of column names pandas ``dtype``s. The provided + ``dtype`` is used when constructing the series for the column + specified. Otherwise, the default pandas behavior is used. + + progress_bar_type (Optional[str]): + If set, use the `tqdm `_ library to + display a progress bar while the data downloads. Install the + ``tqdm`` package to use this feature. + + See + :func:`~google.cloud.bigquery.table.RowIterator.to_dataframe` + for details. + + .. versionadded:: 1.11.0 + create_bqstorage_client (Optional[bool]): + If ``True`` (default), create a BigQuery Storage API client + using the default API settings. The BigQuery Storage API + is a faster way to fetch rows from BigQuery. See the + ``bqstorage_client`` parameter for more information. + + This argument does nothing if ``bqstorage_client`` is supplied. + + .. versionadded:: 1.24.0 + + max_results (Optional[int]): + Maximum number of rows to include in the result. No limit by default. + + .. versionadded:: 2.21.0 + + geography_column (Optional[str]): + If there are more than one GEOGRAPHY column, + identifies which one to use to construct a GeoPandas + GeoDataFrame. This option can be ommitted if there's + only one GEOGRAPHY column. + bool_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.BooleanDtype()``) + to convert BigQuery Boolean type, instead of relying on the default + ``pandas.BooleanDtype()``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("bool")``. BigQuery Boolean + type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#boolean_type + int_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.Int64Dtype()``) + to convert BigQuery Integer types, instead of relying on the default + ``pandas.Int64Dtype()``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("int64")``. A list of BigQuery + Integer types can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#integer_types + float_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.Float32Dtype()``) + to convert BigQuery Float type, instead of relying on the default + ``numpy.dtype("float64")``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("float64")``. BigQuery Float + type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#floating_point_types + string_dtype (Optional[pandas.Series.dtype, None]): + If set, indicate a pandas ExtensionDtype (e.g. ``pandas.StringDtype()``) to + convert BigQuery String type, instead of relying on the default + ``numpy.dtype("object")``. If you explicitly set the value to ``None``, + then the data type will be ``numpy.dtype("object")``. BigQuery String + type can be found at: + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#string_type + timeout (Optional[float]): + The number of seconds to wait for the underlying download to complete. + If ``None``, wait indefinitely. + + Returns: + geopandas.GeoDataFrame: + A :class:`geopandas.GeoDataFrame` populated with row + data and column headers from the query results. The + column headers are derived from the destination + table's schema. + + Raises: + ValueError: + If the :mod:`geopandas` library cannot be imported, or the + :mod:`google.cloud.bigquery_storage_v1` module is + required but cannot be imported. + + .. versionadded:: 2.24.0 + """ + query_result = wait_for_query(self, progress_bar_type, max_results=max_results) + return query_result.to_geodataframe( + bqstorage_client=bqstorage_client, + dtypes=dtypes, + progress_bar_type=progress_bar_type, + create_bqstorage_client=create_bqstorage_client, + geography_column=geography_column, + bool_dtype=bool_dtype, + int_dtype=int_dtype, + float_dtype=float_dtype, + string_dtype=string_dtype, + timeout=timeout, + ) + + def __iter__(self): + return iter(self.result()) + + +class QueryPlanEntryStep(object): + """Map a single step in a query plan entry. + + Args: + kind (str): step type. + substeps (List): names of substeps. + """ + + def __init__(self, kind, substeps): + self.kind = kind + self.substeps = list(substeps) + + @classmethod + def from_api_repr(cls, resource: dict) -> "QueryPlanEntryStep": + """Factory: construct instance from the JSON repr. + + Args: + resource (Dict): JSON representation of the entry. + + Returns: + google.cloud.bigquery.job.QueryPlanEntryStep: + New instance built from the resource. + """ + return cls(kind=resource.get("kind"), substeps=resource.get("substeps", ())) + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return NotImplemented + return self.kind == other.kind and self.substeps == other.substeps + + +class QueryPlanEntry(object): + """QueryPlanEntry represents a single stage of a query execution plan. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#ExplainQueryStage + for the underlying API representation within query statistics. + """ + + def __init__(self): + self._properties = {} + + @classmethod + def from_api_repr(cls, resource: dict) -> "QueryPlanEntry": + """Factory: construct instance from the JSON repr. + + Args: + resource(Dict[str: object]): + ExplainQueryStage representation returned from API. + + Returns: + google.cloud.bigquery.job.QueryPlanEntry: + Query plan entry parsed from ``resource``. + """ + entry = cls() + entry._properties = resource + return entry + + @property + def name(self): + """Optional[str]: Human-readable name of the stage.""" + return self._properties.get("name") + + @property + def entry_id(self): + """Optional[str]: Unique ID for the stage within the plan.""" + return self._properties.get("id") + + @property + def start(self): + """Optional[Datetime]: Datetime when the stage started.""" + if self._properties.get("startMs") is None: + return None + return _helpers._datetime_from_microseconds( + int(self._properties.get("startMs")) * 1000.0 + ) + + @property + def end(self): + """Optional[Datetime]: Datetime when the stage ended.""" + if self._properties.get("endMs") is None: + return None + return _helpers._datetime_from_microseconds( + int(self._properties.get("endMs")) * 1000.0 + ) + + @property + def input_stages(self): + """List(int): Entry IDs for stages that were inputs for this stage.""" + if self._properties.get("inputStages") is None: + return [] + return [ + _helpers._int_or_none(entry) + for entry in self._properties.get("inputStages") + ] + + @property + def parallel_inputs(self): + """Optional[int]: Number of parallel input segments within + the stage. + """ + return _helpers._int_or_none(self._properties.get("parallelInputs")) + + @property + def completed_parallel_inputs(self): + """Optional[int]: Number of parallel input segments completed.""" + return _helpers._int_or_none(self._properties.get("completedParallelInputs")) + + @property + def wait_ms_avg(self): + """Optional[int]: Milliseconds the average worker spent waiting to + be scheduled. + """ + return _helpers._int_or_none(self._properties.get("waitMsAvg")) + + @property + def wait_ms_max(self): + """Optional[int]: Milliseconds the slowest worker spent waiting to + be scheduled. + """ + return _helpers._int_or_none(self._properties.get("waitMsMax")) + + @property + def wait_ratio_avg(self): + """Optional[float]: Ratio of time the average worker spent waiting + to be scheduled, relative to the longest time spent by any worker in + any stage of the overall plan. + """ + return self._properties.get("waitRatioAvg") + + @property + def wait_ratio_max(self): + """Optional[float]: Ratio of time the slowest worker spent waiting + to be scheduled, relative to the longest time spent by any worker in + any stage of the overall plan. + """ + return self._properties.get("waitRatioMax") + + @property + def read_ms_avg(self): + """Optional[int]: Milliseconds the average worker spent reading + input. + """ + return _helpers._int_or_none(self._properties.get("readMsAvg")) + + @property + def read_ms_max(self): + """Optional[int]: Milliseconds the slowest worker spent reading + input. + """ + return _helpers._int_or_none(self._properties.get("readMsMax")) + + @property + def read_ratio_avg(self): + """Optional[float]: Ratio of time the average worker spent reading + input, relative to the longest time spent by any worker in any stage + of the overall plan. + """ + return self._properties.get("readRatioAvg") + + @property + def read_ratio_max(self): + """Optional[float]: Ratio of time the slowest worker spent reading + to be scheduled, relative to the longest time spent by any worker in + any stage of the overall plan. + """ + return self._properties.get("readRatioMax") + + @property + def compute_ms_avg(self): + """Optional[int]: Milliseconds the average worker spent on CPU-bound + processing. + """ + return _helpers._int_or_none(self._properties.get("computeMsAvg")) + + @property + def compute_ms_max(self): + """Optional[int]: Milliseconds the slowest worker spent on CPU-bound + processing. + """ + return _helpers._int_or_none(self._properties.get("computeMsMax")) + + @property + def compute_ratio_avg(self): + """Optional[float]: Ratio of time the average worker spent on + CPU-bound processing, relative to the longest time spent by any + worker in any stage of the overall plan. + """ + return self._properties.get("computeRatioAvg") + + @property + def compute_ratio_max(self): + """Optional[float]: Ratio of time the slowest worker spent on + CPU-bound processing, relative to the longest time spent by any + worker in any stage of the overall plan. + """ + return self._properties.get("computeRatioMax") + + @property + def write_ms_avg(self): + """Optional[int]: Milliseconds the average worker spent writing + output data. + """ + return _helpers._int_or_none(self._properties.get("writeMsAvg")) + + @property + def write_ms_max(self): + """Optional[int]: Milliseconds the slowest worker spent writing + output data. + """ + return _helpers._int_or_none(self._properties.get("writeMsMax")) + + @property + def write_ratio_avg(self): + """Optional[float]: Ratio of time the average worker spent writing + output data, relative to the longest time spent by any worker in any + stage of the overall plan. + """ + return self._properties.get("writeRatioAvg") + + @property + def write_ratio_max(self): + """Optional[float]: Ratio of time the slowest worker spent writing + output data, relative to the longest time spent by any worker in any + stage of the overall plan. + """ + return self._properties.get("writeRatioMax") + + @property + def records_read(self): + """Optional[int]: Number of records read by this stage.""" + return _helpers._int_or_none(self._properties.get("recordsRead")) + + @property + def records_written(self): + """Optional[int]: Number of records written by this stage.""" + return _helpers._int_or_none(self._properties.get("recordsWritten")) + + @property + def status(self): + """Optional[str]: status of this stage.""" + return self._properties.get("status") + + @property + def shuffle_output_bytes(self): + """Optional[int]: Number of bytes written by this stage to + intermediate shuffle. + """ + return _helpers._int_or_none(self._properties.get("shuffleOutputBytes")) + + @property + def shuffle_output_bytes_spilled(self): + """Optional[int]: Number of bytes written by this stage to + intermediate shuffle and spilled to disk. + """ + return _helpers._int_or_none(self._properties.get("shuffleOutputBytesSpilled")) + + @property + def steps(self): + """List(QueryPlanEntryStep): List of step operations performed by + each worker in the stage. + """ + return [ + QueryPlanEntryStep.from_api_repr(step) + for step in self._properties.get("steps", []) + ] + + @property + def slot_ms(self): + """Optional[int]: Slot-milliseconds used by the stage.""" + return _helpers._int_or_none(self._properties.get("slotMs")) + + +class TimelineEntry(object): + """TimelineEntry represents progress of a query job at a particular + point in time. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#querytimelinesample + for the underlying API representation within query statistics. + """ + + def __init__(self): + self._properties = {} + + @classmethod + def from_api_repr(cls, resource): + """Factory: construct instance from the JSON repr. + + Args: + resource(Dict[str: object]): + QueryTimelineSample representation returned from API. + + Returns: + google.cloud.bigquery.TimelineEntry: + Timeline sample parsed from ``resource``. + """ + entry = cls() + entry._properties = resource + return entry + + @property + def elapsed_ms(self): + """Optional[int]: Milliseconds elapsed since start of query + execution.""" + return _helpers._int_or_none(self._properties.get("elapsedMs")) + + @property + def active_units(self): + """Optional[int]: Current number of input units being processed + by workers, reported as largest value since the last sample.""" + return _helpers._int_or_none(self._properties.get("activeUnits")) + + @property + def pending_units(self): + """Optional[int]: Current number of input units remaining for + query stages active at this sample time.""" + return _helpers._int_or_none(self._properties.get("pendingUnits")) + + @property + def completed_units(self): + """Optional[int]: Current number of input units completed by + this query.""" + return _helpers._int_or_none(self._properties.get("completedUnits")) + + @property + def slot_millis(self): + """Optional[int]: Cumulative slot-milliseconds consumed by + this query.""" + return _helpers._int_or_none(self._properties.get("totalSlotMs")) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d228a35bb1348e38a26ef5489ac099f66c1f6992 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__init__.py @@ -0,0 +1,20 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from google.cloud.bigquery.magics.magics import context + + +# For backwards compatibility we need to make the context available in the path +# google.cloud.bigquery.magics.context +__all__ = ("context",) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce92cd9c50e177e8d6e2e5f64d3dd92750c3b043 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__pycache__/magics.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__pycache__/magics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fedc19286c528f0af5c5dd29538f0666ddd38326 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/__pycache__/magics.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9471446c516be47ea1593b01b76306c48f62d9b7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__init__.py @@ -0,0 +1,34 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from google.cloud.bigquery.magics.line_arg_parser.exceptions import ParseError +from google.cloud.bigquery.magics.line_arg_parser.exceptions import ( + DuplicateQueryParamsError, + QueryParamsParseError, +) +from google.cloud.bigquery.magics.line_arg_parser.lexer import Lexer +from google.cloud.bigquery.magics.line_arg_parser.lexer import TokenType +from google.cloud.bigquery.magics.line_arg_parser.parser import Parser +from google.cloud.bigquery.magics.line_arg_parser.visitors import QueryParamsExtractor + + +__all__ = ( + "DuplicateQueryParamsError", + "Lexer", + "Parser", + "ParseError", + "QueryParamsExtractor", + "QueryParamsParseError", + "TokenType", +) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baa0eac19a39140cba75075c2073fcd135313497 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8c507fbbf109a978f0d8a0d7832bffac2d02cb7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/exceptions.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/lexer.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/lexer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3e5bac845446f30cc5cff3ac1f8bf41fcebac5b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/lexer.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/parser.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce6ba3247076eb7b0a359d5e902800cb0e3d5c54 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/parser.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/visitors.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/visitors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a867ebef73502c42d5d5566dd7ba1378cf42cfff Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/__pycache__/visitors.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/exceptions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..6b2081186cab1f14069fbe32afbdee7a6bb21219 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/exceptions.py @@ -0,0 +1,25 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +class ParseError(Exception): + pass + + +class QueryParamsParseError(ParseError): + """Raised when --params option is syntactically incorrect.""" + + +class DuplicateQueryParamsError(ParseError): + pass diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/lexer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..71b287d01e83e43b97884538999e5b497d23622b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/lexer.py @@ -0,0 +1,200 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import namedtuple +from collections import OrderedDict +import itertools +import re + +import enum + + +Token = namedtuple("Token", ("type_", "lexeme", "pos")) +StateTransition = namedtuple("StateTransition", ("new_state", "total_offset")) + +# Pattern matching is done with regexes, and the order in which the token patterns are +# defined is important. +# +# Suppose we had the following token definitions: +# * INT - a token matching integers, +# * FLOAT - a token matching floating point numbers, +# * DOT - a token matching a single literal dot character, i.e. "." +# +# The FLOAT token would have to be defined first, since we would want the input "1.23" +# to be tokenized as a single FLOAT token, and *not* three tokens (INT, DOT, INT). +# +# Sometimes, however, different tokens match too similar patterns, and it is not +# possible to define them in order that would avoid any ambiguity. One such case are +# the OPT_VAL and PY_NUMBER tokens, as both can match an integer literal, say "42". +# +# In order to avoid the dilemmas, the lexer implements a concept of STATES. States are +# used to split token definitions into subgroups, and in each lexer state only a single +# subgroup is used for tokenizing the input. Lexer states can therefore be though of as +# token namespaces. +# +# For example, while parsing the value of the "--params" option, we do not want to +# "recognize" it as a single OPT_VAL token, but instead want to parse it as a Python +# dictionary and verify its syntactial correctness. On the other hand, while parsing +# the value of an option other than "--params", we do not really care about its +# structure, and thus do not want to use any of the "Python tokens" for pattern matching. +# +# Token definition order is important, thus an OrderedDict is used. In addition, PEP 468 +# guarantees us that the order of kwargs is preserved in Python 3.6+. +token_types = OrderedDict( + state_parse_pos_args=OrderedDict( + GOTO_PARSE_NON_PARAMS_OPTIONS=r"(?P(?=--))", # double dash - starting the options list + DEST_VAR=r"(?P[^\d\W]\w*)", # essentially a Python ID + ), + state_parse_non_params_options=OrderedDict( + GOTO_PARSE_PARAMS_OPTION=r"(?P(?=--params(?:\s|=|--|$)))", # the --params option + OPTION_SPEC=r"(?P--\w+)", + OPTION_EQ=r"(?P=)", + OPT_VAL=r"(?P\S+?(?=\s|--|$))", + ), + state_parse_params_option=OrderedDict( + PY_STRING=r"(?P(?:{})|(?:{}))".format( # single and double quoted strings + r"'(?:[^'\\]|\.)*'", r'"(?:[^"\\]|\.)*"' + ), + PARAMS_OPT_SPEC=r"(?P--params(?=\s|=|--|$))", + PARAMS_OPT_EQ=r"(?P=)", + GOTO_PARSE_NON_PARAMS_OPTIONS=r"(?P(?=--\w+))", # found another option spec + PY_BOOL=r"(?PTrue|False)", + DOLLAR_PY_ID=r"(?P\$[^\d\W]\w*)", + PY_NUMBER=r"(?P-?[1-9]\d*(?:\.\d+)?(:?[e|E][+-]?\d+)?)", + SQUOTE=r"(?P')", + DQUOTE=r'(?P")', + COLON=r"(?P:)", + COMMA=r"(?P,)", + LCURL=r"(?P\{)", + RCURL=r"(?P})", + LSQUARE=r"(?P\[)", + RSQUARE=r"(?P])", + LPAREN=r"(?P\()", + RPAREN=r"(?P\))", + ), + common=OrderedDict( + WS=r"(?P\s+)", + EOL=r"(?P$)", + UNKNOWN=r"(?P\S+)", # anything not a whitespace or matched by something else + ), +) + + +class AutoStrEnum(str, enum.Enum): + """Base enum class for for name=value str enums.""" + + def _generate_next_value_(name, start, count, last_values): + return name + + +TokenType = AutoStrEnum( # type: ignore # pytype: disable=wrong-arg-types + "TokenType", + [ + (name, enum.auto()) + for name in itertools.chain.from_iterable(token_types.values()) + if not name.startswith("GOTO_") + ], +) + + +class LexerState(AutoStrEnum): + PARSE_POS_ARGS = enum.auto() # parsing positional arguments + PARSE_NON_PARAMS_OPTIONS = enum.auto() # parsing options other than "--params" + PARSE_PARAMS_OPTION = enum.auto() # parsing the "--params" option + STATE_END = enum.auto() + + +class Lexer(object): + """Lexical analyzer for tokenizing the cell magic input line.""" + + _GRAND_PATTERNS = { + LexerState.PARSE_POS_ARGS: re.compile( + "|".join( + itertools.chain( + token_types["state_parse_pos_args"].values(), + token_types["common"].values(), + ) + ) + ), + LexerState.PARSE_NON_PARAMS_OPTIONS: re.compile( + "|".join( + itertools.chain( + token_types["state_parse_non_params_options"].values(), + token_types["common"].values(), + ) + ) + ), + LexerState.PARSE_PARAMS_OPTION: re.compile( + "|".join( + itertools.chain( + token_types["state_parse_params_option"].values(), + token_types["common"].values(), + ) + ) + ), + } + + def __init__(self, input_text): + self._text = input_text + + def __iter__(self): + # Since re.scanner does not seem to support manipulating inner scanner states, + # we need to implement lexer state transitions manually using special + # non-capturing lookahead token patterns to signal when a state transition + # should be made. + # Since we don't have "nested" states, we don't really need a stack and + # this simple mechanism is sufficient. + state = LexerState.PARSE_POS_ARGS + offset = 0 # the number of characters processed so far + + while state != LexerState.STATE_END: + token_stream = self._find_state_tokens(state, offset) + + for maybe_token in token_stream: # pragma: NO COVER + if isinstance(maybe_token, StateTransition): + state = maybe_token.new_state + offset = maybe_token.total_offset + break + + if maybe_token.type_ != TokenType.WS: + yield maybe_token + + if maybe_token.type_ == TokenType.EOL: + state = LexerState.STATE_END + break + + def _find_state_tokens(self, state, current_offset): + """Scan the input for current state's tokens starting at ``current_offset``. + + Args: + state (LexerState): The current lexer state. + current_offset (int): The offset in the input text, i.e. the number + of characters already scanned so far. + + Yields: + The next ``Token`` or ``StateTransition`` instance. + """ + pattern = self._GRAND_PATTERNS[state] + scanner = pattern.finditer(self._text, current_offset) + + for match in scanner: # pragma: NO COVER + token_type = match.lastgroup + + if token_type.startswith("GOTO_"): + yield StateTransition( + new_state=getattr(LexerState, token_type[5:]), # w/o "GOTO_" prefix + total_offset=match.start(), + ) + + yield Token(token_type, match.group(), match.start()) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/parser.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..b9da20cd78620dfca9d085333ffc574308ad25bb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/parser.py @@ -0,0 +1,484 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from google.cloud.bigquery.magics.line_arg_parser import DuplicateQueryParamsError +from google.cloud.bigquery.magics.line_arg_parser import ParseError +from google.cloud.bigquery.magics.line_arg_parser import QueryParamsParseError +from google.cloud.bigquery.magics.line_arg_parser import TokenType + + +class ParseNode(object): + """A base class for nodes in the input parsed to an abstract syntax tree.""" + + +class InputLine(ParseNode): + def __init__(self, destination_var, option_list): + self.destination_var = destination_var + self.option_list = option_list + + +class DestinationVar(ParseNode): + def __init__(self, token): + # token type is DEST_VAR + self.token = token + self.name = token.lexeme if token is not None else None + + +class CmdOptionList(ParseNode): + def __init__(self, option_nodes): + self.options = [node for node in option_nodes] # shallow copy + + +class CmdOption(ParseNode): + def __init__(self, name, value): + self.name = name # string + self.value = value # CmdOptionValue node + + +class ParamsOption(CmdOption): + def __init__(self, value): + super(ParamsOption, self).__init__("params", value) + + +class CmdOptionValue(ParseNode): + def __init__(self, token): + # token type is OPT_VAL + self.token = token + self.value = token.lexeme + + +class PyVarExpansion(ParseNode): + def __init__(self, token): + self.token = token + self.raw_value = token.lexeme + + +class PyDict(ParseNode): + def __init__(self, dict_items): + self.items = [item for item in dict_items] # shallow copy + + +class PyDictItem(ParseNode): + def __init__(self, key, value): + self.key = key + self.value = value + + +class PyDictKey(ParseNode): + def __init__(self, token): + self.token = token + self.key_value = token.lexeme + + +class PyScalarValue(ParseNode): + def __init__(self, token, raw_value): + self.token = token + self.raw_value = raw_value + + +class PyTuple(ParseNode): + def __init__(self, tuple_items): + self.items = [item for item in tuple_items] # shallow copy + + +class PyList(ParseNode): + def __init__(self, list_items): + self.items = [item for item in list_items] # shallow copy + + +class Parser(object): + """Parser for the tokenized cell magic input line. + + The parser recognizes a simplified subset of Python grammar, specifically + a dictionary representation in typical use cases when the "--params" option + is used with the %%bigquery cell magic. + + The grammar (terminal symbols are CAPITALIZED): + + input_line : destination_var option_list + destination_var : DEST_VAR | EMPTY + option_list : (OPTION_SPEC [OPTION_EQ] option_value)* + (params_option | EMPTY) + (OPTION_SPEC [OPTION_EQ] option_value)* + + option_value : OPT_VAL | EMPTY + + # DOLLAR_PY_ID can occur if a variable passed to --params does not exist + # and is thus not expanded to a dict. + params_option : PARAMS_OPT_SPEC [PARAMS_OPT_EQ] \ + (DOLLAR_PY_ID | PY_STRING | py_dict) + + py_dict : LCURL dict_items RCURL + dict_items : dict_item | (dict_item COMMA dict_items) + dict_item : (dict_key COLON py_value) | EMPTY + + # dict items are actually @parameter names in the cell body (i.e. the query), + # thus restricting them to strings. + dict_key : PY_STRING + + py_value : PY_BOOL + | PY_NUMBER + | PY_STRING + | py_tuple + | py_list + | py_dict + + py_tuple : LPAREN collection_items RPAREN + py_list : LSQUARE collection_items RSQUARE + collection_items : collection_item | (collection_item COMMA collection_items) + collection_item : py_value | EMPTY + + Args: + lexer (line_arg_parser.lexer.Lexer): + An iterable producing a tokenized cell magic argument line. + """ + + def __init__(self, lexer): + self._lexer = lexer + self._tokens_iter = iter(self._lexer) + self.get_next_token() + + def get_next_token(self): + """Obtain the next token from the token stream and store it as current.""" + token = next(self._tokens_iter) + self._current_token = token + + def consume(self, expected_type, exc_type=ParseError): + """Move to the next token in token stream if it matches the expected type. + + Args: + expected_type (lexer.TokenType): The expected token type to be consumed. + exc_type (Optional[ParseError]): The type of the exception to raise. Should be + the ``ParseError`` class or one of its subclasses. Defaults to + ``ParseError``. + + Raises: + ParseError: If the current token does not match the expected type. + """ + if self._current_token.type_ == expected_type: + if expected_type != TokenType.EOL: + self.get_next_token() + else: + if self._current_token.type_ == TokenType.EOL: + msg = "Unexpected end of input, expected {}.".format(expected_type) + else: + msg = "Expected token type {}, but found {} at position {}.".format( + expected_type, self._current_token.lexeme, self._current_token.pos + ) + self.error(message=msg, exc_type=exc_type) + + def error(self, message="Syntax error.", exc_type=ParseError): + """Raise an error with the given message. + + Args: + expected_type (lexer.TokenType): The expected token type to be consumed. + exc_type (Optional[ParseError]): The type of the exception to raise. Should be + the ``ParseError`` class or one of its subclasses. Defaults to + ``ParseError``. + + Raises: + ParseError: If the current token does not match the expected type. + """ + raise exc_type(message) + + def input_line(self): + """The top level method for parsing the cell magic arguments line. + + Implements the following grammar production rule: + + input_line : destination_var option_list + """ + dest_var = self.destination_var() + options = self.option_list() + + token = self._current_token + + if token.type_ != TokenType.EOL: + msg = "Unexpected input at position {}: {}".format(token.pos, token.lexeme) + self.error(msg) + + return InputLine(dest_var, options) + + def destination_var(self): + """Implementation of the ``destination_var`` grammar production rule. + + Production: + + destination_var : DEST_VAR | EMPTY + """ + token = self._current_token + + if token.type_ == TokenType.DEST_VAR: + self.consume(TokenType.DEST_VAR) + result = DestinationVar(token) + elif token.type_ == TokenType.UNKNOWN: + msg = "Unknown input at position {}: {}".format(token.pos, token.lexeme) + self.error(msg) + else: + result = DestinationVar(None) + + return result + + def option_list(self): + """Implementation of the ``option_list`` grammar production rule. + + Production: + + option_list : (OPTION_SPEC [OPTION_EQ] option_value)* + (params_option | EMPTY) + (OPTION_SPEC [OPTION_EQ] option_value)* + """ + all_options = [] + + def parse_nonparams_options(): + while self._current_token.type_ == TokenType.OPTION_SPEC: + token = self._current_token + self.consume(TokenType.OPTION_SPEC) + + opt_name = token.lexeme[2:] # cut off the "--" prefix + + # skip the optional "=" character + if self._current_token.type_ == TokenType.OPTION_EQ: + self.consume(TokenType.OPTION_EQ) + + opt_value = self.option_value() + option = CmdOption(opt_name, opt_value) + all_options.append(option) + + parse_nonparams_options() + + token = self._current_token + + if token.type_ == TokenType.PARAMS_OPT_SPEC: + option = self.params_option() + all_options.append(option) + + parse_nonparams_options() + + if self._current_token.type_ == TokenType.PARAMS_OPT_SPEC: + self.error( + message="Duplicate --params option", exc_type=DuplicateQueryParamsError + ) + + return CmdOptionList(all_options) + + def option_value(self): + """Implementation of the ``option_value`` grammar production rule. + + Production: + + option_value : OPT_VAL | EMPTY + """ + token = self._current_token + + if token.type_ == TokenType.OPT_VAL: + self.consume(TokenType.OPT_VAL) + result = CmdOptionValue(token) + elif token.type_ == TokenType.UNKNOWN: + msg = "Unknown input at position {}: {}".format(token.pos, token.lexeme) + self.error(msg) + else: + result = None + + return result + + def params_option(self): + """Implementation of the ``params_option`` grammar production rule. + + Production: + + params_option : PARAMS_OPT_SPEC [PARAMS_OPT_EQ] \ + (DOLLAR_PY_ID | PY_STRING | py_dict) + """ + self.consume(TokenType.PARAMS_OPT_SPEC) + + # skip the optional "=" character + if self._current_token.type_ == TokenType.PARAMS_OPT_EQ: + self.consume(TokenType.PARAMS_OPT_EQ) + + if self._current_token.type_ == TokenType.DOLLAR_PY_ID: + token = self._current_token + self.consume(TokenType.DOLLAR_PY_ID) + opt_value = PyVarExpansion(token) + elif self._current_token.type_ == TokenType.PY_STRING: + token = self._current_token + self.consume(TokenType.PY_STRING, exc_type=QueryParamsParseError) + opt_value = PyScalarValue(token, token.lexeme) + else: + opt_value = self.py_dict() + + result = ParamsOption(opt_value) + + return result + + def py_dict(self): + """Implementation of the ``py_dict`` grammar production rule. + + Production: + + py_dict : LCURL dict_items RCURL + """ + self.consume(TokenType.LCURL, exc_type=QueryParamsParseError) + dict_items = self.dict_items() + self.consume(TokenType.RCURL, exc_type=QueryParamsParseError) + + return PyDict(dict_items) + + def dict_items(self): + """Implementation of the ``dict_items`` grammar production rule. + + Production: + + dict_items : dict_item | (dict_item COMMA dict_items) + """ + result = [] + + item = self.dict_item() + if item is not None: + result.append(item) + + while self._current_token.type_ == TokenType.COMMA: + self.consume(TokenType.COMMA, exc_type=QueryParamsParseError) + item = self.dict_item() + if item is not None: + result.append(item) + + return result + + def dict_item(self): + """Implementation of the ``dict_item`` grammar production rule. + + Production: + + dict_item : (dict_key COLON py_value) | EMPTY + """ + token = self._current_token + + if token.type_ == TokenType.PY_STRING: + key = self.dict_key() + self.consume(TokenType.COLON, exc_type=QueryParamsParseError) + value = self.py_value() + result = PyDictItem(key, value) + elif token.type_ == TokenType.UNKNOWN: + msg = "Unknown input at position {}: {}".format(token.pos, token.lexeme) + self.error(msg, exc_type=QueryParamsParseError) + else: + result = None + + return result + + def dict_key(self): + """Implementation of the ``dict_key`` grammar production rule. + + Production: + + dict_key : PY_STRING + """ + token = self._current_token + self.consume(TokenType.PY_STRING, exc_type=QueryParamsParseError) + return PyDictKey(token) + + def py_value(self): + """Implementation of the ``py_value`` grammar production rule. + + Production: + + py_value : PY_BOOL | PY_NUMBER | PY_STRING | py_tuple | py_list | py_dict + """ + token = self._current_token + + if token.type_ == TokenType.PY_BOOL: + self.consume(TokenType.PY_BOOL, exc_type=QueryParamsParseError) + return PyScalarValue(token, token.lexeme) + elif token.type_ == TokenType.PY_NUMBER: + self.consume(TokenType.PY_NUMBER, exc_type=QueryParamsParseError) + return PyScalarValue(token, token.lexeme) + elif token.type_ == TokenType.PY_STRING: + self.consume(TokenType.PY_STRING, exc_type=QueryParamsParseError) + return PyScalarValue(token, token.lexeme) + elif token.type_ == TokenType.LPAREN: + tuple_node = self.py_tuple() + return tuple_node + elif token.type_ == TokenType.LSQUARE: + list_node = self.py_list() + return list_node + elif token.type_ == TokenType.LCURL: + dict_node = self.py_dict() + return dict_node + else: + msg = "Unexpected token type {} at position {}.".format( + token.type_, token.pos + ) + self.error(msg, exc_type=QueryParamsParseError) + + def py_tuple(self): + """Implementation of the ``py_tuple`` grammar production rule. + + Production: + + py_tuple : LPAREN collection_items RPAREN + """ + self.consume(TokenType.LPAREN, exc_type=QueryParamsParseError) + items = self.collection_items() + self.consume(TokenType.RPAREN, exc_type=QueryParamsParseError) + + return PyTuple(items) + + def py_list(self): + """Implementation of the ``py_list`` grammar production rule. + + Production: + + py_list : LSQUARE collection_items RSQUARE + """ + self.consume(TokenType.LSQUARE, exc_type=QueryParamsParseError) + items = self.collection_items() + self.consume(TokenType.RSQUARE, exc_type=QueryParamsParseError) + + return PyList(items) + + def collection_items(self): + """Implementation of the ``collection_items`` grammar production rule. + + Production: + + collection_items : collection_item | (collection_item COMMA collection_items) + """ + result = [] + + item = self.collection_item() + if item is not None: + result.append(item) + + while self._current_token.type_ == TokenType.COMMA: + self.consume(TokenType.COMMA, exc_type=QueryParamsParseError) + item = self.collection_item() + if item is not None: + result.append(item) + + return result + + def collection_item(self): + """Implementation of the ``collection_item`` grammar production rule. + + Production: + + collection_item : py_value | EMPTY + """ + if self._current_token.type_ not in {TokenType.RPAREN, TokenType.RSQUARE}: + result = self.py_value() + else: + result = None # end of list/tuple items + + return result diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/visitors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/visitors.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe236c06d91a6f9590104c4957381324f87b915 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/line_arg_parser/visitors.py @@ -0,0 +1,159 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""This module contains classes that traverse AST and convert it to something else. + +If the parser successfully accepts a valid input (the bigquery cell magic arguments), +the result is an Abstract Syntax Tree (AST) that represents the input as a tree +with notes containing various useful metadata. + +Node visitors can process such tree and convert it to something else that can +be used for further processing, for example: + + * An optimized version of the tree with redundancy removed/simplified (not used here). + * The same tree, but with semantic errors checked, because an otherwise syntactically + valid input might still contain errors (not used here, semantic errors are detected + elsewhere). + * A form that can be directly handed to the code that operates on the input. The + ``QueryParamsExtractor`` class, for instance, splits the input arguments into + the "--params <...>" part and everything else. + The "everything else" part can be then parsed by the default Jupyter argument parser, + while the --params option is processed separately by the Python evaluator. + +More info on the visitor design pattern: +https://en.wikipedia.org/wiki/Visitor_pattern + +""" + +from __future__ import print_function + + +class NodeVisitor(object): + """Base visitor class implementing the dispatch machinery.""" + + def visit(self, node): + method_name = "visit_{}".format(type(node).__name__) + visitor_method = getattr(self, method_name, self.method_missing) + return visitor_method(node) + + def method_missing(self, node): + raise Exception("No visit_{} method".format(type(node).__name__)) + + +class QueryParamsExtractor(NodeVisitor): + """A visitor that extracts the "--params <...>" part from input line arguments.""" + + def visit_InputLine(self, node): + params_dict_parts = [] + other_parts = [] + + dest_var_parts = self.visit(node.destination_var) + params, other_options = self.visit(node.option_list) + + if dest_var_parts: + other_parts.extend(dest_var_parts) + + if dest_var_parts and other_options: + other_parts.append(" ") + other_parts.extend(other_options) + + params_dict_parts.extend(params) + + return "".join(params_dict_parts), "".join(other_parts) + + def visit_DestinationVar(self, node): + return [node.name] if node.name is not None else [] + + def visit_CmdOptionList(self, node): + params_opt_parts = [] + other_parts = [] + + for i, opt in enumerate(node.options): + option_parts = self.visit(opt) + list_to_extend = params_opt_parts if opt.name == "params" else other_parts + + if list_to_extend: + list_to_extend.append(" ") + list_to_extend.extend(option_parts) + + return params_opt_parts, other_parts + + def visit_CmdOption(self, node): + result = ["--{}".format(node.name)] + + if node.value is not None: + result.append(" ") + value_parts = self.visit(node.value) + result.extend(value_parts) + + return result + + def visit_CmdOptionValue(self, node): + return [node.value] + + def visit_ParamsOption(self, node): + value_parts = self.visit(node.value) + return value_parts + + def visit_PyVarExpansion(self, node): + return [node.raw_value] + + def visit_PyDict(self, node): + result = ["{"] + + for i, item in enumerate(node.items): + if i > 0: + result.append(", ") + item_parts = self.visit(item) + result.extend(item_parts) + + result.append("}") + return result + + def visit_PyDictItem(self, node): + result = self.visit(node.key) # key parts + result.append(": ") + value_parts = self.visit(node.value) + result.extend(value_parts) + return result + + def visit_PyDictKey(self, node): + return [node.key_value] + + def visit_PyScalarValue(self, node): + return [node.raw_value] + + def visit_PyTuple(self, node): + result = ["("] + + for i, item in enumerate(node.items): + if i > 0: + result.append(", ") + item_parts = self.visit(item) + result.extend(item_parts) + + result.append(")") + return result + + def visit_PyList(self, node): + result = ["["] + + for i, item in enumerate(node.items): + if i > 0: + result.append(", ") + item_parts = self.visit(item) + result.extend(item_parts) + + result.append("]") + return result diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/magics.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/magics.py new file mode 100644 index 0000000000000000000000000000000000000000..1f892b5952224707e70adb808067f4506e2c70d3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/magics/magics.py @@ -0,0 +1,776 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""IPython Magics + +Install ``bigquery-magics`` and call ``%load_ext bigquery_magics`` to use the +``%%bigquery`` cell magic. + +See the `BigQuery Magics reference documentation +`_. +""" + +from __future__ import print_function + +import re +import ast +import copy +import functools +import sys +import time +import warnings +from concurrent import futures + +try: + import IPython # type: ignore + from IPython import display # type: ignore + from IPython.core import magic_arguments # type: ignore +except ImportError: + raise ImportError("This module can only be loaded in IPython.") + +from google.api_core import client_info +from google.api_core import client_options +from google.api_core.exceptions import NotFound +import google.auth # type: ignore +from google.cloud import bigquery +import google.cloud.bigquery.dataset +from google.cloud.bigquery import _versions_helpers +from google.cloud.bigquery import exceptions +from google.cloud.bigquery.dbapi import _helpers +from google.cloud.bigquery.magics import line_arg_parser as lap + +try: + import bigquery_magics # type: ignore +except ImportError: + bigquery_magics = None + +IPYTHON_USER_AGENT = "ipython-{}".format(IPython.__version__) # type: ignore + + +class Context(object): + """Storage for objects to be used throughout an IPython notebook session. + + A Context object is initialized when the ``magics`` module is imported, + and can be found at ``google.cloud.bigquery.magics.context``. + """ + + def __init__(self): + self._credentials = None + self._project = None + self._connection = None + self._default_query_job_config = bigquery.QueryJobConfig() + self._bigquery_client_options = client_options.ClientOptions() + self._bqstorage_client_options = client_options.ClientOptions() + self._progress_bar_type = "tqdm_notebook" + + @property + def credentials(self): + """google.auth.credentials.Credentials: Credentials to use for queries + performed through IPython magics. + + Note: + These credentials do not need to be explicitly defined if you are + using Application Default Credentials. If you are not using + Application Default Credentials, manually construct a + :class:`google.auth.credentials.Credentials` object and set it as + the context credentials as demonstrated in the example below. See + `auth docs`_ for more information on obtaining credentials. + + Example: + Manually setting the context credentials: + + >>> from google.cloud.bigquery import magics + >>> from google.oauth2 import service_account + >>> credentials = (service_account + ... .Credentials.from_service_account_file( + ... '/path/to/key.json')) + >>> magics.context.credentials = credentials + + + .. _auth docs: http://google-auth.readthedocs.io + /en/latest/user-guide.html#obtaining-credentials + """ + if self._credentials is None: + self._credentials, _ = google.auth.default() + return self._credentials + + @credentials.setter + def credentials(self, value): + self._credentials = value + + @property + def project(self): + """str: Default project to use for queries performed through IPython + magics. + + Note: + The project does not need to be explicitly defined if you have an + environment default project set. If you do not have a default + project set in your environment, manually assign the project as + demonstrated in the example below. + + Example: + Manually setting the context project: + + >>> from google.cloud.bigquery import magics + >>> magics.context.project = 'my-project' + """ + if self._project is None: + _, self._project = google.auth.default() + return self._project + + @project.setter + def project(self, value): + self._project = value + + @property + def bigquery_client_options(self): + """google.api_core.client_options.ClientOptions: client options to be + used through IPython magics. + + Note:: + The client options do not need to be explicitly defined if no + special network connections are required. Normally you would be + using the https://bigquery.googleapis.com/ end point. + + Example: + Manually setting the endpoint: + + >>> from google.cloud.bigquery import magics + >>> client_options = {} + >>> client_options['api_endpoint'] = "https://some.special.url" + >>> magics.context.bigquery_client_options = client_options + """ + return self._bigquery_client_options + + @bigquery_client_options.setter + def bigquery_client_options(self, value): + self._bigquery_client_options = value + + @property + def bqstorage_client_options(self): + """google.api_core.client_options.ClientOptions: client options to be + used through IPython magics for the storage client. + + Note:: + The client options do not need to be explicitly defined if no + special network connections are required. Normally you would be + using the https://bigquerystorage.googleapis.com/ end point. + + Example: + Manually setting the endpoint: + + >>> from google.cloud.bigquery import magics + >>> client_options = {} + >>> client_options['api_endpoint'] = "https://some.special.url" + >>> magics.context.bqstorage_client_options = client_options + """ + return self._bqstorage_client_options + + @bqstorage_client_options.setter + def bqstorage_client_options(self, value): + self._bqstorage_client_options = value + + @property + def default_query_job_config(self): + """google.cloud.bigquery.job.QueryJobConfig: Default job + configuration for queries. + + The context's :class:`~google.cloud.bigquery.job.QueryJobConfig` is + used for queries. Some properties can be overridden with arguments to + the magics. + + Example: + Manually setting the default value for ``maximum_bytes_billed`` + to 100 MB: + + >>> from google.cloud.bigquery import magics + >>> magics.context.default_query_job_config.maximum_bytes_billed = 100000000 + """ + return self._default_query_job_config + + @default_query_job_config.setter + def default_query_job_config(self, value): + self._default_query_job_config = value + + @property + def progress_bar_type(self): + """str: Default progress bar type to use to display progress bar while + executing queries through IPython magics. + + Note:: + Install the ``tqdm`` package to use this feature. + + Example: + Manually setting the progress_bar_type: + + >>> from google.cloud.bigquery import magics + >>> magics.context.progress_bar_type = "tqdm_notebook" + """ + return self._progress_bar_type + + @progress_bar_type.setter + def progress_bar_type(self, value): + self._progress_bar_type = value + + +# If bigquery_magics is available, we load that extension rather than this one. +# Ensure google.cloud.bigquery.magics.context setters are on the correct magics +# implementation in case the user has installed the package but hasn't updated +# their code. +if bigquery_magics is not None: + context = bigquery_magics.context +else: + context = Context() + + +def _handle_error(error, destination_var=None): + """Process a query execution error. + + Args: + error (Exception): + An exception that occurred during the query execution. + destination_var (Optional[str]): + The name of the IPython session variable to store the query job. + """ + if destination_var: + query_job = getattr(error, "query_job", None) + + if query_job is not None: + IPython.get_ipython().push({destination_var: query_job}) + else: + # this is the case when previewing table rows by providing just + # table ID to cell magic + print( + "Could not save output to variable '{}'.".format(destination_var), + file=sys.stderr, + ) + + print("\nERROR:\n", str(error), file=sys.stderr) + + +def _run_query(client, query, job_config=None): + """Runs a query while printing status updates + + Args: + client (google.cloud.bigquery.client.Client): + Client to bundle configuration needed for API requests. + query (str): + SQL query to be executed. Defaults to the standard SQL dialect. + Use the ``job_config`` parameter to change dialects. + job_config (Optional[google.cloud.bigquery.job.QueryJobConfig]): + Extra configuration options for the job. + + Returns: + google.cloud.bigquery.job.QueryJob: the query job created + + Example: + >>> client = bigquery.Client() + >>> _run_query(client, "SELECT 17") + Executing query with job ID: bf633912-af2c-4780-b568-5d868058632b + Query executing: 1.66s + Query complete after 2.07s + 'bf633912-af2c-4780-b568-5d868058632b' + """ + start_time = time.perf_counter() + query_job = client.query(query, job_config=job_config) + + if job_config and job_config.dry_run: + return query_job + + print(f"Executing query with job ID: {query_job.job_id}") + + while True: + print( + f"\rQuery executing: {time.perf_counter() - start_time:.2f}s".format(), + end="", + ) + try: + query_job.result(timeout=0.5) + break + except futures.TimeoutError: + continue + print(f"\nJob ID {query_job.job_id} successfully executed") + return query_job + + +def _create_dataset_if_necessary(client, dataset_id): + """Create a dataset in the current project if it doesn't exist. + + Args: + client (google.cloud.bigquery.client.Client): + Client to bundle configuration needed for API requests. + dataset_id (str): + Dataset id. + """ + dataset_reference = bigquery.dataset.DatasetReference(client.project, dataset_id) + try: + dataset = client.get_dataset(dataset_reference) + return + except NotFound: + pass + dataset = bigquery.Dataset(dataset_reference) + dataset.location = client.location + print(f"Creating dataset: {dataset_id}") + dataset = client.create_dataset(dataset) + + +@magic_arguments.magic_arguments() +@magic_arguments.argument( + "destination_var", + nargs="?", + help=("If provided, save the output to this variable instead of displaying it."), +) +@magic_arguments.argument( + "--destination_table", + type=str, + default=None, + help=( + "If provided, save the output of the query to a new BigQuery table. " + "Variable should be in a format .. " + "If table does not exists, it will be created. " + "If table already exists, its data will be overwritten." + ), +) +@magic_arguments.argument( + "--project", + type=str, + default=None, + help=("Project to use for executing this query. Defaults to the context project."), +) +@magic_arguments.argument( + "--max_results", + default=None, + help=( + "Maximum number of rows in dataframe returned from executing the query." + "Defaults to returning all rows." + ), +) +@magic_arguments.argument( + "--maximum_bytes_billed", + default=None, + help=( + "maximum_bytes_billed to use for executing this query. Defaults to " + "the context default_query_job_config.maximum_bytes_billed." + ), +) +@magic_arguments.argument( + "--dry_run", + action="store_true", + default=False, + help=( + "Sets query to be a dry run to estimate costs. " + "Defaults to executing the query instead of dry run if this argument is not used." + ), +) +@magic_arguments.argument( + "--use_legacy_sql", + action="store_true", + default=False, + help=( + "Sets query to use Legacy SQL instead of Standard SQL. Defaults to " + "Standard SQL if this argument is not used." + ), +) +@magic_arguments.argument( + "--bigquery_api_endpoint", + type=str, + default=None, + help=( + "The desired API endpoint, e.g., bigquery.googlepis.com. Defaults to this " + "option's value in the context bigquery_client_options." + ), +) +@magic_arguments.argument( + "--bqstorage_api_endpoint", + type=str, + default=None, + help=( + "The desired API endpoint, e.g., bigquerystorage.googlepis.com. Defaults to " + "this option's value in the context bqstorage_client_options." + ), +) +@magic_arguments.argument( + "--no_query_cache", + action="store_true", + default=False, + help=("Do not use cached query results."), +) +@magic_arguments.argument( + "--use_bqstorage_api", + action="store_true", + default=None, + help=( + "[Deprecated] The BigQuery Storage API is already used by default to " + "download large query results, and this option has no effect. " + "If you want to switch to the classic REST API instead, use the " + "--use_rest_api option." + ), +) +@magic_arguments.argument( + "--use_rest_api", + action="store_true", + default=False, + help=( + "Use the classic REST API instead of the BigQuery Storage API to " + "download query results." + ), +) +@magic_arguments.argument( + "--verbose", + action="store_true", + default=False, + help=( + "If set, print verbose output, including the query job ID and the " + "amount of time for the query to finish. By default, this " + "information will be displayed as the query runs, but will be " + "cleared after the query is finished." + ), +) +@magic_arguments.argument( + "--params", + nargs="+", + default=None, + help=( + "Parameters to format the query string. If present, the --params " + "flag should be followed by a string representation of a dictionary " + "in the format {'param_name': 'param_value'} (ex. {\"num\": 17}), " + "or a reference to a dictionary in the same format. The dictionary " + "reference can be made by including a '$' before the variable " + "name (ex. $my_dict_var)." + ), +) +@magic_arguments.argument( + "--progress_bar_type", + type=str, + default=None, + help=( + "Sets progress bar type to display a progress bar while executing the query." + "Defaults to use tqdm_notebook. Install the ``tqdm`` package to use this feature." + ), +) +@magic_arguments.argument( + "--location", + type=str, + default=None, + help=( + "Set the location to execute query." + "Defaults to location set in query setting in console." + ), +) +def _cell_magic(line, query): + """Underlying function for bigquery cell magic + + Note: + This function contains the underlying logic for the 'bigquery' cell + magic. This function is not meant to be called directly. + + Args: + line (str): "%%bigquery" followed by arguments as required + query (str): SQL query to run + + Returns: + pandas.DataFrame: the query results. + """ + # The built-in parser does not recognize Python structures such as dicts, thus + # we extract the "--params" option and inteprpret it separately. + try: + params_option_value, rest_of_args = _split_args_line(line) + except lap.exceptions.QueryParamsParseError as exc: + rebranded_error = SyntaxError( + "--params is not a correctly formatted JSON string or a JSON " + "serializable dictionary" + ) + raise rebranded_error from exc + except lap.exceptions.DuplicateQueryParamsError as exc: + rebranded_error = ValueError("Duplicate --params option.") + raise rebranded_error from exc + except lap.exceptions.ParseError as exc: + rebranded_error = ValueError( + "Unrecognized input, are option values correct? " + "Error details: {}".format(exc.args[0]) + ) + raise rebranded_error from exc + + args = magic_arguments.parse_argstring(_cell_magic, rest_of_args) + + if args.use_bqstorage_api is not None: + warnings.warn( + "Deprecated option --use_bqstorage_api, the BigQuery " + "Storage API is already used by default.", + category=DeprecationWarning, + ) + use_bqstorage_api = not args.use_rest_api + location = args.location + + params = [] + if params_option_value: + # A non-existing params variable is not expanded and ends up in the input + # in its raw form, e.g. "$query_params". + if params_option_value.startswith("$"): + msg = 'Parameter expansion failed, undefined variable "{}".'.format( + params_option_value[1:] + ) + raise NameError(msg) + + params = _helpers.to_query_parameters(ast.literal_eval(params_option_value), {}) + + project = args.project or context.project + + bigquery_client_options = copy.deepcopy(context.bigquery_client_options) + if args.bigquery_api_endpoint: + if isinstance(bigquery_client_options, dict): + bigquery_client_options["api_endpoint"] = args.bigquery_api_endpoint + else: + bigquery_client_options.api_endpoint = args.bigquery_api_endpoint + + client = bigquery.Client( + project=project, + credentials=context.credentials, + default_query_job_config=context.default_query_job_config, + client_info=client_info.ClientInfo(user_agent=IPYTHON_USER_AGENT), + client_options=bigquery_client_options, + location=location, + ) + if context._connection: + client._connection = context._connection + + bqstorage_client_options = copy.deepcopy(context.bqstorage_client_options) + if args.bqstorage_api_endpoint: + if isinstance(bqstorage_client_options, dict): + bqstorage_client_options["api_endpoint"] = args.bqstorage_api_endpoint + else: + bqstorage_client_options.api_endpoint = args.bqstorage_api_endpoint + + bqstorage_client = _make_bqstorage_client( + client, + use_bqstorage_api, + bqstorage_client_options, + ) + + close_transports = functools.partial(_close_transports, client, bqstorage_client) + + try: + if args.max_results: + max_results = int(args.max_results) + else: + max_results = None + + query = query.strip() + + if not query: + error = ValueError("Query is missing.") + _handle_error(error, args.destination_var) + return + + # Check if query is given as a reference to a variable. + if query.startswith("$"): + query_var_name = query[1:] + + if not query_var_name: + missing_msg = 'Missing query variable name, empty "$" is not allowed.' + raise NameError(missing_msg) + + if query_var_name.isidentifier(): + ip = IPython.get_ipython() + query = ip.user_ns.get(query_var_name, ip) # ip serves as a sentinel + + if query is ip: + raise NameError( + f"Unknown query, variable {query_var_name} does not exist." + ) + else: + if not isinstance(query, (str, bytes)): + raise TypeError( + f"Query variable {query_var_name} must be a string " + "or a bytes-like value." + ) + + # Any query that does not contain whitespace (aside from leading and trailing whitespace) + # is assumed to be a table id + if not re.search(r"\s", query): + try: + rows = client.list_rows(query, max_results=max_results) + except Exception as ex: + _handle_error(ex, args.destination_var) + return + + result = rows.to_dataframe( + bqstorage_client=bqstorage_client, + create_bqstorage_client=False, + ) + if args.destination_var: + IPython.get_ipython().push({args.destination_var: result}) + return + else: + return result + + job_config = bigquery.job.QueryJobConfig() + job_config.query_parameters = params + job_config.use_legacy_sql = args.use_legacy_sql + job_config.dry_run = args.dry_run + + # Don't override context job config unless --no_query_cache is explicitly set. + if args.no_query_cache: + job_config.use_query_cache = False + + if args.destination_table: + split = args.destination_table.split(".") + if len(split) != 2: + raise ValueError( + "--destination_table should be in a . format." + ) + dataset_id, table_id = split + job_config.allow_large_results = True + dataset_ref = bigquery.dataset.DatasetReference(client.project, dataset_id) + destination_table_ref = dataset_ref.table(table_id) + job_config.destination = destination_table_ref + job_config.create_disposition = "CREATE_IF_NEEDED" + job_config.write_disposition = "WRITE_TRUNCATE" + _create_dataset_if_necessary(client, dataset_id) + + if args.maximum_bytes_billed == "None": + job_config.maximum_bytes_billed = 0 + elif args.maximum_bytes_billed is not None: + value = int(args.maximum_bytes_billed) + job_config.maximum_bytes_billed = value + + try: + query_job = _run_query(client, query, job_config=job_config) + except Exception as ex: + _handle_error(ex, args.destination_var) + return + + if not args.verbose: + display.clear_output() + + if args.dry_run and args.destination_var: + IPython.get_ipython().push({args.destination_var: query_job}) + return + elif args.dry_run: + print( + "Query validated. This query will process {} bytes.".format( + query_job.total_bytes_processed + ) + ) + return query_job + + progress_bar = context.progress_bar_type or args.progress_bar_type + + if max_results: + result = query_job.result(max_results=max_results).to_dataframe( + bqstorage_client=None, + create_bqstorage_client=False, + progress_bar_type=progress_bar, + ) + else: + result = query_job.to_dataframe( + bqstorage_client=bqstorage_client, + create_bqstorage_client=False, + progress_bar_type=progress_bar, + ) + + if args.destination_var: + IPython.get_ipython().push({args.destination_var: result}) + else: + return result + finally: + close_transports() + + +def _split_args_line(line): + """Split out the --params option value from the input line arguments. + + Args: + line (str): The line arguments passed to the cell magic. + + Returns: + Tuple[str, str] + """ + lexer = lap.Lexer(line) + scanner = lap.Parser(lexer) + tree = scanner.input_line() + + extractor = lap.QueryParamsExtractor() + params_option_value, rest_of_args = extractor.visit(tree) + + return params_option_value, rest_of_args + + +def _make_bqstorage_client(client, use_bqstorage_api, client_options): + """Creates a BigQuery Storage client. + + Args: + client (:class:`~google.cloud.bigquery.client.Client`): BigQuery client. + use_bqstorage_api (bool): whether BigQuery Storage API is used or not. + client_options (:class:`google.api_core.client_options.ClientOptions`): + Custom options used with a new BigQuery Storage client instance + if one is created. + + Raises: + ImportError: if google-cloud-bigquery-storage is not installed, or + grpcio package is not installed. + + + Returns: + None: if ``use_bqstorage_api == False``, or google-cloud-bigquery-storage + is outdated. + BigQuery Storage Client: + """ + if not use_bqstorage_api: + return None + + try: + _versions_helpers.BQ_STORAGE_VERSIONS.try_import(raise_if_error=True) + except exceptions.BigQueryStorageNotFoundError as err: + customized_error = ImportError( + "The default BigQuery Storage API client cannot be used, install " + "the missing google-cloud-bigquery-storage and pyarrow packages " + "to use it. Alternatively, use the classic REST API by specifying " + "the --use_rest_api magic option." + ) + raise customized_error from err + except exceptions.LegacyBigQueryStorageError: + pass + + try: + from google.api_core.gapic_v1 import client_info as gapic_client_info + except ImportError as err: + customized_error = ImportError( + "Install the grpcio package to use the BigQuery Storage API." + ) + raise customized_error from err + + return client._ensure_bqstorage_client( + client_options=client_options, + client_info=gapic_client_info.ClientInfo(user_agent=IPYTHON_USER_AGENT), + ) + + +def _close_transports(client, bqstorage_client): + """Close the given clients' underlying transport channels. + + Closing the transport is needed to release system resources, namely open + sockets. + + Args: + client (:class:`~google.cloud.bigquery.client.Client`): + bqstorage_client + (Optional[:class:`~google.cloud.bigquery_storage.BigQueryReadClient`]): + A client for the BigQuery Storage API. + + """ + client.close() + if bqstorage_client is not None: + bqstorage_client._transport.grpc_channel.close() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0251039579ca34cb5c8c2daeff08a780cc400fd0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__init__.py @@ -0,0 +1,35 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""User-Defined Routines.""" + + +from google.cloud.bigquery.enums import DeterminismLevel +from google.cloud.bigquery.routine.routine import Routine +from google.cloud.bigquery.routine.routine import RoutineArgument +from google.cloud.bigquery.routine.routine import RoutineReference +from google.cloud.bigquery.routine.routine import RoutineType +from google.cloud.bigquery.routine.routine import RemoteFunctionOptions +from google.cloud.bigquery.routine.routine import ExternalRuntimeOptions + + +__all__ = ( + "DeterminismLevel", + "Routine", + "RoutineArgument", + "RoutineReference", + "RoutineType", + "RemoteFunctionOptions", + "ExternalRuntimeOptions", +) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bbf4335e81c9dafd600d062947da7bb586ee927 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__pycache__/routine.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__pycache__/routine.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb0e543f75a6dd7471470fdbc8c3ec8d5d092aa Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/__pycache__/routine.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/routine.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/routine.py new file mode 100644 index 0000000000000000000000000000000000000000..c5aa8750ea70eae5ebf438612151af28e5da84a8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/bigquery/routine/routine.py @@ -0,0 +1,921 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Define resources for the BigQuery Routines API.""" +import typing +from typing import Any, Dict, Optional, Union + +import google.cloud._helpers # type: ignore +from google.cloud.bigquery import _helpers +from google.cloud.bigquery.standard_sql import StandardSqlDataType +from google.cloud.bigquery.standard_sql import StandardSqlTableType + + +class RoutineType: + """The fine-grained type of the routine. + + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#routinetype + + .. versionadded:: 2.22.0 + """ + + ROUTINE_TYPE_UNSPECIFIED = "ROUTINE_TYPE_UNSPECIFIED" + SCALAR_FUNCTION = "SCALAR_FUNCTION" + PROCEDURE = "PROCEDURE" + TABLE_VALUED_FUNCTION = "TABLE_VALUED_FUNCTION" + + +class Routine(object): + """Resource representing a user-defined routine. + + See + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines + + Args: + routine_ref (Union[str, google.cloud.bigquery.routine.RoutineReference]): + A pointer to a routine. If ``routine_ref`` is a string, it must + included a project ID, dataset ID, and routine ID, each separated + by ``.``. + ``**kwargs`` (Dict): + Initial property values. + """ + + _PROPERTY_TO_API_FIELD = { + "arguments": "arguments", + "body": "definitionBody", + "created": "creationTime", + "etag": "etag", + "imported_libraries": "importedLibraries", + "language": "language", + "modified": "lastModifiedTime", + "reference": "routineReference", + "return_type": "returnType", + "return_table_type": "returnTableType", + "type_": "routineType", + "description": "description", + "determinism_level": "determinismLevel", + "remote_function_options": "remoteFunctionOptions", + "data_governance_type": "dataGovernanceType", + "external_runtime_options": "externalRuntimeOptions", + } + + def __init__(self, routine_ref, **kwargs) -> None: + if isinstance(routine_ref, str): + routine_ref = RoutineReference.from_string(routine_ref) + + self._properties = {"routineReference": routine_ref.to_api_repr()} + for property_name in kwargs: + setattr(self, property_name, kwargs[property_name]) + + @property + def reference(self): + """google.cloud.bigquery.routine.RoutineReference: Reference + describing the ID of this routine. + """ + return RoutineReference.from_api_repr( + self._properties[self._PROPERTY_TO_API_FIELD["reference"]] + ) + + @property + def path(self): + """str: URL path for the routine's APIs.""" + return self.reference.path + + @property + def project(self): + """str: ID of the project containing the routine.""" + return self.reference.project + + @property + def dataset_id(self): + """str: ID of dataset containing the routine.""" + return self.reference.dataset_id + + @property + def routine_id(self): + """str: The routine ID.""" + return self.reference.routine_id + + @property + def etag(self): + """str: ETag for the resource (:data:`None` until set from the + server). + + Read-only. + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["etag"]) + + @property + def type_(self): + """str: The fine-grained type of the routine. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#RoutineType + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["type_"]) + + @type_.setter + def type_(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["type_"]] = value + + @property + def created(self): + """Optional[datetime.datetime]: Datetime at which the routine was + created (:data:`None` until set from the server). + + Read-only. + """ + value = self._properties.get(self._PROPERTY_TO_API_FIELD["created"]) + if value is not None and value != 0: + # value will be in milliseconds. + return google.cloud._helpers._datetime_from_microseconds( + 1000.0 * float(value) + ) + + @property + def modified(self): + """Optional[datetime.datetime]: Datetime at which the routine was + last modified (:data:`None` until set from the server). + + Read-only. + """ + value = self._properties.get(self._PROPERTY_TO_API_FIELD["modified"]) + if value is not None and value != 0: + # value will be in milliseconds. + return google.cloud._helpers._datetime_from_microseconds( + 1000.0 * float(value) + ) + + @property + def language(self): + """Optional[str]: The language of the routine. + + Defaults to ``SQL``. + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["language"]) + + @language.setter + def language(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["language"]] = value + + @property + def arguments(self): + """List[google.cloud.bigquery.routine.RoutineArgument]: Input/output + argument of a function or a stored procedure. + + In-place modification is not supported. To set, replace the entire + property value with the modified list of + :class:`~google.cloud.bigquery.routine.RoutineArgument` objects. + """ + resources = self._properties.get(self._PROPERTY_TO_API_FIELD["arguments"], []) + return [RoutineArgument.from_api_repr(resource) for resource in resources] + + @arguments.setter + def arguments(self, value): + if not value: + resource = [] + else: + resource = [argument.to_api_repr() for argument in value] + self._properties[self._PROPERTY_TO_API_FIELD["arguments"]] = resource + + @property + def return_type(self): + """google.cloud.bigquery.StandardSqlDataType: Return type of + the routine. + + If absent, the return type is inferred from + :attr:`~google.cloud.bigquery.routine.Routine.body` at query time in + each query that references this routine. If present, then the + evaluated result will be cast to the specified returned type at query + time. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#Routine.FIELDS.return_type + """ + resource = self._properties.get(self._PROPERTY_TO_API_FIELD["return_type"]) + if not resource: + return resource + + return StandardSqlDataType.from_api_repr(resource) + + @return_type.setter + def return_type(self, value: StandardSqlDataType): + resource = None if not value else value.to_api_repr() + self._properties[self._PROPERTY_TO_API_FIELD["return_type"]] = resource + + @property + def return_table_type(self) -> Union[StandardSqlTableType, Any, None]: + """The return type of a Table Valued Function (TVF) routine. + + .. versionadded:: 2.22.0 + """ + resource = self._properties.get( + self._PROPERTY_TO_API_FIELD["return_table_type"] + ) + if not resource: + return resource + + return StandardSqlTableType.from_api_repr(resource) + + @return_table_type.setter + def return_table_type(self, value: Optional[StandardSqlTableType]): + if not value: + resource = None + else: + resource = value.to_api_repr() + + self._properties[self._PROPERTY_TO_API_FIELD["return_table_type"]] = resource + + @property + def imported_libraries(self): + """List[str]: The path of the imported JavaScript libraries. + + The :attr:`~google.cloud.bigquery.routine.Routine.language` must + equal ``JAVACRIPT``. + + Examples: + Set the ``imported_libraries`` to a list of Google Cloud Storage + URIs. + + .. code-block:: python + + routine = bigquery.Routine("proj.dataset.routine_id") + routine.imported_libraries = [ + "gs://cloud-samples-data/bigquery/udfs/max-value.js", + ] + """ + return self._properties.get( + self._PROPERTY_TO_API_FIELD["imported_libraries"], [] + ) + + @imported_libraries.setter + def imported_libraries(self, value): + if not value: + resource = [] + else: + resource = value + self._properties[self._PROPERTY_TO_API_FIELD["imported_libraries"]] = resource + + @property + def body(self): + """str: The body of the routine.""" + return self._properties.get(self._PROPERTY_TO_API_FIELD["body"]) + + @body.setter + def body(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["body"]] = value + + @property + def description(self): + """Optional[str]: Description of the routine (defaults to + :data:`None`). + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["description"]) + + @description.setter + def description(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["description"]] = value + + @property + def determinism_level(self): + """Optional[str]: (experimental) The determinism level of the JavaScript UDF + if defined. + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["determinism_level"]) + + @determinism_level.setter + def determinism_level(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["determinism_level"]] = value + + @property + def remote_function_options(self): + """Optional[google.cloud.bigquery.routine.RemoteFunctionOptions]: + Configures remote function options for a routine. + + Raises: + ValueError: + If the value is not + :class:`~google.cloud.bigquery.routine.RemoteFunctionOptions` or + :data:`None`. + """ + prop = self._properties.get( + self._PROPERTY_TO_API_FIELD["remote_function_options"] + ) + if prop is not None: + return RemoteFunctionOptions.from_api_repr(prop) + + @remote_function_options.setter + def remote_function_options(self, value): + api_repr = value + if isinstance(value, RemoteFunctionOptions): + api_repr = value.to_api_repr() + elif value is not None: + raise ValueError( + "value must be google.cloud.bigquery.routine.RemoteFunctionOptions " + "or None" + ) + self._properties[ + self._PROPERTY_TO_API_FIELD["remote_function_options"] + ] = api_repr + + @property + def data_governance_type(self): + """Optional[str]: If set to ``DATA_MASKING``, the function is validated + and made available as a masking function. + + Raises: + ValueError: + If the value is not :data:`string` or :data:`None`. + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["data_governance_type"]) + + @data_governance_type.setter + def data_governance_type(self, value): + if value is not None and not isinstance(value, str): + raise ValueError( + "invalid data_governance_type, must be a string or `None`." + ) + self._properties[self._PROPERTY_TO_API_FIELD["data_governance_type"]] = value + + @property + def external_runtime_options(self): + """Optional[google.cloud.bigquery.routine.ExternalRuntimeOptions]: + Configures the external runtime options for a routine. + + Raises: + ValueError: + If the value is not + :class:`~google.cloud.bigquery.routine.ExternalRuntimeOptions` or + :data:`None`. + """ + prop = self._properties.get( + self._PROPERTY_TO_API_FIELD["external_runtime_options"] + ) + if prop is not None: + return ExternalRuntimeOptions.from_api_repr(prop) + + @external_runtime_options.setter + def external_runtime_options(self, value): + api_repr = value + if isinstance(value, ExternalRuntimeOptions): + api_repr = value.to_api_repr() + elif value is not None: + raise ValueError( + "value must be google.cloud.bigquery.routine.ExternalRuntimeOptions " + "or None" + ) + self._properties[ + self._PROPERTY_TO_API_FIELD["external_runtime_options"] + ] = api_repr + + @classmethod + def from_api_repr(cls, resource: dict) -> "Routine": + """Factory: construct a routine given its API representation. + + Args: + resource (Dict[str, object]): + Resource, as returned from the API. + + Returns: + google.cloud.bigquery.routine.Routine: + Python object, as parsed from ``resource``. + """ + ref = cls(RoutineReference.from_api_repr(resource["routineReference"])) + ref._properties = resource + return ref + + def to_api_repr(self) -> dict: + """Construct the API resource representation of this routine. + + Returns: + Dict[str, object]: Routine represented as an API resource. + """ + return self._properties + + def _build_resource(self, filter_fields): + """Generate a resource for ``update``.""" + return _helpers._build_resource_from_properties(self, filter_fields) + + def __repr__(self): + return "Routine('{}.{}.{}')".format( + self.project, self.dataset_id, self.routine_id + ) + + +class RoutineArgument(object): + """Input/output argument of a function or a stored procedure. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#argument + + Args: + ``**kwargs`` (Dict): + Initial property values. + """ + + _PROPERTY_TO_API_FIELD = { + "data_type": "dataType", + "kind": "argumentKind", + # Even though it's not necessary for field mapping to map when the + # property name equals the resource name, we add these here so that we + # have an exhaustive list of all properties. + "name": "name", + "mode": "mode", + } + + def __init__(self, **kwargs) -> None: + self._properties: Dict[str, Any] = {} + for property_name in kwargs: + setattr(self, property_name, kwargs[property_name]) + + @property + def name(self): + """Optional[str]: Name of this argument. + + Can be absent for function return argument. + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["name"]) + + @name.setter + def name(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["name"]] = value + + @property + def kind(self): + """Optional[str]: The kind of argument, for example ``FIXED_TYPE`` or + ``ANY_TYPE``. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#Argument.FIELDS.argument_kind + """ + return self._properties.get(self._PROPERTY_TO_API_FIELD["kind"]) + + @kind.setter + def kind(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["kind"]] = value + + @property + def mode(self): + """Optional[str]: The input/output mode of the argument.""" + return self._properties.get(self._PROPERTY_TO_API_FIELD["mode"]) + + @mode.setter + def mode(self, value): + self._properties[self._PROPERTY_TO_API_FIELD["mode"]] = value + + @property + def data_type(self): + """Optional[google.cloud.bigquery.StandardSqlDataType]: Type + of a variable, e.g., a function argument. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#Argument.FIELDS.data_type + """ + resource = self._properties.get(self._PROPERTY_TO_API_FIELD["data_type"]) + if not resource: + return resource + + return StandardSqlDataType.from_api_repr(resource) + + @data_type.setter + def data_type(self, value): + if value: + resource = value.to_api_repr() + else: + resource = None + self._properties[self._PROPERTY_TO_API_FIELD["data_type"]] = resource + + @classmethod + def from_api_repr(cls, resource: dict) -> "RoutineArgument": + """Factory: construct a routine argument given its API representation. + + Args: + resource (Dict[str, object]): Resource, as returned from the API. + + Returns: + google.cloud.bigquery.routine.RoutineArgument: + Python object, as parsed from ``resource``. + """ + ref = cls() + ref._properties = resource + return ref + + def to_api_repr(self) -> dict: + """Construct the API resource representation of this routine argument. + + Returns: + Dict[str, object]: Routine argument represented as an API resource. + """ + return self._properties + + def __eq__(self, other): + if not isinstance(other, RoutineArgument): + return NotImplemented + return self._properties == other._properties + + def __ne__(self, other): + return not self == other + + def __repr__(self): + all_properties = [ + "{}={}".format(property_name, repr(getattr(self, property_name))) + for property_name in sorted(self._PROPERTY_TO_API_FIELD) + ] + return "RoutineArgument({})".format(", ".join(all_properties)) + + +class RoutineReference(object): + """A pointer to a routine. + + See: + https://cloud.google.com/bigquery/docs/reference/rest/v2/routines#routinereference + """ + + def __init__(self): + self._properties = {} + + @property + def project(self): + """str: ID of the project containing the routine.""" + return self._properties.get("projectId", "") + + @property + def dataset_id(self): + """str: ID of dataset containing the routine.""" + return self._properties.get("datasetId", "") + + @property + def routine_id(self): + """str: The routine ID.""" + return self._properties.get("routineId", "") + + @property + def path(self): + """str: URL path for the routine's APIs.""" + return "/projects/%s/datasets/%s/routines/%s" % ( + self.project, + self.dataset_id, + self.routine_id, + ) + + @classmethod + def from_api_repr(cls, resource: dict) -> "RoutineReference": + """Factory: construct a routine reference given its API representation. + + Args: + resource (Dict[str, object]): + Routine reference representation returned from the API. + + Returns: + google.cloud.bigquery.routine.RoutineReference: + Routine reference parsed from ``resource``. + """ + ref = cls() + ref._properties = resource + return ref + + @classmethod + def from_string( + cls, routine_id: str, default_project: Optional[str] = None + ) -> "RoutineReference": + """Factory: construct a routine reference from routine ID string. + + Args: + routine_id (str): + A routine ID in standard SQL format. If ``default_project`` + is not specified, this must included a project ID, dataset + ID, and routine ID, each separated by ``.``. + default_project (Optional[str]): + The project ID to use when ``routine_id`` does not + include a project ID. + + Returns: + google.cloud.bigquery.routine.RoutineReference: + Routine reference parsed from ``routine_id``. + + Raises: + ValueError: + If ``routine_id`` is not a fully-qualified routine ID in + standard SQL format. + """ + proj, dset, routine = _helpers._parse_3_part_id( + routine_id, default_project=default_project, property_name="routine_id" + ) + return cls.from_api_repr( + {"projectId": proj, "datasetId": dset, "routineId": routine} + ) + + def to_api_repr(self) -> dict: + """Construct the API resource representation of this routine reference. + + Returns: + Dict[str, object]: Routine reference represented as an API resource. + """ + return self._properties + + def __eq__(self, other): + """Two RoutineReferences are equal if they point to the same routine.""" + if not isinstance(other, RoutineReference): + return NotImplemented + return str(self) == str(other) + + def __hash__(self): + return hash(str(self)) + + def __ne__(self, other): + return not self == other + + def __repr__(self): + return "RoutineReference.from_string('{}')".format(str(self)) + + def __str__(self): + """String representation of the reference. + + This is a fully-qualified ID, including the project ID and dataset ID. + """ + return "{}.{}.{}".format(self.project, self.dataset_id, self.routine_id) + + +class RemoteFunctionOptions(object): + """Configuration options for controlling remote BigQuery functions.""" + + _PROPERTY_TO_API_FIELD = { + "endpoint": "endpoint", + "connection": "connection", + "max_batching_rows": "maxBatchingRows", + "user_defined_context": "userDefinedContext", + } + + def __init__( + self, + endpoint=None, + connection=None, + max_batching_rows=None, + user_defined_context=None, + _properties=None, + ) -> None: + if _properties is None: + _properties = {} + self._properties = _properties + + if endpoint is not None: + self.endpoint = endpoint + if connection is not None: + self.connection = connection + if max_batching_rows is not None: + self.max_batching_rows = max_batching_rows + if user_defined_context is not None: + self.user_defined_context = user_defined_context + + @property + def connection(self): + """string: Fully qualified name of the user-provided connection object which holds the authentication information to send requests to the remote service. + + Format is "projects/{projectId}/locations/{locationId}/connections/{connectionId}" + """ + return _helpers._str_or_none(self._properties.get("connection")) + + @connection.setter + def connection(self, value): + self._properties["connection"] = _helpers._str_or_none(value) + + @property + def endpoint(self): + """string: Endpoint of the user-provided remote service + + Example: "https://us-east1-my_gcf_project.cloudfunctions.net/remote_add" + """ + return _helpers._str_or_none(self._properties.get("endpoint")) + + @endpoint.setter + def endpoint(self, value): + self._properties["endpoint"] = _helpers._str_or_none(value) + + @property + def max_batching_rows(self): + """int64: Max number of rows in each batch sent to the remote service. + + If absent or if 0, BigQuery dynamically decides the number of rows in a batch. + """ + return _helpers._int_or_none(self._properties.get("maxBatchingRows")) + + @max_batching_rows.setter + def max_batching_rows(self, value): + self._properties["maxBatchingRows"] = _helpers._str_or_none(value) + + @property + def user_defined_context(self): + """Dict[str, str]: User-defined context as a set of key/value pairs, + which will be sent as function invocation context together with + batched arguments in the requests to the remote service. The total + number of bytes of keys and values must be less than 8KB. + """ + return self._properties.get("userDefinedContext") + + @user_defined_context.setter + def user_defined_context(self, value): + if not isinstance(value, dict): + raise ValueError("value must be dictionary") + self._properties["userDefinedContext"] = value + + @classmethod + def from_api_repr(cls, resource: dict) -> "RemoteFunctionOptions": + """Factory: construct remote function options given its API representation. + + Args: + resource (Dict[str, object]): Resource, as returned from the API. + + Returns: + google.cloud.bigquery.routine.RemoteFunctionOptions: + Python object, as parsed from ``resource``. + """ + ref = cls() + ref._properties = resource + return ref + + def to_api_repr(self) -> dict: + """Construct the API resource representation of this RemoteFunctionOptions. + + Returns: + Dict[str, object]: Remote function options represented as an API resource. + """ + return self._properties + + def __eq__(self, other): + if not isinstance(other, RemoteFunctionOptions): + return NotImplemented + return self._properties == other._properties + + def __ne__(self, other): + return not self == other + + def __repr__(self): + all_properties = [ + "{}={}".format(property_name, repr(getattr(self, property_name))) + for property_name in sorted(self._PROPERTY_TO_API_FIELD) + ] + return "RemoteFunctionOptions({})".format(", ".join(all_properties)) + + +class ExternalRuntimeOptions(object): + """Options for the runtime of the external system. + + Args: + container_memory (str): + Optional. Amount of memory provisioned for a Python UDF container + instance. Format: {number}{unit} where unit is one of "M", "G", "Mi" + and "Gi" (e.g. 1G, 512Mi). If not specified, the default value is + 512Mi. For more information, see `Configure container limits for + Python UDFs `_ + container_cpu (int): + Optional. Amount of CPU provisioned for a Python UDF container + instance. For more information, see `Configure container limits + for Python UDFs `_ + runtime_connection (str): + Optional. Fully qualified name of the connection whose service account + will be used to execute the code in the container. Format: + "projects/{projectId}/locations/{locationId}/connections/{connectionId}" + max_batching_rows (int): + Optional. Maximum number of rows in each batch sent to the external + runtime. If absent or if 0, BigQuery dynamically decides the number of + rows in a batch. + runtime_version (str): + Optional. Language runtime version. Example: python-3.11. + """ + + _PROPERTY_TO_API_FIELD = { + "container_memory": "containerMemory", + "container_cpu": "containerCpu", + "runtime_connection": "runtimeConnection", + "max_batching_rows": "maxBatchingRows", + "runtime_version": "runtimeVersion", + } + + def __init__( + self, + container_memory: Optional[str] = None, + container_cpu: Optional[int] = None, + runtime_connection: Optional[str] = None, + max_batching_rows: Optional[int] = None, + runtime_version: Optional[str] = None, + _properties: Optional[Dict] = None, + ) -> None: + if _properties is None: + _properties = {} + self._properties = _properties + + if container_memory is not None: + self.container_memory = container_memory + if container_cpu is not None: + self.container_cpu = container_cpu + if runtime_connection is not None: + self.runtime_connection = runtime_connection + if max_batching_rows is not None: + self.max_batching_rows = max_batching_rows + if runtime_version is not None: + self.runtime_version = runtime_version + + @property + def container_memory(self) -> Optional[str]: + """Optional. Amount of memory provisioned for a Python UDF container instance.""" + return _helpers._str_or_none(self._properties.get("containerMemory")) + + @container_memory.setter + def container_memory(self, value: Optional[str]): + if value is not None and not isinstance(value, str): + raise ValueError("container_memory must be a string or None.") + self._properties["containerMemory"] = value + + @property + def container_cpu(self) -> Optional[int]: + """Optional. Amount of CPU provisioned for a Python UDF container instance.""" + return _helpers._int_or_none(self._properties.get("containerCpu")) + + @container_cpu.setter + def container_cpu(self, value: Optional[int]): + if value is not None and not isinstance(value, int): + raise ValueError("container_cpu must be an integer or None.") + self._properties["containerCpu"] = value + + @property + def runtime_connection(self) -> Optional[str]: + """Optional. Fully qualified name of the connection.""" + return _helpers._str_or_none(self._properties.get("runtimeConnection")) + + @runtime_connection.setter + def runtime_connection(self, value: Optional[str]): + if value is not None and not isinstance(value, str): + raise ValueError("runtime_connection must be a string or None.") + self._properties["runtimeConnection"] = value + + @property + def max_batching_rows(self) -> Optional[int]: + """Optional. Maximum number of rows in each batch sent to the external runtime.""" + return typing.cast( + int, _helpers._int_or_none(self._properties.get("maxBatchingRows")) + ) + + @max_batching_rows.setter + def max_batching_rows(self, value: Optional[int]): + if value is not None and not isinstance(value, int): + raise ValueError("max_batching_rows must be an integer or None.") + self._properties["maxBatchingRows"] = _helpers._str_or_none(value) + + @property + def runtime_version(self) -> Optional[str]: + """Optional. Language runtime version.""" + return _helpers._str_or_none(self._properties.get("runtimeVersion")) + + @runtime_version.setter + def runtime_version(self, value: Optional[str]): + if value is not None and not isinstance(value, str): + raise ValueError("runtime_version must be a string or None.") + self._properties["runtimeVersion"] = value + + @classmethod + def from_api_repr(cls, resource: dict) -> "ExternalRuntimeOptions": + """Factory: construct external runtime options given its API representation. + Args: + resource (Dict[str, object]): Resource, as returned from the API. + Returns: + google.cloud.bigquery.routine.ExternalRuntimeOptions: + Python object, as parsed from ``resource``. + """ + ref = cls() + ref._properties = resource + return ref + + def to_api_repr(self) -> dict: + """Construct the API resource representation of this ExternalRuntimeOptions. + Returns: + Dict[str, object]: External runtime options represented as an API resource. + """ + return self._properties + + def __eq__(self, other): + if not isinstance(other, ExternalRuntimeOptions): + return NotImplemented + return self._properties == other._properties + + def __ne__(self, other): + return not self == other + + def __repr__(self): + all_properties = [ + "{}={}".format(property_name, repr(getattr(self, property_name))) + for property_name in sorted(self._PROPERTY_TO_API_FIELD) + ] + return "ExternalRuntimeOptions({})".format(", ".join(all_properties)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f964ee4a38467b34773c1ef9e2357f5f3ca2acd0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_helpers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f6c2fd1b5680f47e125f99ca0ec9149c5762dcf Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_helpers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_http.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67165a084b420920fa7d2b60d11a18a272f54ad9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_http.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_opentelemetry_tracing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_opentelemetry_tracing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69a79c3191a41594b640169f04a0bc798a19c9f4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_opentelemetry_tracing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_signing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_signing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..880b8a261a393e6c55ab3a5964b13ec052b2083f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/_signing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/acl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/acl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcf9579899a492b12e363faf0bfd93f1a5372f49 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/acl.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/batch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/batch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e33fffe0e075ec1a3f3188e8c72e8cc4936d308 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/batch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d88e0326deb1b1ef53f9eb3a371baffc94da2e2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/client.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..965689806fe963db15f45be5773f91ae3cb6fa13 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/constants.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..481374d3f8b9976883e47ce0b036880990ce75f7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/exceptions.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/fileio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/fileio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed0db07b5b310a33bca4c0057173e43c428d49c7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/fileio.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/grpc_client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/grpc_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80716c531aa9fe535384e5b98e1fc694f386d196 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/grpc_client.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/hmac_key.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/hmac_key.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43373805fc1eb80284698fe41747735279ea1bb7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/hmac_key.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/iam.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/iam.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b4915f1e739e52a5b38c86ef6e32931ea1adde8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/iam.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/ip_filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/ip_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f014013c1a0d2fcbbac6d6c188680ee2d3c5918c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/ip_filter.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/notification.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/notification.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea1e8ea5465b297015ff1d650483c9646230c5f5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/notification.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/retry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/retry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3f2b4de6b63b9f1b6f87bb1434b1c5726cf39d7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/retry.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/transfer_manager.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/transfer_manager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18a2f4c78d8147461e78cb5f35e5478366763ca8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/transfer_manager.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c46cfd010a9890fd301b6010abbedaab7592be1b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/__pycache__/version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_experimental/__pycache__/grpc_client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_experimental/__pycache__/grpc_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f698516c9903d85ae100a709f7918c4f470cfd9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_experimental/__pycache__/grpc_client.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_experimental/grpc_client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_experimental/grpc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..99ecbe04443c3e8f6ccc48b6a3f00122902f5e52 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_experimental/grpc_client.py @@ -0,0 +1,11 @@ +import warnings + +# Import everything from the new stable module +from google.cloud.storage.grpc_client import * # noqa + +warnings.warn( + "google.cloud.storage._experimental.grpc_client has been moved to google.cloud.storage.grpc_client. " + "Please update your imports.", + DeprecationWarning, + stacklevel=2, +) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..edab8f51d1aed7621542d12acd77965b81126328 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/__init__.py @@ -0,0 +1,34 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for Google Media Downloads and Resumable Uploads. + +=========== +Subpackages +=========== + +Each subpackage is tailored to a specific transport library: + +* the :mod:`~google.cloud.storage._media.requests` subpackage uses the ``requests`` + transport library. + +.. _requests: http://docs.python-requests.org/ +""" + +from google.cloud.storage._media.common import UPLOAD_CHUNK_SIZE + + +__all__ = [ + "UPLOAD_CHUNK_SIZE", +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_download.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_download.py new file mode 100644 index 0000000000000000000000000000000000000000..422b98041a5517f85bb8ef9397cf1f03d6d21a22 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_download.py @@ -0,0 +1,625 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Virtual bases classes for downloading media from Google APIs.""" + + +import http.client +import re + +from google.cloud.storage._media import _helpers +from google.cloud.storage.exceptions import InvalidResponse +from google.cloud.storage.retry import DEFAULT_RETRY + + +_CONTENT_RANGE_RE = re.compile( + r"bytes (?P\d+)-(?P\d+)/(?P\d+)", + flags=re.IGNORECASE, +) +_ACCEPTABLE_STATUS_CODES = (http.client.OK, http.client.PARTIAL_CONTENT) +_GET = "GET" +_ZERO_CONTENT_RANGE_HEADER = "bytes */0" + + +class DownloadBase(object): + """Base class for download helpers. + + Defines core shared behavior across different download types. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. + end (int): The last byte in a range to be downloaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + retry (Optional[google.api_core.retry.Retry]): How to retry the RPC. + A None value will disable retries. A google.api_core.retry.Retry + value will enable retries, and the object will configure backoff and + timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + """ + + def __init__( + self, + media_url, + stream=None, + start=None, + end=None, + headers=None, + retry=DEFAULT_RETRY, + ): + self.media_url = media_url + self._stream = stream + self.start = start + self.end = end + if headers is None: + headers = {} + self._headers = headers + self._finished = False + self._retry_strategy = retry + + @property + def finished(self): + """bool: Flag indicating if the download has completed.""" + return self._finished + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class Download(DownloadBase): + """Helper to manage downloading a resource from a Google API. + + "Slices" of the resource can be retrieved by specifying a range + with ``start`` and / or ``end``. However, in typical usage, neither + ``start`` nor ``end`` is expected to be provided. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. If not + provided, but ``end`` is provided, will download from the + beginning to ``end`` of the media. + end (int): The last byte in a range to be downloaded. If not + provided, but ``start`` is provided, will download from the + ``start`` to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum (Optional[str]): The type of checksum to compute to verify + the integrity of the object. The response headers must contain + a checksum of the requested type. If the headers lack an + appropriate checksum (for instance in the case of transcoded or + ranged downloads where the remote service does not know the + correct checksum) an INFO-level log will be emitted. Supported + values are "md5", "crc32c", "auto" and None. The default is "auto", + which will try to detect if the C extension for crc32c is installed + and fall back to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + single_shot_download (Optional[bool]): If true, download the object in a single request. + Caution: Enabling this will increase the memory overload for your application. + Please enable this as per your use case. + + """ + + def __init__( + self, + media_url, + stream=None, + start=None, + end=None, + headers=None, + checksum="auto", + retry=DEFAULT_RETRY, + single_shot_download=False, + ): + super(Download, self).__init__( + media_url, stream=stream, start=start, end=end, headers=headers, retry=retry + ) + self.checksum = checksum + if self.checksum == "auto": + self.checksum = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + self.single_shot_download = single_shot_download + self._bytes_downloaded = 0 + self._expected_checksum = None + self._checksum_object = None + self._object_generation = None + + def _prepare_request(self): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always GET) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + Raises: + ValueError: If the current :class:`Download` has already + finished. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("A download can only be used once.") + + add_bytes_range(self.start, self.end, self._headers) + return _GET, self.media_url, None, self._headers + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Tombstone the current Download so it cannot be used again. + self._finished = True + _helpers.require_status_code( + response, _ACCEPTABLE_STATUS_CODES, self._get_status_code + ) + + def consume(self, transport, timeout=None): + """Consume the resource to be downloaded. + + If a ``stream`` is attached to this download, then the downloaded + resource will be written to the stream. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class ChunkedDownload(DownloadBase): + """Download a resource in chunks from a Google API. + + Args: + media_url (str): The URL containing the media to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each + request. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + will be used to concatenate chunks of the resource as they are + downloaded. + start (int): The first byte in a range to be downloaded. If not + provided, defaults to ``0``. + end (int): The last byte in a range to be downloaded. If not + provided, will download to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with each request, e.g. headers for data encryption + key headers. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each request. + + Raises: + ValueError: If ``start`` is negative. + """ + + def __init__( + self, + media_url, + chunk_size, + stream, + start=0, + end=None, + headers=None, + retry=DEFAULT_RETRY, + ): + if start < 0: + raise ValueError( + "On a chunked download the starting " "value cannot be negative." + ) + super(ChunkedDownload, self).__init__( + media_url, + stream=stream, + start=start, + end=end, + headers=headers, + retry=retry, + ) + self.chunk_size = chunk_size + self._bytes_downloaded = 0 + self._total_bytes = None + self._invalid = False + + @property + def bytes_downloaded(self): + """int: Number of bytes that have been downloaded.""" + return self._bytes_downloaded + + @property + def total_bytes(self): + """Optional[int]: The total number of bytes to be downloaded.""" + return self._total_bytes + + @property + def invalid(self): + """bool: Indicates if the download is in an invalid state. + + This will occur if a call to :meth:`consume_next_chunk` fails. + """ + return self._invalid + + def _get_byte_range(self): + """Determines the byte range for the next request. + + Returns: + Tuple[int, int]: The pair of begin and end byte for the next + chunked request. + """ + curr_start = self.start + self.bytes_downloaded + curr_end = curr_start + self.chunk_size - 1 + # Make sure ``curr_end`` does not exceed ``end``. + if self.end is not None: + curr_end = min(curr_end, self.end) + # Make sure ``curr_end`` does not exceed ``total_bytes - 1``. + if self.total_bytes is not None: + curr_end = min(curr_end, self.total_bytes - 1) + return curr_start, curr_end + + def _prepare_request(self): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used multiple times, so ``headers`` will + be mutated in between requests. However, we don't make a copy + since the same keys are being updated. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always GET) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + Raises: + ValueError: If the current download has finished. + ValueError: If the current download is invalid. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("Download has finished.") + if self.invalid: + raise ValueError("Download is invalid and cannot be re-used.") + + curr_start, curr_end = self._get_byte_range() + add_bytes_range(curr_start, curr_end, self._headers) + return _GET, self.media_url, None, self._headers + + def _make_invalid(self): + """Simple setter for ``invalid``. + + This is intended to be passed along as a callback to helpers that + raise an exception so they can mark this instance as invalid before + raising. + """ + self._invalid = True + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to write + a chunk to ``stream``. However, this will (almost) certainly not be + network I/O. + + Updates the current state after consuming a chunk. First, + increments ``bytes_downloaded`` by the number of bytes in the + ``content-length`` header. + + If ``total_bytes`` is already set, this assumes (but does not check) + that we already have the correct value and doesn't bother to check + that it agrees with the headers. + + We expect the **total** length to be in the ``content-range`` header, + but this header is only present on requests which sent the ``range`` + header. This response header should be of the form + ``bytes {start}-{end}/{total}`` and ``{end} - {start} + 1`` + should be the same as the ``Content-Length``. + + Args: + response (object): The HTTP response object (need headers). + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the number + of bytes in the body doesn't match the content length header. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Verify the response before updating the current instance. + if _check_for_zero_content_range( + response, self._get_status_code, self._get_headers + ): + self._finished = True + return + + _helpers.require_status_code( + response, + _ACCEPTABLE_STATUS_CODES, + self._get_status_code, + callback=self._make_invalid, + ) + headers = self._get_headers(response) + response_body = self._get_body(response) + + start_byte, end_byte, total_bytes = get_range_info( + response, self._get_headers, callback=self._make_invalid + ) + + transfer_encoding = headers.get("transfer-encoding") + + if transfer_encoding is None: + content_length = _helpers.header_required( + response, + "content-length", + self._get_headers, + callback=self._make_invalid, + ) + num_bytes = int(content_length) + if len(response_body) != num_bytes: + self._make_invalid() + raise InvalidResponse( + response, + "Response is different size than content-length", + "Expected", + num_bytes, + "Received", + len(response_body), + ) + else: + # 'content-length' header not allowed with chunked encoding. + num_bytes = end_byte - start_byte + 1 + + # First update ``bytes_downloaded``. + self._bytes_downloaded += num_bytes + # If the end byte is past ``end`` or ``total_bytes - 1`` we are done. + if self.end is not None and end_byte >= self.end: + self._finished = True + elif end_byte >= total_bytes - 1: + self._finished = True + # NOTE: We only use ``total_bytes`` if not already known. + if self.total_bytes is None: + self._total_bytes = total_bytes + # Write the response body to the stream. + self._stream.write(response_body) + + def consume_next_chunk(self, transport, timeout=None): + """Consume the next chunk of the resource to be downloaded. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +def add_bytes_range(start, end, headers): + """Add a bytes range to a header dictionary. + + Some possible inputs and the corresponding bytes ranges:: + + >>> headers = {} + >>> add_bytes_range(None, None, headers) + >>> headers + {} + >>> add_bytes_range(500, 999, headers) + >>> headers['range'] + 'bytes=500-999' + >>> add_bytes_range(None, 499, headers) + >>> headers['range'] + 'bytes=0-499' + >>> add_bytes_range(-500, None, headers) + >>> headers['range'] + 'bytes=-500' + >>> add_bytes_range(9500, None, headers) + >>> headers['range'] + 'bytes=9500-' + + Args: + start (Optional[int]): The first byte in a range. Can be zero, + positive, negative or :data:`None`. + end (Optional[int]): The last byte in a range. Assumed to be + positive. + headers (Mapping[str, str]): A headers mapping which can have the + bytes range added if at least one of ``start`` or ``end`` + is not :data:`None`. + """ + if start is None: + if end is None: + # No range to add. + return + else: + # NOTE: This assumes ``end`` is non-negative. + bytes_range = "0-{:d}".format(end) + else: + if end is None: + if start < 0: + bytes_range = "{:d}".format(start) + else: + bytes_range = "{:d}-".format(start) + else: + # NOTE: This is invalid if ``start < 0``. + bytes_range = "{:d}-{:d}".format(start, end) + + headers[_helpers.RANGE_HEADER] = "bytes=" + bytes_range + + +def get_range_info(response, get_headers, callback=_helpers.do_nothing): + """Get the start, end and total bytes from a content range header. + + Args: + response (object): An HTTP response object. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + Tuple[int, int, int]: The start byte, end byte and total bytes. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the + ``Content-Range`` header is not of the form + ``bytes {start}-{end}/{total}``. + """ + content_range = _helpers.header_required( + response, _helpers.CONTENT_RANGE_HEADER, get_headers, callback=callback + ) + match = _CONTENT_RANGE_RE.match(content_range) + if match is None: + callback() + raise InvalidResponse( + response, + "Unexpected content-range header", + content_range, + 'Expected to be of the form "bytes {start}-{end}/{total}"', + ) + + return ( + int(match.group("start_byte")), + int(match.group("end_byte")), + int(match.group("total_bytes")), + ) + + +def _check_for_zero_content_range(response, get_status_code, get_headers): + """Validate if response status code is 416 and content range is zero. + + This is the special case for handling zero bytes files. + + Args: + response (object): An HTTP response object. + get_status_code (Callable[Any, int]): Helper to get a status code + from a response. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + + Returns: + bool: True if content range total bytes is zero, false otherwise. + """ + if get_status_code(response) == http.client.REQUESTED_RANGE_NOT_SATISFIABLE: + content_range = _helpers.header_required( + response, + _helpers.CONTENT_RANGE_HEADER, + get_headers, + callback=_helpers.do_nothing, + ) + if content_range == _ZERO_CONTENT_RANGE_HEADER: + return True + return False diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_helpers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c07101edabbab8db274515d82dade061812a27f5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_helpers.py @@ -0,0 +1,383 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared utilities used by both downloads and uploads.""" + +from __future__ import absolute_import + +import base64 +import hashlib +import logging + +from urllib.parse import parse_qs +from urllib.parse import urlencode +from urllib.parse import urlsplit +from urllib.parse import urlunsplit + +from google.cloud.storage import retry +from google.cloud.storage.exceptions import InvalidResponse + + +RANGE_HEADER = "range" +CONTENT_RANGE_HEADER = "content-range" +CONTENT_ENCODING_HEADER = "content-encoding" + +_SLOW_CRC32C_WARNING = ( + "Currently using crcmod in pure python form. This is a slow " + "implementation. Python 3 has a faster implementation, `google-crc32c`, " + "which will be used if it is installed." +) +_GENERATION_HEADER = "x-goog-generation" +_HASH_HEADER = "x-goog-hash" +_STORED_CONTENT_ENCODING_HEADER = "x-goog-stored-content-encoding" + +_MISSING_CHECKSUM = """\ +No {checksum_type} checksum was returned from the service while downloading {} +(which happens for composite objects), so client-side content integrity +checking is not being performed.""" +_LOGGER = logging.getLogger(__name__) + + +def do_nothing(): + """Simple default callback.""" + + +def header_required(response, name, get_headers, callback=do_nothing): + """Checks that a specific header is in a headers dictionary. + + Args: + response (object): An HTTP response object, expected to have a + ``headers`` attribute that is a ``Mapping[str, str]``. + name (str): The name of a required header. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + str: The desired header. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the header + is missing. + """ + headers = get_headers(response) + if name not in headers: + callback() + raise InvalidResponse(response, "Response headers must contain header", name) + + return headers[name] + + +def require_status_code(response, status_codes, get_status_code, callback=do_nothing): + """Require a response has a status code among a list. + + Args: + response (object): The HTTP response object. + status_codes (tuple): The acceptable status codes. + get_status_code (Callable[Any, int]): Helper to get a status code + from a response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + int: The status code. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status code + is not one of the values in ``status_codes``. + """ + status_code = get_status_code(response) + if status_code not in status_codes: + if status_code not in retry._RETRYABLE_STATUS_CODES: + callback() + raise InvalidResponse( + response, + "Request failed with status code", + status_code, + "Expected one of", + *status_codes + ) + return status_code + + +def _get_metadata_key(checksum_type): + if checksum_type == "md5": + return "md5Hash" + else: + return checksum_type + + +def prepare_checksum_digest(digest_bytestring): + """Convert a checksum object into a digest encoded for an HTTP header. + + Args: + bytes: A checksum digest bytestring. + + Returns: + str: A base64 string representation of the input. + """ + encoded_digest = base64.b64encode(digest_bytestring) + # NOTE: ``b64encode`` returns ``bytes``, but HTTP headers expect ``str``. + return encoded_digest.decode("utf-8") + + +def _get_expected_checksum(response, get_headers, media_url, checksum_type): + """Get the expected checksum and checksum object for the download response. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + media_url (str): The URL containing the media to be downloaded. + checksum_type Optional(str): The checksum type to read from the headers, + exactly as it will appear in the headers (case-sensitive). Must be + "md5", "crc32c" or None. + + Returns: + Tuple (Optional[str], object): The expected checksum of the response, + if it can be detected from the ``X-Goog-Hash`` header, and the + appropriate checksum object for the expected checksum. + """ + if checksum_type not in ["md5", "crc32c", None]: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + elif checksum_type in ["md5", "crc32c"]: + headers = get_headers(response) + expected_checksum = _parse_checksum_header( + headers.get(_HASH_HEADER), response, checksum_label=checksum_type + ) + + if expected_checksum is None: + msg = _MISSING_CHECKSUM.format( + media_url, checksum_type=checksum_type.upper() + ) + _LOGGER.info(msg) + checksum_object = _DoNothingHash() + else: + checksum_object = _get_checksum_object(checksum_type) + else: + expected_checksum = None + checksum_object = _DoNothingHash() + + return (expected_checksum, checksum_object) + + +def _get_uploaded_checksum_from_headers(response, get_headers, checksum_type): + """Get the computed checksum and checksum object from the response headers. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + checksum_type Optional(str): The checksum type to read from the headers, + exactly as it will appear in the headers (case-sensitive). Must be + "md5", "crc32c" or None. + + Returns: + Tuple (Optional[str], object): The checksum of the response, + if it can be detected from the ``X-Goog-Hash`` header, and the + appropriate checksum object for the expected checksum. + """ + if checksum_type not in ["md5", "crc32c", None]: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + elif checksum_type in ["md5", "crc32c"]: + headers = get_headers(response) + remote_checksum = _parse_checksum_header( + headers.get(_HASH_HEADER), response, checksum_label=checksum_type + ) + else: + remote_checksum = None + + return remote_checksum + + +def _parse_checksum_header(header_value, response, checksum_label): + """Parses the checksum header from an ``X-Goog-Hash`` value. + + .. _header reference: https://cloud.google.com/storage/docs/\ + xml-api/reference-headers#xgooghash + + Expects ``header_value`` (if not :data:`None`) to be in one of the three + following formats: + + * ``crc32c=n03x6A==`` + * ``md5=Ojk9c3dhfxgoKVVHYwFbHQ==`` + * ``crc32c=n03x6A==,md5=Ojk9c3dhfxgoKVVHYwFbHQ==`` + + See the `header reference`_ for more information. + + Args: + header_value (Optional[str]): The ``X-Goog-Hash`` header from + a download response. + response (~requests.Response): The HTTP response object. + checksum_label (str): The label of the header value to read, as in the + examples above. Typically "md5" or "crc32c" + + Returns: + Optional[str]: The expected checksum of the response, if it + can be detected from the ``X-Goog-Hash`` header; otherwise, None. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If there are + multiple checksums of the requested type in ``header_value``. + """ + if header_value is None: + return None + + matches = [] + for checksum in header_value.split(","): + name, value = checksum.split("=", 1) + # Official docs say "," is the separator, but real-world responses have encountered ", " + if name.lstrip() == checksum_label: + matches.append(value) + + if len(matches) == 0: + return None + elif len(matches) == 1: + return matches[0] + else: + raise InvalidResponse( + response, + "X-Goog-Hash header had multiple ``{}`` values.".format(checksum_label), + header_value, + matches, + ) + + +def _get_checksum_object(checksum_type): + """Respond with a checksum object for a supported type, if not None. + + Raises ValueError if checksum_type is unsupported. + """ + if checksum_type == "md5": + return hashlib.md5() + elif checksum_type == "crc32c": + # In order to support platforms that don't have google_crc32c + # support, only perform the import on demand. + import google_crc32c + + return google_crc32c.Checksum() + elif checksum_type is None: + return None + else: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + + +def _is_crc32c_available_and_fast(): + """Return True if the google_crc32c C extension is installed. + + Return False if either the package is not installed, or if only the + pure-Python version is installed. + """ + try: + import google_crc32c + + if google_crc32c.implementation == "c": + return True + except Exception: + pass + return False + + +def _parse_generation_header(response, get_headers): + """Parses the generation header from an ``X-Goog-Generation`` value. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + + Returns: + Optional[long]: The object generation from the response, if it + can be detected from the ``X-Goog-Generation`` header; otherwise, None. + """ + headers = get_headers(response) + object_generation = headers.get(_GENERATION_HEADER, None) + + if object_generation is None: + return None + else: + return int(object_generation) + + +def _get_generation_from_url(media_url): + """Retrieve the object generation query param specified in the media url. + + Args: + media_url (str): The URL containing the media to be downloaded. + + Returns: + long: The object generation from the media url if exists; otherwise, None. + """ + + _, _, _, query, _ = urlsplit(media_url) + query_params = parse_qs(query) + object_generation = query_params.get("generation", None) + + if object_generation is None: + return None + else: + return int(object_generation[0]) + + +def add_query_parameters(media_url, query_params): + """Add query parameters to a base url. + + Args: + media_url (str): The URL containing the media to be downloaded. + query_params (dict): Names and values of the query parameters to add. + + Returns: + str: URL with additional query strings appended. + """ + + if len(query_params) == 0: + return media_url + + scheme, netloc, path, query, frag = urlsplit(media_url) + params = parse_qs(query) + new_params = {**params, **query_params} + query = urlencode(new_params, doseq=True) + return urlunsplit((scheme, netloc, path, query, frag)) + + +def _is_decompressive_transcoding(response, get_headers): + """Returns True if the object was served decompressed. This happens when the + "x-goog-stored-content-encoding" header is "gzip" and "content-encoding" header + is not "gzip". See more at: https://cloud.google.com/storage/docs/transcoding#transcoding_and_gzip + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + Returns: + bool: Returns True if decompressive transcoding has occurred; otherwise, False. + """ + headers = get_headers(response) + return ( + headers.get(_STORED_CONTENT_ENCODING_HEADER) == "gzip" + and headers.get(CONTENT_ENCODING_HEADER) != "gzip" + ) + + +class _DoNothingHash(object): + """Do-nothing hash object. + + Intended as a stand-in for ``hashlib.md5`` or a crc32c checksum + implementation in cases where it isn't necessary to compute the hash. + """ + + def update(self, unused_chunk): + """Do-nothing ``update`` method. + + Intended to match the interface of ``hashlib.md5`` and other checksums. + + Args: + unused_chunk (bytes): A chunk of data. + """ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_upload.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..4a919d18ac84ce7d49708b7233cfc4344fca8080 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/_upload.py @@ -0,0 +1,1647 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Virtual bases classes for uploading media via Google APIs. + +Supported here are: + +* simple (media) uploads +* multipart uploads that contain both metadata and a small file as payload +* resumable uploads (with metadata as well) +""" + +import http.client +import json +import os +import random +import re +import sys +import urllib.parse + +from google.cloud.storage._media import _helpers +from google.cloud.storage._media import UPLOAD_CHUNK_SIZE +from google.cloud.storage.exceptions import InvalidResponse +from google.cloud.storage.exceptions import DataCorruption +from google.cloud.storage.retry import DEFAULT_RETRY + +from xml.etree import ElementTree + + +_CONTENT_TYPE_HEADER = "content-type" +_CONTENT_RANGE_TEMPLATE = "bytes {:d}-{:d}/{:d}" +_RANGE_UNKNOWN_TEMPLATE = "bytes {:d}-{:d}/*" +_EMPTY_RANGE_TEMPLATE = "bytes */{:d}" +_BOUNDARY_WIDTH = len(str(sys.maxsize - 1)) +_BOUNDARY_FORMAT = "==============={{:0{:d}d}}==".format(_BOUNDARY_WIDTH) +_MULTIPART_SEP = b"--" +_CRLF = b"\r\n" +_MULTIPART_BEGIN = b"\r\ncontent-type: application/json; charset=UTF-8\r\n\r\n" +_RELATED_HEADER = b'multipart/related; boundary="' +_BYTES_RANGE_RE = re.compile(r"bytes=0-(?P\d+)", flags=re.IGNORECASE) +_STREAM_ERROR_TEMPLATE = ( + "Bytes stream is in unexpected state. " + "The local stream has had {:d} bytes read from it while " + "{:d} bytes have already been updated (they should match)." +) +_STREAM_READ_PAST_TEMPLATE = ( + "{:d} bytes have been read from the stream, which exceeds " + "the expected total {:d}." +) +_DELETE = "DELETE" +_POST = "POST" +_PUT = "PUT" +_UPLOAD_CHECKSUM_MISMATCH_MESSAGE = ( + "The computed ``{}`` checksum, ``{}``, and the checksum reported by the " + "remote host, ``{}``, did not match." +) +_UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE = ( + "Response metadata had no ``{}`` value; checksum could not be validated." +) +_UPLOAD_HEADER_NO_APPROPRIATE_CHECKSUM_MESSAGE = ( + "Response headers had no ``{}`` value; checksum could not be validated." +) +_MPU_INITIATE_QUERY = "?uploads" +_MPU_PART_QUERY_TEMPLATE = "?partNumber={part}&uploadId={upload_id}" +_S3_COMPAT_XML_NAMESPACE = "{http://s3.amazonaws.com/doc/2006-03-01/}" +_UPLOAD_ID_NODE = "UploadId" +_MPU_FINAL_QUERY_TEMPLATE = "?uploadId={upload_id}" + + +class UploadBase(object): + """Base class for upload helpers. + + Defines core shared behavior across different upload types. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def __init__(self, upload_url, headers=None, retry=DEFAULT_RETRY): + self.upload_url = upload_url + if headers is None: + headers = {} + self._headers = headers + self._finished = False + self._retry_strategy = retry + + @property + def finished(self): + """bool: Flag indicating if the upload has completed.""" + return self._finished + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Tombstone the current upload so it cannot be used again (in either + # failure or success). + self._finished = True + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class SimpleUpload(UploadBase): + """Upload a resource to a Google API. + + A **simple** media upload sends no metadata and completes the upload + in a single request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def _prepare_request(self, data, content_type): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used only once, so ``headers`` will be + mutated by having a new key added to it. + + Args: + data (bytes): The resource content to be uploaded. + content_type (str): The content type for the request. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already finished. + TypeError: If ``data`` isn't bytes. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("An upload can only be used once.") + + if not isinstance(data, bytes): + raise TypeError("`data` must be bytes, received", type(data)) + self._headers[_CONTENT_TYPE_HEADER] = content_type + return _POST, self.upload_url, data, self._headers + + def transmit(self, transport, data, content_type, timeout=None): + """Transmit the resource to be uploaded. + + Args: + transport (object): An object which can make authenticated + requests. + data (bytes): The resource content to be uploaded. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class MultipartUpload(UploadBase): + """Upload a resource with metadata to a Google API. + + A **multipart** upload sends both metadata and the resource in a single + (multipart) request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The request metadata will be amended + to include the computed value. Using this option will override a + manually-set checksum value. Supported values are "md5", + "crc32c", "auto", and None. The default is "auto", which will try + to detect if the C extension for crc32c is installed and fall back + to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def __init__(self, upload_url, headers=None, checksum="auto", retry=DEFAULT_RETRY): + super(MultipartUpload, self).__init__(upload_url, headers=headers, retry=retry) + self._checksum_type = checksum + if self._checksum_type == "auto": + self._checksum_type = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + + def _prepare_request(self, data, metadata, content_type): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used only once, so ``headers`` will be + mutated by having a new key added to it. + + Args: + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already finished. + TypeError: If ``data`` isn't bytes. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("An upload can only be used once.") + + if not isinstance(data, bytes): + raise TypeError("`data` must be bytes, received", type(data)) + + checksum_object = _helpers._get_checksum_object(self._checksum_type) + if checksum_object is not None: + checksum_object.update(data) + actual_checksum = _helpers.prepare_checksum_digest(checksum_object.digest()) + metadata_key = _helpers._get_metadata_key(self._checksum_type) + metadata[metadata_key] = actual_checksum + + content, multipart_boundary = construct_multipart_request( + data, metadata, content_type + ) + multipart_content_type = _RELATED_HEADER + multipart_boundary + b'"' + self._headers[_CONTENT_TYPE_HEADER] = multipart_content_type + + return _POST, self.upload_url, content, self._headers + + def transmit(self, transport, data, metadata, content_type, timeout=None): + """Transmit the resource to be uploaded. + + Args: + transport (object): An object which can make authenticated + requests. + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class ResumableUpload(UploadBase): + """Initiate and fulfill a resumable upload to a Google API. + + A **resumable** upload sends an initial request with the resource metadata + and then gets assigned an upload ID / upload URL to send bytes to. + Using the upload URL, the upload is then done in chunks (determined by + the user) until all bytes have been uploaded. + + Args: + upload_url (str): The URL where the resumable upload will be initiated. + chunk_size (int): The size of each chunk used to upload the resource. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be checked + and google.cloud.storage.exceptions.DataCorruption will be raised on + a mismatch. The corrupted file will not be deleted from the remote + host automatically. Supported values are "md5", "crc32c", "auto", + and None. The default is "auto", which will try to detect if the C + extension for crc32c is installed and fall back to md5 otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + + Raises: + ValueError: If ``chunk_size`` is not a multiple of + :data:`.UPLOAD_CHUNK_SIZE`. + """ + + def __init__( + self, + upload_url, + chunk_size, + checksum="auto", + headers=None, + retry=DEFAULT_RETRY, + ): + super(ResumableUpload, self).__init__(upload_url, headers=headers, retry=retry) + if chunk_size % UPLOAD_CHUNK_SIZE != 0: + raise ValueError( + "{} KB must divide chunk size".format(UPLOAD_CHUNK_SIZE / 1024) + ) + self._chunk_size = chunk_size + self._stream = None + self._content_type = None + self._bytes_uploaded = 0 + self._bytes_checksummed = 0 + self._checksum_type = checksum + if self._checksum_type == "auto": + self._checksum_type = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + self._checksum_object = None + self._total_bytes = None + self._resumable_url = None + self._invalid = False + + @property + def invalid(self): + """bool: Indicates if the upload is in an invalid state. + + This will occur if a call to :meth:`transmit_next_chunk` fails. + To recover from such a failure, call :meth:`recover`. + """ + return self._invalid + + @property + def chunk_size(self): + """int: The size of each chunk used to upload the resource.""" + return self._chunk_size + + @property + def resumable_url(self): + """Optional[str]: The URL of the in-progress resumable upload.""" + return self._resumable_url + + @property + def bytes_uploaded(self): + """int: Number of bytes that have been uploaded.""" + return self._bytes_uploaded + + @property + def total_bytes(self): + """Optional[int]: The total number of bytes to be uploaded. + + If this upload is initiated (via :meth:`initiate`) with + ``stream_final=True``, this value will be populated based on the size + of the ``stream`` being uploaded. (By default ``stream_final=True``.) + + If this upload is initiated with ``stream_final=False``, + :attr:`total_bytes` will be :data:`None` since it cannot be + determined from the stream. + """ + return self._total_bytes + + def _prepare_initiate_request( + self, + stream, + metadata, + content_type, + total_bytes=None, + stream_final=True, + ): + """Prepare the contents of HTTP request to initiate upload. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already been initiated. + ValueError: If ``stream`` is not at the beginning. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.resumable_url is not None: + raise ValueError("This upload has already been initiated.") + if stream.tell() != 0: + raise ValueError("Stream must be at beginning.") + + self._stream = stream + self._content_type = content_type + + # Signed URL requires content type set directly - not through x-upload-content-type + parse_result = urllib.parse.urlparse(self.upload_url) + parsed_query = urllib.parse.parse_qs(parse_result.query) + if "x-goog-signature" in parsed_query or "X-Goog-Signature" in parsed_query: + # Deconstruct **self._headers first so that content type defined here takes priority + headers = {**self._headers, _CONTENT_TYPE_HEADER: content_type} + else: + # Deconstruct **self._headers first so that content type defined here takes priority + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: "application/json; charset=UTF-8", + "x-upload-content-type": content_type, + } + # Set the total bytes if possible. + if total_bytes is not None: + self._total_bytes = total_bytes + elif stream_final: + self._total_bytes = get_total_bytes(stream) + # Add the total bytes to the headers if set. + if self._total_bytes is not None: + content_length = "{:d}".format(self._total_bytes) + headers["x-upload-content-length"] = content_length + + payload = json.dumps(metadata).encode("utf-8") + return _POST, self.upload_url, payload, headers + + def _process_initiate_response(self, response): + """Process the response from an HTTP request that initiated upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + This method takes the URL from the ``Location`` header and stores it + for future use. Within that URL, we assume the ``upload_id`` query + parameter has been included, but we do not check. + + Args: + response (object): The HTTP response object (need headers). + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code( + response, + (http.client.OK, http.client.CREATED), + self._get_status_code, + callback=self._make_invalid, + ) + self._resumable_url = _helpers.header_required( + response, "location", self._get_headers + ) + + def initiate( + self, + transport, + stream, + metadata, + content_type, + total_bytes=None, + stream_final=True, + timeout=None, + ): + """Initiate a resumable upload. + + By default, this method assumes your ``stream`` is in a "final" + state ready to transmit. However, ``stream_final=False`` can be used + to indicate that the size of the resource is not known. This can happen + if bytes are being dynamically fed into ``stream``, e.g. if the stream + is attached to application logs. + + If ``stream_final=False`` is used, :attr:`chunk_size` bytes will be + read from the stream every time :meth:`transmit_next_chunk` is called. + If one of those reads produces strictly fewer bites than the chunk + size, the upload will be concluded. + + Args: + transport (object): An object which can make authenticated + requests. + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_request(self): + """Prepare the contents of HTTP request to upload a chunk. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to read + a chunk from ``stream`` (via :func:`get_next_chunk`). However, this + will (almost) certainly not be network I/O. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request + * headers for the request + + The headers incorporate the ``_headers`` on the current instance. + + Raises: + ValueError: If the current upload has finished. + ValueError: If the current upload is in an invalid state. + ValueError: If the current upload has not been initiated. + ValueError: If the location in the stream (i.e. ``stream.tell()``) + does not agree with ``bytes_uploaded``. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("Upload has finished.") + if self.invalid: + raise ValueError( + "Upload is in an invalid state. To recover call `recover()`." + ) + if self.resumable_url is None: + raise ValueError( + "This upload has not been initiated. Please call " + "initiate() before beginning to transmit chunks." + ) + + start_byte, payload, content_range = get_next_chunk( + self._stream, self._chunk_size, self._total_bytes + ) + if start_byte != self.bytes_uploaded: + msg = _STREAM_ERROR_TEMPLATE.format(start_byte, self.bytes_uploaded) + raise ValueError(msg) + + self._update_checksum(start_byte, payload) + + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: self._content_type, + _helpers.CONTENT_RANGE_HEADER: content_range, + } + if (start_byte + len(payload) == self._total_bytes) and ( + self._checksum_object is not None + ): + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + headers["x-goog-hash"] = f"{self._checksum_type}={local_checksum}" + return _PUT, self.resumable_url, payload, headers + + def _update_checksum(self, start_byte, payload): + """Update the checksum with the payload if not already updated. + + Because error recovery can result in bytes being transmitted more than + once, the checksum tracks the number of bytes checked in + self._bytes_checksummed and skips bytes that have already been summed. + """ + if not self._checksum_type: + return + + if not self._checksum_object: + self._checksum_object = _helpers._get_checksum_object(self._checksum_type) + + if start_byte < self._bytes_checksummed: + offset = self._bytes_checksummed - start_byte + data = payload[offset:] + else: + data = payload + + self._checksum_object.update(data) + self._bytes_checksummed += len(data) + + def _make_invalid(self): + """Simple setter for ``invalid``. + + This is intended to be passed along as a callback to helpers that + raise an exception so they can mark this instance as invalid before + raising. + """ + self._invalid = True + + def _process_resumable_response(self, response, bytes_sent): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + bytes_sent (int): The number of bytes sent in the request that + ``response`` was returned for. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is 308 and the ``range`` header is not of the form + ``bytes 0-{end}``. + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200 or 308. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + status_code = _helpers.require_status_code( + response, + (http.client.OK, http.client.PERMANENT_REDIRECT), + self._get_status_code, + callback=self._make_invalid, + ) + if status_code == http.client.OK: + # NOTE: We use the "local" information of ``bytes_sent`` to update + # ``bytes_uploaded``, but do not verify this against other + # state. However, there may be some other information: + # + # * a ``size`` key in JSON response body + # * the ``total_bytes`` attribute (if set) + # * ``stream.tell()`` (relying on fact that ``initiate()`` + # requires stream to be at the beginning) + self._bytes_uploaded = self._bytes_uploaded + bytes_sent + # Tombstone the current upload so it cannot be used again. + self._finished = True + # Validate the checksum. This can raise an exception on failure. + self._validate_checksum(response) + else: + bytes_range = _helpers.header_required( + response, + _helpers.RANGE_HEADER, + self._get_headers, + callback=self._make_invalid, + ) + match = _BYTES_RANGE_RE.match(bytes_range) + if match is None: + self._make_invalid() + raise InvalidResponse( + response, + 'Unexpected "range" header', + bytes_range, + 'Expected to be of the form "bytes=0-{end}"', + ) + self._bytes_uploaded = int(match.group("end_byte")) + 1 + + def _validate_checksum(self, response): + """Check the computed checksum, if any, against the recieved metadata. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the checksum + computed locally and the checksum reported by the remote host do + not match. + """ + if self._checksum_type is None: + return + metadata_key = _helpers._get_metadata_key(self._checksum_type) + metadata = response.json() + remote_checksum = metadata.get(metadata_key) + if remote_checksum is None: + raise InvalidResponse( + response, + _UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE.format(metadata_key), + self._get_headers(response), + ) + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + if local_checksum != remote_checksum: + raise DataCorruption( + response, + _UPLOAD_CHECKSUM_MISMATCH_MESSAGE.format( + self._checksum_type.upper(), local_checksum, remote_checksum + ), + ) + + def transmit_next_chunk(self, transport, timeout=None): + """Transmit the next chunk of the resource to be uploaded. + + If the current upload was initiated with ``stream_final=False``, + this method will dynamically determine if the upload has completed. + The upload will be considered complete if the stream produces + fewer than :attr:`chunk_size` bytes when a chunk is read from it. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_recover_request(self): + """Prepare the contents of HTTP request to recover from failure. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + We assume that the :attr:`resumable_url` is set (i.e. the only way + the upload can end up :attr:`invalid` is if it has been initiated. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + The headers **do not** incorporate the ``_headers`` on the + current instance. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + headers = {_helpers.CONTENT_RANGE_HEADER: "bytes */*"} + return _PUT, self.resumable_url, None, headers + + def _process_recover_response(self, response): + """Process the response from an HTTP request to recover from failure. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 308. + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is 308 and the ``range`` header is not of the form + ``bytes 0-{end}``. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code( + response, (http.client.PERMANENT_REDIRECT,), self._get_status_code + ) + headers = self._get_headers(response) + if _helpers.RANGE_HEADER in headers: + bytes_range = headers[_helpers.RANGE_HEADER] + match = _BYTES_RANGE_RE.match(bytes_range) + if match is None: + raise InvalidResponse( + response, + 'Unexpected "range" header', + bytes_range, + 'Expected to be of the form "bytes=0-{end}"', + ) + self._bytes_uploaded = int(match.group("end_byte")) + 1 + else: + # In this case, the upload has not "begun". + self._bytes_uploaded = 0 + + self._stream.seek(self._bytes_uploaded) + self._invalid = False + + def recover(self, transport): + """Recover from a failure. + + This method should be used when a :class:`ResumableUpload` is in an + :attr:`~ResumableUpload.invalid` state due to a request failure. + + This will verify the progress with the server and make sure the + current upload is in a valid state before :meth:`transmit_next_chunk` + can be used again. + + Args: + transport (object): An object which can make authenticated + requests. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class XMLMPUContainer(UploadBase): + """Initiate and close an upload using the XML MPU API. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with this container object, the + uploading of individual parts is handled separately, by XMLMPUPart objects + spawned from this container class. The XMLMPUPart objects are not + necessarily in the same process as the container, so they do not update the + container automatically. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). The + initiate, PUT, and finalization requests will all use this URL, with + varying query parameters. + filename (str): The name (path) of the file to upload. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + upload_id (Optional(str)): The ID of the upload from the initialization + response. + """ + + def __init__( + self, + upload_url, + filename, + headers=None, + upload_id=None, + retry=DEFAULT_RETRY, + ): + super().__init__(upload_url, headers=headers, retry=retry) + self._filename = filename + self._upload_id = upload_id + self._parts = {} + + @property + def upload_id(self): + return self._upload_id + + def register_part(self, part_number, etag): + """Register an uploaded part by part number and corresponding etag. + + XMLMPUPart objects represent individual parts, and their part number + and etag can be registered to the container object with this method + and therefore incorporated in the finalize() call to finish the upload. + + This method accepts part_number and etag, but not XMLMPUPart objects + themselves, to reduce the complexity involved in running XMLMPUPart + uploads in separate processes. + + Args: + part_number (int): The part number. Parts are assembled into the + final uploaded object with finalize() in order of their part + numbers. + etag (str): The etag included in the server response after upload. + """ + self._parts[part_number] = etag + + def _prepare_initiate_request(self, content_type): + """Prepare the contents of HTTP request to initiate upload. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already been initiated. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.upload_id is not None: + raise ValueError("This upload has already been initiated.") + + initiate_url = self.upload_url + _MPU_INITIATE_QUERY + + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: content_type, + } + return _POST, initiate_url, None, headers + + def _process_initiate_response(self, response): + """Process the response from an HTTP request that initiated the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + This method takes the URL from the ``Location`` header and stores it + for future use. Within that URL, we assume the ``upload_id`` query + parameter has been included, but we do not check. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + root = ElementTree.fromstring(response.text) + self._upload_id = root.find(_S3_COMPAT_XML_NAMESPACE + _UPLOAD_ID_NODE).text + + def initiate( + self, + transport, + content_type, + timeout=None, + ): + """Initiate an MPU and record the upload ID. + + Args: + transport (object): An object which can make authenticated + requests. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_finalize_request(self): + """Prepare the contents of an HTTP request to finalize the upload. + + All of the parts must be registered before calling this method. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the upload has not been initiated. + """ + if self.upload_id is None: + raise ValueError("This upload has not yet been initiated.") + + final_query = _MPU_FINAL_QUERY_TEMPLATE.format(upload_id=self._upload_id) + finalize_url = self.upload_url + final_query + final_xml_root = ElementTree.Element("CompleteMultipartUpload") + for part_number, etag in self._parts.items(): + part = ElementTree.SubElement(final_xml_root, "Part") # put in a loop + ElementTree.SubElement(part, "PartNumber").text = str(part_number) + ElementTree.SubElement(part, "ETag").text = etag + payload = ElementTree.tostring(final_xml_root) + return _POST, finalize_url, payload, self._headers + + def _process_finalize_response(self, response): + """Process the response from an HTTP request that finalized the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + self._finished = True + + def finalize( + self, + transport, + timeout=None, + ): + """Finalize an MPU request with all the parts. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_cancel_request(self): + """Prepare the contents of an HTTP request to cancel the upload. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always DELETE) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the upload has not been initiated. + """ + if self.upload_id is None: + raise ValueError("This upload has not yet been initiated.") + + cancel_query = _MPU_FINAL_QUERY_TEMPLATE.format(upload_id=self._upload_id) + cancel_url = self.upload_url + cancel_query + return _DELETE, cancel_url, None, self._headers + + def _process_cancel_response(self, response): + """Process the response from an HTTP request that canceled the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 204. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + + _helpers.require_status_code( + response, (http.client.NO_CONTENT,), self._get_status_code + ) + + def cancel( + self, + transport, + timeout=None, + ): + """Cancel an MPU request and permanently delete any uploaded parts. + + This cannot be undone. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class XMLMPUPart(UploadBase): + """Upload a single part of an existing XML MPU container. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with the container object, the + uploading of individual parts is handled separately by multiple objects + of this class. Once a part is uploaded, it can be registered with the + container with `container.register_part(part.part_number, part.etag)`. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). + upload_id (str): The ID of the upload from the initialization response. + filename (str): The name (path) of the file to upload. + start (int): The byte index of the beginning of the part. + end (int): The byte index of the end of the part. + part_number (int): The part number. Part numbers will be assembled in + sequential order when the container is finalized. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + checksum (Optional([str])): The type of checksum to compute to verify + the integrity of the object. The request headers will be amended + to include the computed value. Supported values are "md5", "crc32c", + "auto" and None. The default is "auto", which will try to detect if + the C extension for crc32c is installed and fall back to md5 + otherwise. + retry (Optional[google.api_core.retry.Retry]): How to retry the + RPC. A None value will disable retries. A + google.api_core.retry.Retry value will enable retries, and the + object will configure backoff and timeout options. + + See the retry.py source code and docstrings in this package + (google.cloud.storage.retry) for information on retry types and how + to configure them. + + Attributes: + upload_url (str): The URL of the object (without query parameters). + upload_id (str): The ID of the upload from the initialization response. + filename (str): The name (path) of the file to upload. + start (int): The byte index of the beginning of the part. + end (int): The byte index of the end of the part. + part_number (int): The part number. Part numbers will be assembled in + sequential order when the container is finalized. + etag (Optional(str)): The etag returned by the service after upload. + """ + + def __init__( + self, + upload_url, + upload_id, + filename, + start, + end, + part_number, + headers=None, + checksum="auto", + retry=DEFAULT_RETRY, + ): + super().__init__(upload_url, headers=headers, retry=retry) + self._filename = filename + self._start = start + self._end = end + self._upload_id = upload_id + self._part_number = part_number + self._etag = None + self._checksum_type = checksum + if self._checksum_type == "auto": + self._checksum_type = ( + "crc32c" if _helpers._is_crc32c_available_and_fast() else "md5" + ) + self._checksum_object = None + + @property + def part_number(self): + return self._part_number + + @property + def upload_id(self): + return self._upload_id + + @property + def filename(self): + return self._filename + + @property + def etag(self): + return self._etag + + @property + def start(self): + return self._start + + @property + def end(self): + return self._end + + def _prepare_upload_request(self): + """Prepare the contents of HTTP request to upload a part. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to read + a part from ``stream`` (via :func:`get_part_payload`). However, this + will (almost) certainly not be network I/O. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request + * headers for the request + + The headers incorporate the ``_headers`` on the current instance. + + Raises: + ValueError: If the current upload has finished. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("This part has already been uploaded.") + + with open(self._filename, "br") as f: + f.seek(self._start) + payload = f.read(self._end - self._start) + + self._checksum_object = _helpers._get_checksum_object(self._checksum_type) + if self._checksum_object is not None: + self._checksum_object.update(payload) + + part_query = _MPU_PART_QUERY_TEMPLATE.format( + part=self._part_number, upload_id=self._upload_id + ) + upload_url = self.upload_url + part_query + return _PUT, upload_url, payload, self._headers + + def _process_upload_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.InvalidResponse: If the status + code is not 200 or the response is missing data. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Data corruption errors shouldn't be considered as invalid responses, + # So we handle them earlier than call to `_helpers.require_status_code`. + # If the response is 400, we check for data corruption errors. + if response.status_code == 400: + root = ElementTree.fromstring(response.text) + error_code = root.find("Code").text + error_message = root.find("Message").text + error_details = root.find("Details").text + if error_code in ["InvalidDigest", "BadDigest", "CrcMismatch"]: + raise DataCorruption( + response, + ( + "Checksum mismatch: checksum calculated by client and" + " server did not match. Error code: {error_code}," + " Error message: {error_message}," + " Error details: {error_details}" + ).format( + error_code=error_code, + error_message=error_message, + error_details=error_details, + ), + ) + + _helpers.require_status_code( + response, + (http.client.OK,), + self._get_status_code, + ) + + self._validate_checksum(response) + + etag = _helpers.header_required(response, "etag", self._get_headers) + self._etag = etag + self._finished = True + + def upload( + self, + transport, + timeout=None, + ): + """Upload the part. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _validate_checksum(self, response): + """Check the computed checksum, if any, against the response headers. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.cloud.storage.exceptions.DataCorruption: If the checksum + computed locally and the checksum reported by the remote host do + not match. + """ + if self._checksum_type is None: + return + + remote_checksum = _helpers._get_uploaded_checksum_from_headers( + response, self._get_headers, self._checksum_type + ) + + if remote_checksum is None: + metadata_key = _helpers._get_metadata_key(self._checksum_type) + raise InvalidResponse( + response, + _UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE.format(metadata_key), + self._get_headers(response), + ) + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + if local_checksum != remote_checksum: + raise DataCorruption( + response, + _UPLOAD_CHECKSUM_MISMATCH_MESSAGE.format( + self._checksum_type.upper(), local_checksum, remote_checksum + ), + ) + + +def get_boundary(): + """Get a random boundary for a multipart request. + + Returns: + bytes: The boundary used to separate parts of a multipart request. + """ + random_int = random.randrange(sys.maxsize) + boundary = _BOUNDARY_FORMAT.format(random_int) + # NOTE: Neither % formatting nor .format() are available for byte strings + # in Python 3.4, so we must use unicode strings as templates. + return boundary.encode("utf-8") + + +def construct_multipart_request(data, metadata, content_type): + """Construct a multipart request body. + + Args: + data (bytes): The resource content (UTF-8 encoded as bytes) + to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[bytes, bytes]: The multipart request body and the boundary used + between each part. + """ + multipart_boundary = get_boundary() + json_bytes = json.dumps(metadata).encode("utf-8") + content_type = content_type.encode("utf-8") + # Combine the two parts into a multipart payload. + # NOTE: We'd prefer a bytes template but are restricted by Python 3.4. + boundary_sep = _MULTIPART_SEP + multipart_boundary + content = ( + boundary_sep + + _MULTIPART_BEGIN + + json_bytes + + _CRLF + + boundary_sep + + _CRLF + + b"content-type: " + + content_type + + _CRLF + + _CRLF + + data # Empty line between headers and body. + + _CRLF + + boundary_sep + + _MULTIPART_SEP + ) + + return content, multipart_boundary + + +def get_total_bytes(stream): + """Determine the total number of bytes in a stream. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object). + + Returns: + int: The number of bytes. + """ + current_position = stream.tell() + # NOTE: ``.seek()`` **should** return the same value that ``.tell()`` + # returns, but in Python 2, ``file`` objects do not. + stream.seek(0, os.SEEK_END) + end_position = stream.tell() + # Go back to the initial position. + stream.seek(current_position) + + return end_position + + +def get_next_chunk(stream, chunk_size, total_bytes): + """Get a chunk from an I/O stream. + + The ``stream`` may have fewer bytes remaining than ``chunk_size`` + so it may not always be the case that + ``end_byte == start_byte + chunk_size - 1``. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object). + chunk_size (int): The size of the chunk to be read from the ``stream``. + total_bytes (Optional[int]): The (expected) total number of bytes + in the ``stream``. + + Returns: + Tuple[int, bytes, str]: Triple of: + + * the start byte index + * the content in between the start and end bytes (inclusive) + * content range header for the chunk (slice) that has been read + + Raises: + ValueError: If ``total_bytes == 0`` but ``stream.read()`` yields + non-empty content. + ValueError: If there is no data left to consume. This corresponds + exactly to the case ``end_byte < start_byte``, which can only + occur if ``end_byte == start_byte - 1``. + """ + start_byte = stream.tell() + if total_bytes is not None and start_byte + chunk_size >= total_bytes > 0: + payload = stream.read(total_bytes - start_byte) + else: + payload = stream.read(chunk_size) + end_byte = stream.tell() - 1 + + num_bytes_read = len(payload) + if total_bytes is None: + if num_bytes_read < chunk_size: + # We now **KNOW** the total number of bytes. + total_bytes = end_byte + 1 + elif total_bytes == 0: + # NOTE: We also expect ``start_byte == 0`` here but don't check + # because ``_prepare_initiate_request()`` requires the + # stream to be at the beginning. + if num_bytes_read != 0: + raise ValueError( + "Stream specified as empty, but produced non-empty content." + ) + else: + if num_bytes_read == 0: + raise ValueError( + "Stream is already exhausted. There is no content remaining." + ) + + content_range = get_content_range(start_byte, end_byte, total_bytes) + return start_byte, payload, content_range + + +def get_content_range(start_byte, end_byte, total_bytes): + """Convert start, end and total into content range header. + + If ``total_bytes`` is not known, uses "bytes {start}-{end}/*". + If we are dealing with an empty range (i.e. ``end_byte < start_byte``) + then "bytes */{total}" is used. + + This function **ASSUMES** that if the size is not known, the caller will + not also pass an empty range. + + Args: + start_byte (int): The start (inclusive) of the byte range. + end_byte (int): The end (inclusive) of the byte range. + total_bytes (Optional[int]): The number of bytes in the byte + range (if known). + + Returns: + str: The content range header. + """ + if total_bytes is None: + return _RANGE_UNKNOWN_TEMPLATE.format(start_byte, end_byte) + elif end_byte < start_byte: + return _EMPTY_RANGE_TEMPLATE.format(total_bytes) + else: + return _CONTENT_RANGE_TEMPLATE.format(start_byte, end_byte, total_bytes) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/common.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/common.py new file mode 100644 index 0000000000000000000000000000000000000000..2917ea53dfceff1d6e2ecb327b180e5488de20e3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/common.py @@ -0,0 +1,21 @@ +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common utilities for Google Media Downloads and Resumable Uploads. + +Includes custom exception types, useful constants and shared helpers. +""" + +UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 +"""int: Chunks in a resumable upload must come in multiples of 256 KB.""" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/py.typed b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..7705b065b00d1990fff0bfa83bc916b3f239a6f2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/_media/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-resumable_media package uses inline types. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..170a0cfae929e56691528e551eaf79a7922151d7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/_utils.py @@ -0,0 +1,41 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import google_crc32c + +from google.api_core import exceptions + + +def raise_if_no_fast_crc32c(): + """Check if the C-accelerated version of google-crc32c is available. + + If not, raise an error to prevent silent performance degradation. + + raises google.api_core.exceptions.FailedPrecondition: If the C extension is not available. + returns: True if the C extension is available. + rtype: bool + + """ + if google_crc32c.implementation != "c": + raise exceptions.FailedPrecondition( + "The google-crc32c package is not installed with C support. " + "C extension is required for faster data integrity checks." + "For more information, see https://github.com/googleapis/python-crc32c." + ) + + +def update_write_handle_if_exists(obj, response): + """Update the write_handle attribute of an object if it exists in the response.""" + if hasattr(response, "write_handle") and response.write_handle is not None: + obj.write_handle = response.write_handle diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_abstract_object_stream.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_abstract_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..26cbab7a0956601828f3fd862a3f4f50576d31be --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_abstract_object_stream.py @@ -0,0 +1,67 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import abc +from typing import Any, Optional + + +class _AsyncAbstractObjectStream(abc.ABC): + """Abstract base class to represent gRPC bidi-stream for GCS ``Object``. + + Concrete implementation of this class could be ``_AsyncReadObjectStream`` + or ``_AsyncWriteObjectStream``. + + :type bucket_name: str + :param bucket_name: (Optional) The name of the bucket containing the object. + + :type object_name: str + :param object_name: (Optional) The name of the object. + + :type generation_number: int + :param generation_number: (Optional) If present, selects a specific revision of + this object. + + :type handle: Any + :param handle: (Optional) The handle for the object, could be read_handle or + write_handle, based on how the stream is used. + """ + + def __init__( + self, + bucket_name: str, + object_name: str, + generation_number: Optional[int] = None, + handle: Optional[Any] = None, + ) -> None: + super().__init__() + self.bucket_name: str = bucket_name + self.object_name: str = object_name + self.generation_number: Optional[int] = generation_number + self.handle: Optional[Any] = handle + + @abc.abstractmethod + async def open(self) -> None: + pass + + @abc.abstractmethod + async def close(self) -> None: + pass + + @abc.abstractmethod + async def send(self, protobuf: Any) -> None: + pass + + @abc.abstractmethod + async def recv(self) -> Any: + pass diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_appendable_object_writer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_appendable_object_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..c65209680c694d12a6d259f46e964d7c474169d8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_appendable_object_writer.py @@ -0,0 +1,585 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from io import BufferedReader +import io +import logging +from typing import List, Optional, Tuple, Union + +from google.api_core import exceptions +from google.api_core.retry_async import AsyncRetry +from google.rpc import status_pb2 +from google.cloud._storage_v2.types import BidiWriteObjectRedirectedError +from google.cloud._storage_v2.types.storage import BidiWriteObjectRequest + + +from . import _utils +from google.cloud import _storage_v2 +from google.cloud.storage.asyncio.async_grpc_client import ( + AsyncGrpcClient, +) +from google.cloud.storage.asyncio.async_write_object_stream import ( + _AsyncWriteObjectStream, +) +from google.cloud.storage.asyncio.retry.bidi_stream_retry_manager import ( + _BidiStreamRetryManager, +) +from google.cloud.storage.asyncio.retry.writes_resumption_strategy import ( + _WriteResumptionStrategy, + _WriteState, +) +from google.cloud.storage.asyncio.retry._helpers import ( + _extract_bidi_writes_redirect_proto, +) + +_MAX_CHUNK_SIZE_BYTES = 2 * 1024 * 1024 # 2 MiB +_DEFAULT_FLUSH_INTERVAL_BYTES = 16 * 1024 * 1024 # 16 MiB +_BIDI_WRITE_REDIRECTED_TYPE_URL = ( + "type.googleapis.com/google.storage.v2.BidiWriteObjectRedirectedError" +) +logger = logging.getLogger(__name__) + + +def _is_write_retryable(exc): + """Predicate to determine if a write operation should be retried.""" + + if isinstance( + exc, + ( + exceptions.InternalServerError, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + exceptions.TooManyRequests, + BidiWriteObjectRedirectedError, + ), + ): + logger.warning(f"Retryable write exception encountered: {exc}") + return True + + grpc_error = None + if isinstance(exc, exceptions.Aborted) and exc.errors: + grpc_error = exc.errors[0] + if isinstance(grpc_error, BidiWriteObjectRedirectedError): + return True + + trailers = grpc_error.trailing_metadata() + if not trailers: + return False + + status_details_bin = None + for key, value in trailers: + if key == "grpc-status-details-bin": + status_details_bin = value + break + + if status_details_bin: + status_proto = status_pb2.Status() + try: + status_proto.ParseFromString(status_details_bin) + for detail in status_proto.details: + if detail.type_url == _BIDI_WRITE_REDIRECTED_TYPE_URL: + return True + except Exception: + logger.error( + "Error unpacking redirect details from gRPC error. Exception: ", + {exc}, + ) + return False + return False + + +class AsyncAppendableObjectWriter: + """Class for appending data to a GCS Appendable Object asynchronously.""" + + def __init__( + self, + client: AsyncGrpcClient, + bucket_name: str, + object_name: str, + generation: Optional[int] = None, + write_handle: Optional[_storage_v2.BidiWriteHandle] = None, + writer_options: Optional[dict] = None, + ): + """ + Class for appending data to a GCS Appendable Object. + + Example usage: + + ``` + + from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient + from google.cloud.storage.asyncio.async_appendable_object_writer import AsyncAppendableObjectWriter + import asyncio + + client = AsyncGrpcClient() + bucket_name = "my-bucket" + object_name = "my-appendable-object" + + # instantiate the writer + writer = AsyncAppendableObjectWriter(client, bucket_name, object_name) + # open the writer, (underlying gRPC bidi-stream will be opened) + await writer.open() + + # append data, it can be called multiple times. + await writer.append(b"hello world") + await writer.append(b"some more data") + + # optionally flush data to persist. + await writer.flush() + + # close the gRPC stream. + # Please note closing the program will also close the stream, + # however it's recommended to close the stream if no more data to append + # to clean up gRPC connection (which means CPU/memory/network resources) + await writer.close() + ``` + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient` + :param client: async grpc client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the GCS bucket containing the object. + + :type object_name: str + :param object_name: The name of the GCS Appendable Object to be written. + + :type generation: Optional[int] + :param generation: (Optional) If present, creates writer for that + specific revision of that object. Use this to append data to an + existing Appendable Object. + + Setting to ``0`` makes the `writer.open()` succeed only if + object doesn't exist in the bucket (useful for not accidentally + overwriting existing objects). + + Warning: If `None`, a new object is created. If an object with the + same name already exists, it will be overwritten the moment + `writer.open()` is called. + + :type write_handle: _storage_v2.BidiWriteHandle + :param write_handle: (Optional) An handle for writing the object. + If provided, opening the bidi-gRPC connection will be faster. + + :type writer_options: dict + :param writer_options: (Optional) A dictionary of writer options. + Supported options: + - "FLUSH_INTERVAL_BYTES": int + The number of bytes to append before "persisting" data in GCS + servers. Default is `_DEFAULT_FLUSH_INTERVAL_BYTES`. + Must be a multiple of `_MAX_CHUNK_SIZE_BYTES`. + """ + _utils.raise_if_no_fast_crc32c() + self.client = client + self.bucket_name = bucket_name + self.object_name = object_name + self.write_handle = write_handle + self.generation = generation + + self.write_obj_stream: Optional[_AsyncWriteObjectStream] = None + self._is_stream_open: bool = False + # `offset` is the latest size of the object without staleless. + self.offset: Optional[int] = None + # `persisted_size` is the total_bytes persisted in the GCS server. + # Please note: `offset` and `persisted_size` are same when the stream is + # opened. + self.persisted_size: Optional[int] = None + if writer_options is None: + writer_options = {} + self.flush_interval = writer_options.get( + "FLUSH_INTERVAL_BYTES", _DEFAULT_FLUSH_INTERVAL_BYTES + ) + if self.flush_interval < _MAX_CHUNK_SIZE_BYTES: + raise exceptions.OutOfRange( + f"flush_interval must be >= {_MAX_CHUNK_SIZE_BYTES} , but provided {self.flush_interval}" + ) + if self.flush_interval % _MAX_CHUNK_SIZE_BYTES != 0: + raise exceptions.OutOfRange( + f"flush_interval must be a multiple of {_MAX_CHUNK_SIZE_BYTES}, but provided {self.flush_interval}" + ) + self.bytes_appended_since_last_flush = 0 + self._routing_token: Optional[str] = None + self.object_resource: Optional[_storage_v2.Object] = None + self._flush_count = 0 + + async def state_lookup(self) -> int: + """Returns the persisted_size + + :rtype: int + :returns: persisted size. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before state_lookup().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest( + state_lookup=True, + ) + ) + response = await self.write_obj_stream.recv() + self.persisted_size = response.persisted_size + return self.persisted_size + + def _on_open_error(self, exc): + """Extracts routing token and write handle on redirect error during open.""" + redirect_proto = _extract_bidi_writes_redirect_proto(exc) + if redirect_proto: + if redirect_proto.routing_token: + self._routing_token = redirect_proto.routing_token + if redirect_proto.write_handle: + self.write_handle = redirect_proto.write_handle + if redirect_proto.generation: + self.generation = redirect_proto.generation + + async def open( + self, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Opens the underlying bidi-gRPC stream. + + :raises ValueError: If the stream is already open. + + """ + if self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is already open") + + if retry_policy is None: + retry_policy = AsyncRetry( + predicate=_is_write_retryable, on_error=self._on_open_error + ) + else: + original_on_error = retry_policy._on_error + + def combined_on_error(exc): + self._on_open_error(exc) + if original_on_error: + original_on_error(exc) + + retry_policy = AsyncRetry( + predicate=_is_write_retryable, + initial=retry_policy._initial, + maximum=retry_policy._maximum, + multiplier=retry_policy._multiplier, + deadline=retry_policy._deadline, + on_error=combined_on_error, + ) + + async def _do_open(): + current_metadata = list(metadata) if metadata else [] + + # Cleanup stream from previous failed attempt, if any. + if self.write_obj_stream: + if self.write_obj_stream.is_stream_open: + try: + await self.write_obj_stream.close() + except Exception as e: + logger.warning( + f"Error closing previous write stream during open retry. Got exception: {e}" + ) + self.write_obj_stream = None + self._is_stream_open = False + + self.write_obj_stream = _AsyncWriteObjectStream( + client=self.client.grpc_client, + bucket_name=self.bucket_name, + object_name=self.object_name, + generation_number=self.generation, + write_handle=self.write_handle, + routing_token=self._routing_token, + ) + + if self._routing_token: + current_metadata.append( + ("x-goog-request-params", f"routing_token={self._routing_token}") + ) + + await self.write_obj_stream.open( + metadata=current_metadata if current_metadata else None + ) + + if self.write_obj_stream.generation_number: + self.generation = self.write_obj_stream.generation_number + if self.write_obj_stream.write_handle: + self.write_handle = self.write_obj_stream.write_handle + if self.write_obj_stream.persisted_size is not None: + self.persisted_size = self.write_obj_stream.persisted_size + # set offset while opening + self.offset = self.persisted_size + + self._is_stream_open = True + self._routing_token = None + + await retry_policy(_do_open)() + + async def append( + self, + data: bytes, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Appends data to the Appendable object with automatic retries. + + calling `self.append` will append bytes at the end of the current size + ie. `self.offset` bytes relative to the begining of the object. + + This method sends the provided `data` to the GCS server in chunks. + and persists data in GCS at every `_DEFAULT_FLUSH_INTERVAL_BYTES` bytes + or at the last chunk whichever is earlier. Persisting is done by setting + `flush=True` on request. + + :type data: bytes + :param data: The bytes to append to the object. + + :type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry` + :param retry_policy: (Optional) The retry policy to use for the operation. + + :type metadata: List[Tuple[str, str]] + :param metadata: (Optional) The metadata to be sent with the request. + + :raises ValueError: If the stream is not open. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before append().") + if not data: + logger.debug("No data provided to append; returning without action.") + return + + if retry_policy is None: + retry_policy = AsyncRetry(predicate=_is_write_retryable) + + strategy = _WriteResumptionStrategy() + buffer = io.BytesIO(data) + attempt_count = 0 + + def send_and_recv_generator( + requests: List[BidiWriteObjectRequest], + state: dict[str, _WriteState], + metadata: Optional[List[Tuple[str, str]]] = None, + ): + async def generator(): + nonlocal attempt_count + nonlocal requests + attempt_count += 1 + resp = None + write_state = state["write_state"] + # If this is a retry or redirect, we must re-open the stream + if attempt_count > 1 or write_state.routing_token: + logger.info( + f"Re-opening the stream with attempt_count: {attempt_count}" + ) + + current_metadata = list(metadata) if metadata else [] + if write_state.routing_token: + current_metadata.append( + ( + "x-goog-request-params", + f"routing_token={write_state.routing_token}", + ) + ) + self._routing_token = write_state.routing_token + + self._is_stream_open = False + await self.open(metadata=current_metadata) + + write_state.persisted_size = self.persisted_size + write_state.write_handle = self.write_handle + write_state.routing_token = None + + write_state.user_buffer.seek(write_state.persisted_size) + write_state.bytes_sent = write_state.persisted_size + write_state.bytes_since_last_flush = 0 + self.bytes_appended_since_last_flush = 0 + + requests = strategy.generate_requests(state) + + for chunk_req in requests: + await self.write_obj_stream.send(chunk_req) + if chunk_req.flush: + self._flush_count += 1 + + resp = None + if chunk_req.state_lookup: + # TODO: if there's error, it'll raise error + # and will be handled by `recover_state_on_failure` + resp = await self.write_obj_stream.recv() + + if resp: + if resp.persisted_size is not None: + self.persisted_size = resp.persisted_size + state["write_state"].persisted_size = resp.persisted_size + self.offset = self.persisted_size + if resp.write_handle: + self.write_handle = resp.write_handle + state["write_state"].write_handle = resp.write_handle + + yield resp + + return generator() + + # State initialization + write_state = _WriteState(_MAX_CHUNK_SIZE_BYTES, buffer, self.flush_interval) + write_state.write_handle = self.write_handle + write_state.persisted_size = self.persisted_size + # offset is set during `open()` call. + write_state.bytes_sent = self.offset or 0 + write_state.bytes_since_last_flush = self.bytes_appended_since_last_flush + + retry_manager = _BidiStreamRetryManager( + _WriteResumptionStrategy(), + lambda r, s: send_and_recv_generator(r, s, metadata), + ) + await retry_manager.execute({"write_state": write_state}, retry_policy) + + # Sync local markers + self.bytes_appended_since_last_flush = write_state.bytes_since_last_flush + self.offset = write_state.bytes_sent + + async def simple_flush(self) -> None: + """Flushes the data to the server. + Please note: Unlike `flush` it does not do `state_lookup` + + :rtype: None + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before simple_flush().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest( + flush=True, + ) + ) + self.bytes_appended_since_last_flush = 0 + + async def flush(self) -> int: + """Flushes the data to the server. + + :rtype: int + :returns: The persisted size after flush. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before flush().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest( + flush=True, + state_lookup=True, + ) + ) + response = await self.write_obj_stream.recv() + self.persisted_size = response.persisted_size + self.offset = self.persisted_size + self.bytes_appended_since_last_flush = 0 + return self.persisted_size + + async def close(self, finalize_on_close=False) -> Union[int, _storage_v2.Object]: + """Closes the underlying bidi-gRPC stream. + + :type finalize_on_close: bool + :param finalize_on_close: Finalizes the Appendable Object. No more data + can be appended. + + rtype: Union[int, _storage_v2.Object] + returns: Updated `self.persisted_size` by default after closing the + bidi-gRPC stream. However, if `finalize_on_close=True` is passed, + returns the finalized object resource. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before close().") + + if finalize_on_close: + return await self.finalize() + + await self.write_obj_stream.close() + + self._is_stream_open = False + return self.persisted_size + + async def finalize(self) -> _storage_v2.Object: + """Finalizes the Appendable Object. + + Note: Once finalized no more data can be appended. + This method is different from `close`. if `.close()` is called data may + still be appended to object at a later point in time by opening with + generation number. + (i.e. `open(..., generation=)`. + However if `.finalize()` is called no more data can be appended to the + object. + + rtype: google.cloud.storage_v2.types.Object + returns: The finalized object resource. + + :raises ValueError: If the stream is not open (i.e., `open()` has not + been called). + """ + if not self._is_stream_open: + raise ValueError("Stream is not open. Call open() before finalize().") + + await self.write_obj_stream.send( + _storage_v2.BidiWriteObjectRequest(finish_write=True) + ) + response = await self.write_obj_stream.recv() + self.object_resource = response.resource + self.persisted_size = self.object_resource.size + await self.write_obj_stream.close() + + self._is_stream_open = False + self.offset = None + return self.object_resource + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open + + # helper methods. + async def append_from_string(self, data: str): + """ + str data will be encoded to bytes using utf-8 encoding calling + + self.append(data.encode("utf-8")) + """ + raise NotImplementedError("append_from_string is not implemented yet.") + + async def append_from_stream(self, stream_obj): + """ + At a time read a chunk of data (16MiB) from `stream_obj` + and call self.append(chunk) + """ + raise NotImplementedError("append_from_stream is not implemented yet.") + + async def append_from_file( + self, file_obj: BufferedReader, block_size: int = _DEFAULT_FLUSH_INTERVAL_BYTES + ): + """ + Appends data to an Appendable Object using file_handle which is opened + for reading in binary mode. + + :type file_obj: file + :param file_obj: A file handle opened in binary mode for reading. + + """ + while block := file_obj.read(block_size): + await self.append(block) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_grpc_client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_grpc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..90ca78bfb969a4e4d409323b1ef3e07f46b105ad --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_grpc_client.py @@ -0,0 +1,250 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""An async client for interacting with Google Cloud Storage using the gRPC API.""" + +from google.cloud import _storage_v2 as storage_v2 +from google.cloud._storage_v2.services.storage.transports.base import ( + DEFAULT_CLIENT_INFO, +) +from google.cloud.storage import __version__ +import grpc +from google.auth import credentials as auth_credentials + + +class AsyncGrpcClient: + """An asynchronous client for interacting with Google Cloud Storage using the gRPC API. + + :type credentials: :class:`~google.auth.credentials.Credentials` + :param credentials: (Optional) The OAuth2 Credentials to use for this + client. If not passed, falls back to the default + inferred from the environment. + + :type client_info: :class:`~google.api_core.client_info.ClientInfo` + :param client_info: + The client info used to send a user-agent string along with API + requests. If ``None``, then default info will be used. + + :type client_options: :class:`~google.api_core.client_options.ClientOptions` + :param client_options: (Optional) Client options used to set user options + on the client. + + :type attempt_direct_path: bool + :param attempt_direct_path: + (Optional) Whether to attempt to use DirectPath for gRPC connections. + Defaults to ``True``. + """ + + def __init__( + self, + credentials=None, + client_info=None, + client_options=None, + *, + attempt_direct_path=True, + ): + if isinstance(credentials, auth_credentials.AnonymousCredentials): + if client_options is None or client_options.api_endpoint is None: + raise ValueError( + "Either client_options or `client_option.api_endpoint` is None. Please provide api_endpoint when `AnonymousCredentials` is used " + ) + self._grpc_client = self._create_anonymous_client( + client_options, credentials + ) + return + + if client_info is None: + client_info = DEFAULT_CLIENT_INFO + client_info.client_library_version = __version__ + if client_info.user_agent is None: + client_info.user_agent = "" + agent_version = f"gcloud-python/{__version__}" + if agent_version not in client_info.user_agent: + client_info.user_agent += f" {agent_version} " + + self._grpc_client = self._create_async_grpc_client( + credentials=credentials, + client_info=client_info, + client_options=client_options, + attempt_direct_path=attempt_direct_path, + ) + + def _create_anonymous_client(self, client_options, credentials): + channel = grpc.aio.insecure_channel(client_options.api_endpoint) + transport = storage_v2.services.storage.transports.StorageGrpcAsyncIOTransport( + channel=channel, credentials=credentials + ) + return storage_v2.StorageAsyncClient(transport=transport) + + @classmethod + def _create_insecure_grpc_client(cls, client_options): + return cls( + credentials=auth_credentials.AnonymousCredentials(), + client_options=client_options, + attempt_direct_path=False, + ) + + def _create_async_grpc_client( + self, + credentials=None, + client_info=None, + client_options=None, + attempt_direct_path=True, + ): + transport_cls = storage_v2.StorageAsyncClient.get_transport_class( + "grpc_asyncio" + ) + + primary_user_agent = client_info.to_user_agent() + + channel = transport_cls.create_channel( + attempt_direct_path=attempt_direct_path, + credentials=credentials, + options=(("grpc.primary_user_agent", primary_user_agent),), + ) + transport = transport_cls(channel=channel) + + return storage_v2.StorageAsyncClient( + transport=transport, + client_info=client_info, + client_options=client_options, + ) + + @property + def grpc_client(self): + """The underlying gRPC client. + + This property gives users direct access to the `_storage_v2.StorageAsyncClient` + instance. This can be useful for accessing + newly added or experimental RPCs that are not yet exposed through + the high-level GrpcClient. + Returns: + google.cloud._storage_v2.StorageAsyncClient: The configured GAPIC client. + """ + return self._grpc_client + + async def delete_object( + self, + bucket_name, + object_name, + generation=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + **kwargs, + ): + """Deletes an object and its metadata. + + :type bucket_name: str + :param bucket_name: The name of the bucket in which the object resides. + + :type object_name: str + :param object_name: The name of the object to delete. + + :type generation: int + :param generation: + (Optional) If present, permanently deletes a specific generation + of an object. + + :type if_generation_match: int + :param if_generation_match: (Optional) + + :type if_generation_not_match: int + :param if_generation_not_match: (Optional) + + :type if_metageneration_match: int + :param if_metageneration_match: (Optional) + + :type if_metageneration_not_match: int + :param if_metageneration_not_match: (Optional) + + + """ + # The gRPC API requires the bucket name to be in the format "projects/_/buckets/bucket_name" + bucket_path = f"projects/_/buckets/{bucket_name}" + request = storage_v2.DeleteObjectRequest( + bucket=bucket_path, + object=object_name, + generation=generation, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + **kwargs, + ) + await self._grpc_client.delete_object(request=request) + + async def get_object( + self, + bucket_name, + object_name, + generation=None, + if_generation_match=None, + if_generation_not_match=None, + if_metageneration_match=None, + if_metageneration_not_match=None, + soft_deleted=None, + **kwargs, + ): + """Retrieves an object's metadata. + + In the gRPC API, this is performed by the GetObject RPC, which + returns the object resource (metadata) without the object's data. + + :type bucket_name: str + :param bucket_name: The name of the bucket in which the object resides. + + :type object_name: str + :param object_name: The name of the object. + + :type generation: int + :param generation: + (Optional) If present, selects a specific generation of an object. + + :type if_generation_match: int + :param if_generation_match: (Optional) Precondition for object generation match. + + :type if_generation_not_match: int + :param if_generation_not_match: (Optional) Precondition for object generation mismatch. + + :type if_metageneration_match: int + :param if_metageneration_match: (Optional) Precondition for metageneration match. + + :type if_metageneration_not_match: int + :param if_metageneration_not_match: (Optional) Precondition for metageneration mismatch. + + :type soft_deleted: bool + :param soft_deleted: + (Optional) If True, return the soft-deleted version of this object. + + :rtype: :class:`google.cloud._storage_v2.types.Object` + :returns: The object metadata resource. + """ + bucket_path = f"projects/_/buckets/{bucket_name}" + + request = storage_v2.GetObjectRequest( + bucket=bucket_path, + object=object_name, + generation=generation, + if_generation_match=if_generation_match, + if_generation_not_match=if_generation_not_match, + if_metageneration_match=if_metageneration_match, + if_metageneration_not_match=if_metageneration_not_match, + soft_deleted=soft_deleted or False, + **kwargs, + ) + + # Calls the underlying GAPIC StorageAsyncClient.get_object method + return await self._grpc_client.get_object(request=request) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_multi_range_downloader.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_multi_range_downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..51afd255bda1006591100d0086b7224e60eef7d6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_multi_range_downloader.py @@ -0,0 +1,528 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations +import asyncio +import logging +from google.api_core import exceptions +from google.api_core.retry_async import AsyncRetry +from google.cloud.storage.asyncio.retry._helpers import _handle_redirect +from google.rpc import status_pb2 + +from typing import List, Optional, Tuple, Any, Dict + +from ._utils import raise_if_no_fast_crc32c +from google.cloud.storage.asyncio.async_read_object_stream import ( + _AsyncReadObjectStream, +) +from google.cloud.storage.asyncio.async_grpc_client import ( + AsyncGrpcClient, +) +from google.cloud.storage.asyncio.retry.bidi_stream_retry_manager import ( + _BidiStreamRetryManager, +) +from google.cloud.storage.asyncio.retry.reads_resumption_strategy import ( + _ReadResumptionStrategy, + _DownloadState, +) + +from io import BytesIO +from google.cloud import _storage_v2 +from google.cloud.storage._helpers import generate_random_56_bit_integer + +_MAX_READ_RANGES_PER_BIDI_READ_REQUEST = 100 +_BIDI_READ_REDIRECTED_TYPE_URL = ( + "type.googleapis.com/google.storage.v2.BidiReadObjectRedirectedError" +) + +logger = logging.getLogger(__name__) + + +def _is_read_retryable(exc): + """Predicate to determine if a read operation should be retried.""" + if isinstance( + exc, + ( + exceptions.InternalServerError, + exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, + exceptions.TooManyRequests, + ), + ): + return True + + if not isinstance(exc, exceptions.Aborted) or not exc.errors: + return False + + try: + grpc_error = exc.errors[0] + trailers = grpc_error.trailing_metadata() + if not trailers: + return False + + status_details_bin = next( + (v for k, v in trailers if k == "grpc-status-details-bin"), None + ) + + if not status_details_bin: + return False + + status_proto = status_pb2.Status() + status_proto.ParseFromString(status_details_bin) + return any( + detail.type_url == _BIDI_READ_REDIRECTED_TYPE_URL + for detail in status_proto.details + ) + except Exception as e: + logger.error(f"Error parsing status_details_bin: {e}") + return False + + +class AsyncMultiRangeDownloader: + """Provides an interface for downloading multiple ranges of a GCS ``Object`` + concurrently. + + Example usage: + + .. code-block:: python + + client = AsyncGrpcClient() + mrd = await AsyncMultiRangeDownloader.create_mrd( + client, bucket_name="chandrasiri-rs", object_name="test_open9" + ) + my_buff1 = open('my_fav_file.txt', 'wb') + my_buff2 = BytesIO() + my_buff3 = BytesIO() + my_buff4 = any_object_which_provides_BytesIO_like_interface() + await mrd.download_ranges( + [ + # (start_byte, bytes_to_read, writeable_buffer) + (0, 100, my_buff1), + (100, 20, my_buff2), + (200, 123, my_buff3), + (300, 789, my_buff4), + ] + ) + + # verify data in buffers... + assert my_buff2.getbuffer().nbytes == 20 + + + """ + + @classmethod + async def create_mrd( + cls, + client: AsyncGrpcClient, + bucket_name: str, + object_name: str, + generation: Optional[int] = None, + read_handle: Optional[_storage_v2.BidiReadHandle] = None, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + **kwargs, + ) -> AsyncMultiRangeDownloader: + """Initializes a MultiRangeDownloader and opens the underlying bidi-gRPC + object for reading. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient` + :param client: The asynchronous client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the bucket containing the object. + + :type object_name: str + :param object_name: The name of the object to be read. + + :type generation: int + :param generation: (Optional) If present, selects a specific + revision of this object. + + :type read_handle: _storage_v2.BidiReadHandle + :param read_handle: (Optional) An existing handle for reading the object. + If provided, opening the bidi-gRPC connection will be faster. + + :type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry` + :param retry_policy: (Optional) The retry policy to use for the ``open`` operation. + + :type metadata: List[Tuple[str, str]] + :param metadata: (Optional) The metadata to be sent with the ``open`` request. + + :rtype: :class:`~google.cloud.storage.asyncio.async_multi_range_downloader.AsyncMultiRangeDownloader` + :returns: An initialized AsyncMultiRangeDownloader instance for reading. + """ + mrd = cls( + client, + bucket_name, + object_name, + generation=generation, + read_handle=read_handle, + **kwargs, + ) + await mrd.open(retry_policy=retry_policy, metadata=metadata) + return mrd + + def __init__( + self, + client: AsyncGrpcClient, + bucket_name: str, + object_name: str, + generation: Optional[int] = None, + read_handle: Optional[_storage_v2.BidiReadHandle] = None, + **kwargs, + ) -> None: + """Constructor for AsyncMultiRangeDownloader, clients are not adviced to + use it directly. Instead it's adviced to use the classmethod `create_mrd`. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient` + :param client: The asynchronous client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the bucket containing the object. + + :type object_name: str + :param object_name: The name of the object to be read. + + :type generation: int + :param generation: (Optional) If present, selects a specific revision of + this object. + + :type read_handle: _storage_v2.BidiReadHandle + :param read_handle: (Optional) An existing read handle. + """ + if "generation_number" in kwargs: + if generation is not None: + raise TypeError( + "Cannot set both 'generation' and 'generation_number'. " + "Use 'generation' for new code." + ) + logger.warning( + "'generation_number' is deprecated and will be removed in a future " + "major release. Please use 'generation' instead." + ) + generation = kwargs.pop("generation_number") + + raise_if_no_fast_crc32c() + + self.client = client + self.bucket_name = bucket_name + self.object_name = object_name + self.generation = generation + self.read_handle: Optional[_storage_v2.BidiReadHandle] = read_handle + self.read_obj_str: Optional[_AsyncReadObjectStream] = None + self._is_stream_open: bool = False + self._routing_token: Optional[str] = None + self._read_id_to_writable_buffer_dict = {} + self._read_id_to_download_ranges_id = {} + self._download_ranges_id_to_pending_read_ids = {} + self.persisted_size: Optional[int] = None # updated after opening the stream + self._open_retries: int = 0 + + async def __aenter__(self): + """Opens the underlying bidi-gRPC connection to read from the object.""" + await self.open() + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + """Closes the underlying bidi-gRPC connection.""" + if self.is_stream_open: + await self.close() + + def _on_open_error(self, exc): + """Extracts routing token and read handle on redirect error during open.""" + logger.warning(f"Error occurred while opening MRD: {exc}") + routing_token, read_handle = _handle_redirect(exc) + if routing_token: + self._routing_token = routing_token + if read_handle: + self.read_handle = read_handle + + async def open( + self, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Opens the bidi-gRPC connection to read from the object.""" + if self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is already open") + + if retry_policy is None: + def on_error_wrapper(exc): + self._open_retries += 1 + self._on_open_error(exc) + + retry_policy = AsyncRetry( + predicate=_is_read_retryable, on_error=on_error_wrapper + ) + else: + original_on_error = retry_policy._on_error + + def combined_on_error(exc): + self._open_retries += 1 + self._on_open_error(exc) + if original_on_error: + original_on_error(exc) + + retry_policy = AsyncRetry( + predicate=_is_read_retryable, + initial=retry_policy._initial, + maximum=retry_policy._maximum, + multiplier=retry_policy._multiplier, + deadline=retry_policy._deadline, + on_error=combined_on_error, + ) + + async def _do_open(): + current_metadata = list(metadata) if metadata else [] + + # Cleanup stream from previous failed attempt, if any. + if self.read_obj_str: + if self.read_obj_str.is_stream_open: + try: + await self.read_obj_str.close() + except exceptions.GoogleAPICallError as e: + logger.warning( + f"Failed to close existing stream during resumption: {e}" + ) + self.read_obj_str = None + self._is_stream_open = False + + self.read_obj_str = _AsyncReadObjectStream( + client=self.client.grpc_client, + bucket_name=self.bucket_name, + object_name=self.object_name, + generation_number=self.generation, + read_handle=self.read_handle, + ) + + if self._routing_token: + current_metadata.append( + ("x-goog-request-params", f"routing_token={self._routing_token}") + ) + self._routing_token = None + + await self.read_obj_str.open( + metadata=current_metadata if current_metadata else None + ) + + if self.read_obj_str.generation_number: + self.generation = self.read_obj_str.generation_number + if self.read_obj_str.read_handle: + self.read_handle = self.read_obj_str.read_handle + if self.read_obj_str.persisted_size is not None: + self.persisted_size = self.read_obj_str.persisted_size + + self._is_stream_open = True + + await retry_policy(_do_open)() + + async def download_ranges( + self, + read_ranges: List[Tuple[int, int, BytesIO]], + lock: asyncio.Lock = None, + retry_policy: Optional[AsyncRetry] = None, + metadata: Optional[List[Tuple[str, str]]] = None, + ) -> None: + """Downloads multiple byte ranges from the object into the buffers + provided by user with automatic retries. + + :type read_ranges: List[Tuple[int, int, "BytesIO"]] + :param read_ranges: A list of tuples, where each tuple represents a + combination of byte_range and writeable buffer in format - + (`start_byte`, `bytes_to_read`, `writeable_buffer`). Buffer has + to be provided by the user, and user has to make sure appropriate + memory is available in the application to avoid out-of-memory crash. + + Special cases: + if the value of `bytes_to_read` is 0, it'll be interpreted as + download all contents until the end of the file from `start_byte`. + Examples: + * (0, 0, buffer) : downloads 0 to end , i.e. entire object. + * (100, 0, buffer) : downloads from 100 to end. + + + :type lock: asyncio.Lock + :param lock: (Optional) An asyncio lock to synchronize sends and recvs + on the underlying bidi-GRPC stream. This is required when multiple + coroutines are calling this method concurrently. + + i.e. Example usage with multiple coroutines: + + ``` + lock = asyncio.Lock() + task1 = asyncio.create_task(mrd.download_ranges(ranges1, lock)) + task2 = asyncio.create_task(mrd.download_ranges(ranges2, lock)) + await asyncio.gather(task1, task2) + + ``` + + If user want to call this method serially from multiple coroutines, + then providing a lock is not necessary. + + ``` + await mrd.download_ranges(ranges1) + await mrd.download_ranges(ranges2) + + # ... some other code code... + + ``` + + :type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry` + :param retry_policy: (Optional) The retry policy to use for the operation. + + :raises ValueError: if the underlying bidi-GRPC stream is not open. + :raises ValueError: if the length of read_ranges is more than 1000. + :raises DataCorruption: if a checksum mismatch is detected while reading data. + + """ + + if len(read_ranges) > 1000: + raise ValueError( + "Invalid input - length of read_ranges cannot be more than 1000" + ) + + if not self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is not open") + + if lock is None: + lock = asyncio.Lock() + + if retry_policy is None: + retry_policy = AsyncRetry(predicate=_is_read_retryable) + + # Initialize Global State for Retry Strategy + download_states = {} + for read_range in read_ranges: + read_id = generate_random_56_bit_integer() + download_states[read_id] = _DownloadState( + initial_offset=read_range[0], + initial_length=read_range[1], + user_buffer=read_range[2], + ) + + initial_state = { + "download_states": download_states, + "read_handle": self.read_handle, + "routing_token": None, + } + + # Track attempts to manage stream reuse + attempt_count = 0 + + def send_ranges_and_get_bytes( + requests: List[_storage_v2.ReadRange], + state: Dict[str, Any], + metadata: Optional[List[Tuple[str, str]]] = None, + ): + async def generator(): + nonlocal attempt_count + attempt_count += 1 + + if attempt_count > 1: + logger.info( + f"Resuming download (attempt {attempt_count}) for {len(requests)} ranges." + ) + + async with lock: + current_handle = state.get("read_handle") + current_token = state.get("routing_token") + + # We reopen if it's a redirect (token exists) OR if this is a retry + # (not first attempt). This prevents trying to send data on a dead + # stream from a previous failed attempt. + should_reopen = ( + (attempt_count > 1) + or (current_token is not None) + or (metadata is not None) + ) + + if should_reopen: + if current_token: + logger.info( + f"Re-opening stream with routing token: {current_token}" + ) + + self.read_obj_str = _AsyncReadObjectStream( + client=self.client.grpc_client, + bucket_name=self.bucket_name, + object_name=self.object_name, + generation_number=self.generation, + read_handle=current_handle, + ) + + # Inject routing_token into metadata if present + current_metadata = list(metadata) if metadata else [] + if current_token: + current_metadata.append( + ( + "x-goog-request-params", + f"routing_token={current_token}", + ) + ) + + await self.read_obj_str.open( + metadata=current_metadata if current_metadata else None + ) + self._is_stream_open = True + + pending_read_ids = {r.read_id for r in requests} + + # Send Requests + for i in range( + 0, len(requests), _MAX_READ_RANGES_PER_BIDI_READ_REQUEST + ): + batch = requests[i : i + _MAX_READ_RANGES_PER_BIDI_READ_REQUEST] + await self.read_obj_str.send( + _storage_v2.BidiReadObjectRequest(read_ranges=batch) + ) + + while pending_read_ids: + response = await self.read_obj_str.recv() + if response is None: + break + if response.object_data_ranges: + for data_range in response.object_data_ranges: + if data_range.range_end: + pending_read_ids.discard( + data_range.read_range.read_id + ) + yield response + + return generator() + + strategy = _ReadResumptionStrategy() + retry_manager = _BidiStreamRetryManager( + strategy, lambda r, s: send_ranges_and_get_bytes(r, s, metadata=metadata) + ) + + await retry_manager.execute(initial_state, retry_policy) + + if initial_state.get("read_handle"): + self.read_handle = initial_state["read_handle"] + + async def close(self): + """ + Closes the underlying bidi-gRPC connection. + """ + if not self._is_stream_open: + raise ValueError("Underlying bidi-gRPC stream is not open") + + if self.read_obj_str: + await self.read_obj_str.close() + self.read_obj_str = None + self._is_stream_open = False + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_read_object_stream.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_read_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..bde6c16518c11e88893f109ba2f8967c8e55664e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_read_object_stream.py @@ -0,0 +1,188 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import List, Optional, Tuple +from google.cloud import _storage_v2 +from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient +from google.cloud.storage.asyncio.async_abstract_object_stream import ( + _AsyncAbstractObjectStream, +) + +from google.api_core.bidi_async import AsyncBidiRpc + + +class _AsyncReadObjectStream(_AsyncAbstractObjectStream): + """Class representing a gRPC bidi-stream for reading data from a GCS ``Object``. + + This class provides a unix socket-like interface to a GCS ``Object``, with + methods like ``open``, ``close``, ``send``, and ``recv``. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient.grpc_client` + :param client: async grpc client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the GCS ``bucket`` containing the object. + + :type object_name: str + :param object_name: The name of the GCS ``object`` to be read. + + :type generation_number: int + :param generation_number: (Optional) If present, selects a specific revision of + this object. + + :type read_handle: _storage_v2.BidiReadHandle + :param read_handle: (Optional) An existing handle for reading the object. + If provided, opening the bidi-gRPC connection will be faster. + """ + + def __init__( + self, + client: AsyncGrpcClient.grpc_client, + bucket_name: str, + object_name: str, + generation_number: Optional[int] = None, + read_handle: Optional[_storage_v2.BidiReadHandle] = None, + ) -> None: + if client is None: + raise ValueError("client must be provided") + if bucket_name is None: + raise ValueError("bucket_name must be provided") + if object_name is None: + raise ValueError("object_name must be provided") + + super().__init__( + bucket_name=bucket_name, + object_name=object_name, + generation_number=generation_number, + ) + self.client: AsyncGrpcClient.grpc_client = client + self.read_handle: Optional[_storage_v2.BidiReadHandle] = read_handle + + self._full_bucket_name = f"projects/_/buckets/{self.bucket_name}" + + self.rpc = self.client._client._transport._wrapped_methods[ + self.client._client._transport.bidi_read_object + ] + self.metadata = (("x-goog-request-params", f"bucket={self._full_bucket_name}"),) + self.socket_like_rpc: Optional[AsyncBidiRpc] = None + self._is_stream_open: bool = False + self.persisted_size: Optional[int] = None + + async def open(self, metadata: Optional[List[Tuple[str, str]]] = None) -> None: + """Opens the bidi-gRPC connection to read from the object. + + This method sends an initial request to start the stream and receives + the first response containing metadata and a read handle. + + Args: + metadata (Optional[List[Tuple[str, str]]]): Additional metadata + to send with the initial stream request, e.g., for routing tokens. + """ + if self._is_stream_open: + raise ValueError("Stream is already open") + + read_handle = self.read_handle if self.read_handle else None + + read_object_spec = _storage_v2.BidiReadObjectSpec( + bucket=self._full_bucket_name, + object=self.object_name, + generation=self.generation_number if self.generation_number else None, + read_handle=read_handle, + ) + self.first_bidi_read_req = _storage_v2.BidiReadObjectRequest( + read_object_spec=read_object_spec + ) + + # Build the x-goog-request-params header + request_params = [f"bucket={self._full_bucket_name}"] + other_metadata = [] + if metadata: + for key, value in metadata: + if key == "x-goog-request-params": + request_params.append(value) + else: + other_metadata.append((key, value)) + + current_metadata = other_metadata + current_metadata.append(("x-goog-request-params", "&".join(request_params))) + + self.socket_like_rpc = AsyncBidiRpc( + self.rpc, + initial_request=self.first_bidi_read_req, + metadata=current_metadata, + ) + await self.socket_like_rpc.open() # this is actually 1 send + response = await self.socket_like_rpc.recv() + # populated only in the first response of bidi-stream and when opened + # without using `read_handle` + if hasattr(response, "metadata") and response.metadata: + if self.generation_number is None: + self.generation_number = response.metadata.generation + # update persisted size + self.persisted_size = response.metadata.size + + if response and response.read_handle: + self.read_handle = response.read_handle + + self._is_stream_open = True + + async def close(self) -> None: + """Closes the bidi-gRPC connection.""" + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.requests_done() + await self.socket_like_rpc.close() + self._is_stream_open = False + + async def requests_done(self): + """Signals that all requests have been sent.""" + + await self.socket_like_rpc.send(None) + await self.socket_like_rpc.recv() + + async def send( + self, bidi_read_object_request: _storage_v2.BidiReadObjectRequest + ) -> None: + """Sends a request message on the stream. + + Args: + bidi_read_object_request (:class:`~google.cloud._storage_v2.types.BidiReadObjectRequest`): + The request message to send. This is typically used to specify + the read offset and limit. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.socket_like_rpc.send(bidi_read_object_request) + + async def recv(self) -> _storage_v2.BidiReadObjectResponse: + """Receives a response from the stream. + + This method waits for the next message from the server, which could + contain object data or metadata. + + Returns: + :class:`~google.cloud._storage_v2.types.BidiReadObjectResponse`: + The response message from the server. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + response = await self.socket_like_rpc.recv() + # Update read_handle if present in response + if response and response.read_handle: + self.read_handle = response.read_handle + return response + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_write_object_stream.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_write_object_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..4729cfd2020ee0c8f71788248808ba8726693e69 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google/cloud/storage/asyncio/async_write_object_stream.py @@ -0,0 +1,239 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import List, Optional, Tuple +import grpc +from google.cloud import _storage_v2 +from google.cloud.storage.asyncio import _utils +from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient +from google.cloud.storage.asyncio.async_abstract_object_stream import ( + _AsyncAbstractObjectStream, +) +from google.api_core.bidi_async import AsyncBidiRpc + + +class _AsyncWriteObjectStream(_AsyncAbstractObjectStream): + """Class representing a gRPC bidi-stream for writing data from a GCS + ``Appendable Object``. + + This class provides a unix socket-like interface to a GCS ``Object``, with + methods like ``open``, ``close``, ``send``, and ``recv``. + + :type client: :class:`~google.cloud.storage.asyncio.async_grpc_client.AsyncGrpcClient.grpc_client` + :param client: async grpc client to use for making API requests. + + :type bucket_name: str + :param bucket_name: The name of the GCS ``bucket`` containing the object. + + :type object_name: str + :param object_name: The name of the GCS ``Appendable Object`` to be write. + + :type generation_number: int + :param generation_number: (Optional) If present, creates writer for that + specific revision of that object. Use this to append data to an + existing Appendable Object. + + Setting to ``0`` makes the `writer.open()` succeed only if + object doesn't exist in the bucket (useful for not accidentally + overwriting existing objects). + + Warning: If `None`, a new object is created. If an object with the + same name already exists, it will be overwritten the moment + `writer.open()` is called. + + :type write_handle: _storage_v2.BidiWriteHandle + :param write_handle: (Optional) An existing handle for writing the object. + If provided, opening the bidi-gRPC connection will be faster. + """ + + def __init__( + self, + client: AsyncGrpcClient.grpc_client, + bucket_name: str, + object_name: str, + generation_number: Optional[int] = None, # None means new object + write_handle: Optional[_storage_v2.BidiWriteHandle] = None, + routing_token: Optional[str] = None, + ) -> None: + if client is None: + raise ValueError("client must be provided") + if bucket_name is None: + raise ValueError("bucket_name must be provided") + if object_name is None: + raise ValueError("object_name must be provided") + + super().__init__( + bucket_name=bucket_name, + object_name=object_name, + generation_number=generation_number, + ) + self.client: AsyncGrpcClient.grpc_client = client + self.write_handle: Optional[_storage_v2.BidiWriteHandle] = write_handle + self.routing_token: Optional[str] = routing_token + + self._full_bucket_name = f"projects/_/buckets/{self.bucket_name}" + + self.rpc = self.client._client._transport._wrapped_methods[ + self.client._client._transport.bidi_write_object + ] + + self.metadata = (("x-goog-request-params", f"bucket={self._full_bucket_name}"),) + self.socket_like_rpc: Optional[AsyncBidiRpc] = None + self._is_stream_open: bool = False + self.first_bidi_write_req = None + self.persisted_size = 0 + self.object_resource: Optional[_storage_v2.Object] = None + + async def open(self, metadata: Optional[List[Tuple[str, str]]] = None) -> None: + """ + Opens the bidi-gRPC connection to write to the object. + + This method sends an initial request to start the stream and receives + the first response containing metadata and a write handle. + + :rtype: None + :raises ValueError: If the stream is already open. + :raises google.api_core.exceptions.FailedPrecondition: + if `generation_number` is 0 and object already exists. + """ + if self._is_stream_open: + raise ValueError("Stream is already open") + + # Create a new object or overwrite existing one if generation_number + # is None. This makes it consistent with GCS JSON API behavior. + # Created object type would be Appendable Object. + # if `generation_number` == 0 new object will be created only if there + # isn't any existing object. + if self.generation_number is None or self.generation_number == 0: + self.first_bidi_write_req = _storage_v2.BidiWriteObjectRequest( + write_object_spec=_storage_v2.WriteObjectSpec( + resource=_storage_v2.Object( + name=self.object_name, bucket=self._full_bucket_name + ), + appendable=True, + if_generation_match=self.generation_number, + ), + ) + else: + self.first_bidi_write_req = _storage_v2.BidiWriteObjectRequest( + append_object_spec=_storage_v2.AppendObjectSpec( + bucket=self._full_bucket_name, + object=self.object_name, + generation=self.generation_number, + write_handle=self.write_handle if self.write_handle else None, + routing_token=self.routing_token if self.routing_token else None, + ), + ) + + request_param_values = [f"bucket={self._full_bucket_name}"] + final_metadata = [] + if metadata: + for key, value in metadata: + if key == "x-goog-request-params": + request_param_values.append(value) + else: + final_metadata.append((key, value)) + + final_metadata.append(("x-goog-request-params", "&".join(request_param_values))) + + self.socket_like_rpc = AsyncBidiRpc( + self.rpc, + initial_request=self.first_bidi_write_req, + metadata=final_metadata, + ) + + await self.socket_like_rpc.open() # this is actually 1 send + response = await self.socket_like_rpc.recv() + self._is_stream_open = True + + if response.persisted_size: + self.persisted_size = response.persisted_size + + if response.resource: + if not response.resource.size: + # Appending to a 0 byte appendable object. + self.persisted_size = 0 + else: + self.persisted_size = response.resource.size + + self.generation_number = response.resource.generation + + if response.write_handle: + self.write_handle = response.write_handle + + async def close(self) -> None: + """Closes the bidi-gRPC connection.""" + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.requests_done() + await self.socket_like_rpc.close() + self._is_stream_open = False + + async def requests_done(self): + """Signals that all requests have been sent.""" + await self.socket_like_rpc.send(None) + + # The server may send a final "EOF" response immediately, or it may + # first send an intermediate response followed by the EOF response depending on whether the object was finalized or not. + first_resp = await self.socket_like_rpc.recv() + _utils.update_write_handle_if_exists(self, first_resp) + + if first_resp != grpc.aio.EOF: + # this persisted_size will not be upto date., also what if response + # doesn't have persisted_size? , it'll throw error. + if hasattr(first_resp, "persisted_size"): + self.persisted_size = first_resp.persisted_size + second_resp = await self.socket_like_rpc.recv() + assert second_resp == grpc.aio.EOF + + async def send( + self, bidi_write_object_request: _storage_v2.BidiWriteObjectRequest + ) -> None: + """Sends a request message on the stream. + + Args: + bidi_write_object_request (:class:`~google.cloud._storage_v2.types.BidiReadObjectRequest`): + The request message to send. This is typically used to specify + the read offset and limit. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + await self.socket_like_rpc.send(bidi_write_object_request) + + async def recv(self) -> _storage_v2.BidiWriteObjectResponse: + """Receives a response from the stream. + + This method waits for the next message from the server, which could + contain object data or metadata. + + Returns: + :class:`~google.cloud._storage_v2.types.BidiWriteObjectResponse`: + The response message from the server. + """ + if not self._is_stream_open: + raise ValueError("Stream is not open") + response = await self.socket_like_rpc.recv() + # Update write_handle if present in response + if response: + if response.write_handle: + self.write_handle = response.write_handle + if response.persisted_size is not None: + self.persisted_size = response.persisted_size + if response.resource and response.resource.size: + self.persisted_size = response.resource.size + return response + + @property + def is_stream_open(self) -> bool: + return self._is_stream_open